Reputation: 55
I running a very simple REST web service to receive string params in post query, process them and send back a string response. In order to parse the params from string
param1=testData1¶m2=testData2&
I'm using String.split()
as under:
@POST
@Produces(MediaType.TEXT_PLAIN)
public String post(String str) {
String[] parts = str.split("&");
String part1 = parts[0]; // param1=testData1
String part2 = parts[1]; // param2=testData2
......do something on these values and return String....
return str;
}
for getting the param values I'll have to split again..... can someone please suggest a cleaner and elegant solution to get these param values..
Upvotes: 0
Views: 382
Reputation: 208994
Assuming its form parameters, one way that will work for either Jersey 1.x or Jersey 2.x is to inject MultivaluedMap
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(MultivaluedMap<String, String> form) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, List<String>> params : form.entrySet()) {
for (String key: params.getValue()) {
builder.append("key: ").append(params.getKey()).append("; ")
.append("value: ").append(params.getValue().get(0)).append("\n");
}
}
return builder.toString();
}
If you know ahead of time the name of the form key, you could create a bean.
public class Bean {
@FormParam("key1")
private String value1;
@FormParam("key2")
private String value2;
// getter and setters
}
For Jersey 2.x, you would inject with @BeanParam
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(@BeanParam Bean bean) {
}
For Jersey 1.x you would inject with @InjectParam
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(@InjectParam Bean bean) {
}
Note that the bean injection will work for all the other @XxxParam
s also, not just @FormParam
, for instance @QueryParam
, @PathParam
. You can mix and match them.
Or if you know the names ahead of time, if you don't need the bean, you can simply declare all the form params in the method signature
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(@FormParam("key1") String value1,
@FormParam("key2") String value2) {
}
Upvotes: 3