在REST服务中使用ContainerResponse筛选器时,GET正在工作,但POST不工作

GET is working but POST not when using ContainerResponse filter in REST-services?

本文关键字:工作 POST GET 服务 REST ContainerResponse 筛选      更新时间:2023-09-26

我开始将我的软件从Primefaces更改为HTML5客户端-服务器解决方案。

问题:同源策略在使用POST时失败,但在使用GET时有效。

WEB服务

@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Users entity) {
    super.create(entity);
}
@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Users> findAll() {
    return super.findAll();
}

过滤器

public class CrossOriginResourceSharingFilter implements ContainerResponseFilter {

public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    response.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
    response.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    response.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "content-type");
    return response;
}

}

WEB.XML

<init-param>
        <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
        <param-value>entity.CrossOriginResourceSharingFilter</param-value>
    </init-param>

客户

 <form id="register-form"> 

                    <div class="register-form-block">
                        <input type="text" value='Your first name' name="firstName" id="firstName"/>
                    </div> 

                    <div class="register-form-block">
                        <input type="text" value='Your surname' name="lastName" id="lastName" onclick="this.value = ('')" />
                    </div>
                    <div class="register-form-block">
                        <input type="text" value='Username' name="username" id="username" onclick="this.value = ('')"/>
                    </div>
                    <div class="register-form-block">
                        <input type="password" value='Password' name="password" id="password" onclick="this.value = ('')"/>
                    </div>
                    <div class="register-form-block">
                        <input type="password" value='Password again' name="passwordagain" onclick="this.value = ('')"/>
                    </div>
                    <button type="submit" class="btn btn-primary" id="btnAddUser" onclick="foo()">Register</button>
                </form>
<script>
       function foo(){
    alert('Button pressed');
        $.ajax({
            type: 'POST',
            contentType: 'application/json',
            url: 'http://127.0.0.1:8080/testsoft/webresources/entity.users/',
            dataType: "json",
            data: formToJSON(),
            success: function(data, textStatus, jqXHR) {
                alert('User created successfully');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('addUser error: ' + textStatus +' ERROR:'+ errorThrown);
            }
        });
    };

        function formToJSON() {
        alert($('#username').val());
                return JSON.stringify({
                        "username": $('#username').val(),
                        "firstName": $('#firstName').val(),
                        "lastName": $('#lastName').val(),
                        "password": $('#password').val(),
                        
                    });
        }
    </script>

错误

 Failed to load resource: the server responded with a status of 500 (Internal Server Error) (22:49:54:618 | error, network)
  at http://localhost:8080/testsoft/webresources/entity.users/
XMLHttpRequest cannot load http://localhost:8080/testsoft/webresources/entity.users/. Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin. (22:49:54:618 | error, javascript)

另一个解决方案不起作用,根本没有错误

function foo(){
    alert('Button pressed');
        console.log('#####################addUser################################');
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://127.0.0.1:8080/testsoft/webresources/entity.users/",
            dataType: "json",
            data: {"username":"UllaUser","password":"testpwd","firstName":"Unto","lastName":"lastnameson","nickName":null,"isAdmin":false,"isCustomer":false,"isGuest":false,"isActive":true,"isInvemailsent":false,"isInvCardSent":null,"inSaveDateSent":false,"isThankCardSent":false,"weddingAsUser":false,"hasGuestUsers":false,"userRole":null,"email":null,"createDate":null,"turnout":null,"lastUpdated":1360240740000,"secretQuestion":null,"secretAnswer":null,"weddingWeddingId":null,"languageLanguageId":null,"invitationInvitationId":null,"emailEmailId":null,"addressAddressId":null},
        success: function(data){  
    // we have the response  
            alert("Server said:'n '" + data.username + "'");
            },
            error: function(data) {
    alert('addUser error: ' + data.username);
            }
        });
    };

这可能是因为一些浏览器(如chrome)沙盒localhost。试着插入你的ip而不是localhost,看看这是否有什么作用。