在 REST 服务中使用 ContainerResponse 过滤器时,GET 工作但 POST 不工作?

Posted

技术标签:

【中文标题】在 REST 服务中使用 ContainerResponse 过滤器时,GET 工作但 POST 不工作?【英文标题】:GET is working but POST not when using ContainerResponse filter in REST-services? 【发布时间】:2013-01-24 17:52:56 【问题描述】:

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

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

网络服务

@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);
            
        );
    ;

【问题讨论】:

【参考方案1】:

这可能是因为某些浏览器(如 chrome)沙箱 localhost。尝试插入您的 ip 而不是 localhost,看看是否有任何作用。

【讨论】:

它没有帮助:(顺便说一句,我认识到输入字段的值在这里未定义:console.log('---------formToJSON------- ---'); console.log($('#username').val());---->undefined console.log($('#firstName').val());---- >undefined console.log($('#lastName').val()); ---->undefined 我的错误,id 丢失了,但仍然是同样的问题。 id="firstName"...接缝它甚至从未调用过 Web 服务,我添加了 system.out.println 以在 Web 服务中创建方法,但从未看到它。

以上是关于在 REST 服务中使用 ContainerResponse 过滤器时,GET 工作但 POST 不工作?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 SoapUI 中测试使用 JWT 的 REST 服务?

在angularjs中使用来自rest服务的JSON对象

在 Spring Boot 的 DeferredResult REST 方法中使用 Semaphore 服务

如何在 snappy-data sql 数据库中使用 REST 服务

如何在 Rest 中暴露服务? [关闭]

如何在 PowerShell 中使用 Rest API 创建服务更改