Question
How can I correctly pass and access parameters in a RESTful POST method using Jersey?
@POST
@Consumes({"application/json"})
@Path("create/")
public void create(String param1, String param2){
System.out.println("param1 = " + param1);
System.out.println("param2 = " + param2);
}
Answer
In a RESTful service built using Jersey, to correctly process parameters sent in a POST request, you must ensure that the JSON structure sent by the client matches the parameters expected by the server. In the provided example, the issue arises due to improper formation of the JSON payload sent to the server.
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
@Path("create/")
public class MyResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void create(MyRequest request) {
System.out.println("param1 = " + request.getParam1());
System.out.println("param2 = " + request.getParam2());
}
}
public class MyRequest {
private String param1;
private String param2;
// Getters and setters
public String getParam1() { return param1; }
public void setParam1(String param1) { this.param1 = param1; }
public String getParam2() { return param2; }
public void setParam2(String param2) { this.param2 = param2; }
}
Causes
- The JSON string is using incorrect syntax; it should be formatted as a JSON object.
- The parameters are expected to be extracted from a proper JSON object rather than concatenated strings.
Solutions
- Format the JSON string correctly with colons instead of equals signs for key-value pairs.
- Use a class to represent the incoming data structure instead of passing individual parameters.
Common Mistakes
Mistake: Sending improperly formatted JSON (e.g., using = instead of :)
Solution: Ensure the JSON structure is correct: {'param1': 'hello', 'param2': 'hello2' }.
Mistake: Not using an object to encapsulate request parameters
Solution: Create a data class to encapsulate request parameters and ensure proper parsing.
Helpers
- RESTful POST method
- Jersey parameters
- access parameters in Jersey
- JSON in Jersey REST
- Jersey client example