I\'m trying to bind values in a GET request to a POJO.
The values are parameters in a HTTP GET request. I\'m using JSONP to pass the parameters however it looks like JS
GET request cannot consume any entity. Instead, use POST or PUT methods (provided request is for insert or update). Otherwise, go with standard way of passing attributes in URL.
I was able resolve this by using @com.sun.jersey.api.core.InjectParam of jersey
public JSONWithPadding doSomething(@InjectParam final MyPojo argPojo)
Then the Pojo looks like this
public class MyPojo
{
/** */
@QueryParam("value1")
private String value1;
/** */
@QueryParam("value2")
private String value2;
/** */
@QueryParam("value3")
private List<String> value3;
I am proposing a more expanded example.
jQuery client side:
var argPojo = {
callback:"myPojoCallback",
value1:"val1",
value2:"val2",
value3:["val1", "val2", "val3"]
};
var url = 'xxx.xx.xx.xx/testPojo';
$.ajax({
type: 'GET',
async: false,
jsonpCallback: argPojo.callback,
url: url,
data:argPojo,
contentType: "application/json",
dataType: 'jsonp',
beforeSend:function(){
console.log("sending:",argPojo);
},
success: function(response) {
console.log("reciving",response);
},
error: function(e) {
console.error("error",e);
}
});
on the server
@Path("testPojo")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/x-javascript")
public JSONWithPadding testPojo(@InjectParam MyPojo argPojo){
System.out.println(argPojo);
System.out.println(argPojo.callback);
System.out.println(argPojo.value1);
System.out.println(argPojo.value2);
System.out.println(argPojo.value3);
return new JSONWithPadding(argPojo, argPojo.callback);
}
the actual class object
public class MyPojo {
@QueryParam("callback")
public String callback;
@QueryParam("value1")
public String value1;
@QueryParam("value2")
public String value2;
@QueryParam("value3[]")
public List<String> value3;
public MyPojo(){}
}
chrome console result
sending: Object
callback: "myPojoCallback"
value1: "val1"
value2: "val2"
value3: Array[3]
__proto__: Object
receiving Object
callback: "myPojoCallback"
value1: "val1"
value2: "val2"
value3: Array[3]
__proto__: Object
HTTP GET by specification includes the parameters in the URL - therefore it only accepts value pairs. So, what you are trying to do is not feasible. why don't you use a POST instead to bundle a JSON object together with the request?
As we know GET request cannot consume any entity, we need to pass each parameter as params. To be simple we can do like the below using javax.ws.rs.BeanParam
(We can use the @BeanParam
instead of @InjectParam
public JSONWithPadding doSomething(@BeanParam final MyPojo argPojo)
....
public class MyPojo
{
/** */
@QueryParam("value1")
private String value1;
/** */
@QueryParam("value2")
private String value2;
/** */
@QueryParam("value3")
private List<String> value3;