Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access POST parameters in HttpServletRequest?

I've got an app that's basically a proxy to a service. The app itself is built on Jersey and served by Jetty. I have this Resource method:

@POST
@Path("/{default: .*}")
@Timed
@Consumes("application/x-www-form-urlencoded")
public MyView post(@Context UriInfo uriInfo, @Context HttpServletRequest request) {
  ...
}

A user submits a POST form. All POST requests go through this method. The UriInfo and HttpServletRequest are injected appropriately except for one detail: there seem to be no parameters. Here is my request being sent from the terminal:

POST /some/endpoint HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 15
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8010
User-Agent: HTTPie/0.9.2

foo=bar&biz=baz

Here the POST body clearly contains 2 parameters: foo and biz. But when I try to get them in my code (request.getParameterMap) the result is a map of size 0.

How do I access these parameters or this parameter string from inside my resource method? If it matters, the implementation of HttpServletRequest that is used is org.eclipse.jetty.server.Request.

like image 853
tytk Avatar asked Jul 20 '26 02:07

tytk


1 Answers

Three options

  1. @FormParam("<param-name>") to gt individual params. Ex.

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public Response post(@FormParam("foo") String foo
                         @FormParam("bar") String bar) {}
    
  2. Use a MultivaluedMap to get all the params

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public Response post(MultivaluedMap<String, String> formParams) {
        String foo = formParams.getFirst("foo");
    }
    
  3. Use Form to get all the params.

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public Response post(Form form) {
        MultivaluedMap<String, String> formParams = form.asMap();
        String foo = formParams.getFirst("foo");
    }
    
  4. Use a @BeanParam along with individual @FormParams to get all the individual params inside a bean.

    public class FormBean {
        @FormParam("foo")
        private String foo;
        @FormParam("bar")
        private String bar;
        // getters and setters
    }
    
    @POST
    @Consumes("application/x-www-form-urlencoded")
    public Response post(@BeanParam FormBean form) {
    }
    
like image 92
Paul Samsotha Avatar answered Jul 22 '26 15:07

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!