如何使带有JSON数据的post ajax调用到Jersey休息服务? [英] How to make post ajax call with JSON data to Jersey rest service?

查看:69
本文介绍了如何使带有JSON数据的post ajax调用到Jersey休息服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过此链接.但这并没有帮助我.

I have been through this link. but this did not helped me out.

我正在使用jersey lib v1.17.1. 我的球衣休息服务:

I am using jersey lib v1.17.1. My jersey rest service:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/post1")
public ResponseBean post1(@QueryParam("param1")String param1)
{
    return ResponseFactory.createResponse(param1, "TEST", "TEST", null, true);
}

URL是:/test/post1

我的ajax呼叫:

var d = {"param1":"just a dummy data"};
    $.ajax({
        type : "POST",
        url : "http://localhost:7070/scl/rs/test/post1",
        contentType :"application/json; charSet=UTF-8",
        data : d,
        dataType : "json"
    })
    .done(function(data){
        console.log(data);
    })
    .fail(function(data){
        console.log(data);
    });

它打到了我的休息服务,但是作为param1,我总是得到空值.另一种解决方案是添加带有@XMLRootElement的JavaBean,它将把Java对象封送/解组到json,反之亦然,但是我不想使用它.
是否有任何方法可以发布数据并使用诸如@QueryParam之类的适当注释接收数据? 请帮助

It hits to my rest service but as param1 I am alway getting null value. The alternate solution is to add JavaBean with @XMLRootElement which will marshal/unmarshal the java object to json and vice versa, but I do not want to use this.
Is there any way to post data and receive it using appropriate annotation like @QueryParam or something like that ? Please help

推荐答案

您的服务器端代码应如下所示:

Your server-side code should be like this:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/post1")
public ResponseBean post1(Data param1)
{
    return ResponseFactory.createResponse(param1, "TEST", "TEST", null, true);
}

其中,Data是一个用@XmlRootElement注释的(POJO)类,它对应于客户端将发送的JSON数据(即,具有带有getter和setter的param1字段). JAX-RS实现会将POST的正文解组为Data的实例.

where Data is a (POJO) class annotated with @XmlRootElement and corresponds to the JSON data what your client will send (ie, have a param1 field with getter and setter). The JAX-RS implementation will unmarshall the body of the POST into an instance of Data.

@QueryParam批注用于在(通常)GET请求中检索查询参数.查询参数是问号(?)之后的参数.例如:当处理以下请求时,@QueryParam("start") String start将映射为1:GET http://foo.com/bar?start=1,但这不是您要使用的AFAICS.

@QueryParam annotation is used ot retrieve the query params in a (usually) GET requests. Query params are the params after the question mark (?). Eg: @QueryParam("start") String start will map be set to 1 when the following request is processed: GET http://foo.com/bar?start=1, but this is not what you're doing in your case, AFAICS.

这篇关于如何使带有JSON数据的post ajax调用到Jersey休息服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆