How to get POST parameter in JAX-RS method?

user1573269 picture user1573269 · Oct 22, 2012 · Viewed 53.6k times · Source

I am developing RESTful services with Jersey and it works great with GET methods. But I can only get null parameters using the POST method. Here is the sample code from my project.

HTML

<form action="rest/console/sendemail" method="post">
  <input type="text" id="email" name="email">
  <button type="submit">Send</button>
</form> 

Java

@POST
@Path("/sendemail")
public Response sendEmail(@QueryParam("email") String email) {
    System.out.println(email);
    return  new Response();
}

The email I get from the post is always null. Anyone has the idea?

I changed QueryParam to FormParam, the parameter I get is still null.

Answer

user647772 picture user647772 · Oct 22, 2012

In a form submitted via POST, email is not a @QueryParam like in /[email protected].

If you submit your HTML form via POST, email is a @FormParam.

Edit:

This is a minimal JAX-RS Resource that can deal with your HTML form.

package rest;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/console")
public class Console {

    @POST
    @Path("/sendemail")
    @Produces(MediaType.TEXT_PLAIN)
    public Response sendEmail(@FormParam("email") String email) {
        System.out.println(email);
        return Response.ok("email=" + email).build();
    }
}