从Javascript客户端将POST JSON POST到Atmosphere框架中的Jersey资源

时间:2013-03-08 20:00:09

标签: java javascript json jersey atmosphere

我一直在谷歌搜索并尝试让它工作数小时...问题是服务器没有收到JSON的数据,而是文本。这是POJO

package my.package;

import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement
    public class TestConfig {

        private String firmID;
        private String traderID;
        private String userID;

        public TestConfig() {};
    ...
    }

包含以下内容的Javascript客户端

    function callbackForTest(response) {
        console.log("Call to callbackForTest");
        if (response.state == "opening" && response.status == 200) {

            //push request data
            if (connectedEndpoint[0] == null) {
                console.log("[DEBUG] Connected endpoint for " + value + "is null!");
                //disable button
                $(value).attr('disabled','');
                $.atmosphere.unsubscribe();
                return false;
            }

            // push ( POST ) 
            connectedEndpoint[0].push(JSON.stringify(
                    {
                        operation       :   "RUN",
                        firmID          :   $('#firmID').val(),
                        userID          :   $('#userID').val(),
                        traderID        :   $('#traderID').val(),
                        protocol        :   $('#protocol').val(),
                        group1          :   
                    }
                ));
        }
    }

    function subscribeUrl(jobName, call, transport) {
        var location = subscribePath + jobName.id;
        return subscribeAtmosphere(location, call, transport);
    }

    function globalCallback(response) {
        if (response.state != "messageReceived") {
            return;
        }
    }

    function subscribeAtmosphere(location, call, transport) {
        var rq = $.atmosphere.subscribe(location, globalCallback, $.atmosphere.request = {
            logLevel : 'debug',
            transport : transport,
            enableProtocol: true,
            callback : call,
            contentType : 'application/json'
        });
        return rq;
    }

    function sendMessage(connectedEndpoint, jobName) {
        var phrase = $('#msg-' + jobName).val();
        connectedEndpoint.push({data: "message=" + phrase});
    }


    // Run Test handlers
    $("input[name='runButtons']").each(function(index, value){
        $(value).click(function(){

            //disable button
            $(value).attr('disabled','disabled');

            // connect (GET)
            connectedEndpoint[index] = subscribeUrl(value, callbackForTest, transport);
            });
        });

我已经包含了此屏幕截图中显示的库:

LIBS

这是我的web.xml(部分内容)

           com.sun.jersey.api.json.POJOMappingFeature            真正

泽西岛资源

@Path("/subscribe/{topic}")
@Produces({MediaType.APPLICATION_JSON, "text/html;charset=ISO-8859-1", MediaType.TEXT_PLAIN})
public class Subscriber {

    private static final Logger LOG = Logger.getLogger(Subscriber.class);

    @PathParam("topic")
    private Broadcaster topic;

    @GET
    public SuspendResponse<String> subscribe() {
        LOG.debug("GET - OnSubscribe to topic");
        SuspendResponse<String> sr = new SuspendResponse.SuspendResponseBuilder<String>().broadcaster(topic).outputComments(true)
                .addListener(new EventsLogger()).build();

        return sr;
    }

    @POST
    @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML})
    @Broadcast
    public Broadcastable publish( TestConfig t) {
        LOG.debug("POST");
        String s = t.getFirmID();
        return new Broadcastable(s, "", topic);
    }

我可以订阅好了。当我尝试推送到服务器时,我得到了这个例外:

A message body reader for Java class com.mx.sailcertifier.TestConfig, and Java type class com.mx.sailcertifier.TestConfig, and MIME media type text/plain was not found.

如果我将内容类型设置为application/json,为什么要发送纯文本?获取Jersey资源以读取JSON的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

我终于有了两个改变:

查看示例here后,我将此init-param添加到AtmosphereServlet中的web.xml以解决Tomcat中的text/plain问题:

<init-param>
     <param-name>org.atmosphere.websocket.messageContentType</param-name>
     <param-value>application/json</param-value>
</init-param>

我没有在Atmosphere文档中看到过任何记录。它本来可以节省很多时间,但在文档方面,API很遗憾是杂乱无章的。

另外,我需要使用jersey-bundle jar确保包含泽西相关的所有内容,包括jersey-json.jar。在那之后,它工作了!希望这有助于其他可能遇到相同或类似问题的人。