I have been through this link . but this did not helped me out.
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 is: /test/post1
My ajax call:
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);
});
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);
}
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
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.
You can simply take Post dat as a string and then you can parse it using JSONObject.
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/post1")
public Response postStrMsg(String msg) {
String output = "POST:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@XMLRootElement是实现此目的的方法,因为必须先对json进行封送处理,然后才能使用其任何元素。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.