简体   繁体   中英

Injection of HttpServletRequest in Jersey POST handler

Consider this case:-
I am injecting HttpServletRequest in a Rest Service like

@Context
HttpServletRequest request;

And use it in a method like:-

@GET
@Path("/simple")
public Response handleSimple() {
    System.out.println(request.getParameter("myname"));
    return Response.status(200).entity("hello.....").build();

}

This works fine but when I try to send it through POST method and replace the @GET by @POST annotation, I get the parameter value null.
Please suggest me where I am mistaking.

You do not need to get your parameters etc out of the request. The JAX-RS impl. handles that for you.

You have to use the parameter annotations to map your parameters to method parameters. Casting converting etc. is done automaticly.

Here your method using three differnt ways to map your parameter:

// As Pathparameter
@POST
@Path("/simple/{myname}")
public Response handleSimple(@PathParam("myname") String myName) {
    System.out.println(myName);
    return Response.status(200).entity("hello.....").build();
}

// As query parameter
@POST
@Path("/simple")
public Response handleSimple(@QueryParam("myname") String myName) {
    System.out.println(myName);
    return Response.status(200).entity("hello.....").build();
}

// As form parameter
@POST
@Path("/simple")
public Response handleSimple(@FormParam("myname") String myName) {
    System.out.println(myName);
    return Response.status(200).entity("hello.....").build();
}

Documentation about JAX-RS Annotations from Jersey you can find here: https://jersey.java.net/documentation/latest/jaxrs-resources.html

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