简体   繁体   中英

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?

If you will follow jersey example project you must have application class extending ResourceConfig which should include your class and JacksonFeature class

 public class MyApplication extends ResourceConfig { public MyApplication() { super( EmptyArrayResource.class, NonJaxbBeanResource.class, CombinedAnnotationResource.class, // register Jackson ObjectMapper resolver MyObjectMapperProvider.class, ExceptionMappingTestResource.class, JacksonFeature.class );
  • In your Appplication, instantiate your GetMessageDAO class (for that matter any DAO class) upfront and pass it as a constructor parameter of "1st Java class".
  • In constructor of "1st Java class", set GetMessageDAO as field variable
  • In method status , access the field variable.

Add jersey-media-json-jackson denepndency to your project.

It is support module for JSON Jackson.

Have you considered to use the @FormParam or the @BeanForm annotation:

@POST
public String delivery(@FormParam("deliveryAddress") String deliveryAddress,
                       @FormParam("quantity") Long quantity) 
{
    return "Form parameters are " +
            "[deliveryAddress=" + deliveryAddress + ", quantity=" + quantity + "]";
}

You need to set the correct Content-Type to mimic the form submission action. \

To set the form parameters you use the -d flag:

curl -X POST -H 'Content-Type:application/x-www-form-urlencoded' \
   -d 'deliveryAddress=Street 1A&quantity=5' \
   http://localhost:8080/application/delivery

Output:

Form parameters are [deliveryAddress=Street 1A, quantity=5]

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM