Search code examples
javajsonrestjersey

Rest service adding an extra parameter throws error


I am trying to create a REST service with body. When I try to add an extra parameter(to read POST body), the rest request does not get invoked.

1st JAVA CLASS:

@Path("{module}/{messageKey}")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response status(final @Context HttpServletRequest request, @PathParam("module") final String module, @PathParam("messageKey") final String messageKey, final GetMessageDAO dao) {
        String messageText = "";
System.out.println(messageKey);
        CacheControl cacheControl = new CacheControl();
        cacheControl.setNoCache(true);
        return Response.ok(String.valueOf(messageText)).cacheControl(cacheControl).build();
    }

2nd Java Class:

public class GetMessageDAO {

    @JsonProperty("args")
    private String args;

    public String getArgs() {
        return args;
    }

    public void setArgs(String args) {
        this.args = args;
    }
}

JS Call:

    new Ajax.Request(
          '/ecmws/resources/message/gp/transactionManager.confirm.affected_calc_req', 
          {
            method: 'post',
            parameter: {args: "abc"},
data: {args: "abc"},
            contentType: 'application/json;charset=UTF-8',
            charset: 'UTF-8',
            async: false});

The moment I remove the last parameter from 1st Java class, it works fine but I need to read POST body as well and hence the problem.

I have jersey-core, jersey-json, jersey-client, jersey-server, jackson-mapper all in classpath.

Can you please suggest what I am missing?


Solution

  • Problem is NOT with your Jersey Controller, but it is with the way you are sending data in your AJAX call.

    If you make a postman call or curl your request, you will probably not have any issues and method even with GetMessageDAO will be invoked as expected. But making an ajax call from browser will fail.

    curl --request POST 'http://localhost:8080/todos/hello/world' --header 'Content-Type: application/json' --data-raw '{"args":"b"}' 
    

    To fix this issue change your line

    data: {args: "abc"},
    

    to

    data: JSON.stringify({args: 'abc'}),
    

    FURTHER (to verify):

    If you check your browser network request, data without JSON.stringify is sent as

    args=abc
    

    but chaning it to JSON.stringify changes it to JSON String and you will be see data being sent is:

    {"args": "abc"}
    

    Which then can be marshalled to GetMessageDAO class instance.