How to make post ajax call with JSON data to Jersey rest service?

你离开我真会死。 提交于 2021-01-28 07:00:30

问题


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


回答1:


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.




回答2:


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();
    }



回答3:


the @XMLRootElement is the way to do that since the json must be unmarshaled before you can use any of its elements.



来源:https://stackoverflow.com/questions/21699745/how-to-make-post-ajax-call-with-json-data-to-jersey-rest-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!