java - Parsing the String params received in POST query -
i running simple rest web service receive string params in post query, process them , send string response. in order parse params string
param1=testdata1¶m2=testdata2&
i'm using string.split()
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 on these values , return string.... return str; }
for getting param values i'll have split again..... can please suggest cleaner , elegant solution these param values..
assuming form parameters, 1 way work either jersey 1.x or jersey 2.x inject multivaluedmap
@post @consumes(mediatype.application_form_urlencoded) public string post(multivaluedmap<string, string> form) { stringbuilder builder = new stringbuilder(); (map.entry<string, list<string>> params : form.entryset()) { (string key: params.getvalue()) { builder.append("key: ").append(params.getkey()).append("; ") .append("value: ").append(params.getvalue().get(0)).append("\n"); } } return builder.tostring(); }
if know ahead of time name of form key, create bean.
public class bean { @formparam("key1") private string value1; @formparam("key2") private string value2; // getter , setters }
for jersey 2.x, inject @beanparam
@post @consumes(mediatype.application_form_urlencoded) public response post(@beanparam bean bean) { }
for jersey 1.x inject @injectparam
@post @consumes(mediatype.application_form_urlencoded) public response post(@injectparam bean bean) { }
note bean injection work other @xxxparam
s also, not @formparam
, instance @queryparam
, @pathparam
. can mix , match them.
or if know names ahead of time, if don't need bean, can declare form params in method signature
@post @consumes(mediatype.application_form_urlencoded) public response post(@formparam("key1") string value1, @formparam("key2") string value2) { }
Comments
Post a Comment