Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map multiple query parameters to the fields of a bean on Jersey GET request?

A service class has a @GET operation that accepts multiple parameters. These parameters are passed in as query parameters to the @GET service call.

@GET @Path("find") @Produces(MediaType.APPLICATION_XML) public FindResponse find(@QueryParam("prop1") String prop1,                           @QueryParam("prop2") String prop2,                           @QueryParam("prop3") String prop3,                           @QueryParam("prop4") String prop4, ...)  

The list of these parameters are growing, so I would like to place them into a single bean that contains all these parameters.

@GET @Path("find") @Produces(MediaType.APPLICATION_XML) public FindResponse find(ParameterBean paramBean)  {     String prop1 = paramBean.getProp1();     String prop2 = paramBean.getProp2();     String prop3 = paramBean.getProp3();     String prop4 = paramBean.getProp4(); } 

How would you do this? Is this even possible?

like image 872
onejigtwojig Avatar asked Apr 19 '11 20:04

onejigtwojig


People also ask

How do I pass a query param on a map?

Create new map and put there parameters you need: Map<String, String> params = new HashMap<>(); params. put("param1", "value1"); params. put("param2", "value2");

What is @BeanParam?

BeanParam annotation allows you to inject all the matching request parameters into a single bean object. The @BeanParam annotation can be set on a class field, a resource class bean property (the getter method for accessing the attribute), or a method parameter.


1 Answers

In Jersey 2.0, you'll want to use BeanParam to seamlessly provide what you're looking for in the normal Jersey style.

From the above linked doc page, you can use BeanParam to do something like:

@GET @Path("find") @Produces(MediaType.APPLICATION_XML) public FindResponse find(@BeanParam ParameterBean paramBean)  {     String prop1 = paramBean.prop1;     String prop2 = paramBean.prop2;     String prop3 = paramBean.prop3;     String prop4 = paramBean.prop4; } 

And then ParameterBean.java would contain:

public class ParameterBean {      @QueryParam("prop1")       public String prop1;       @QueryParam("prop2")       public String prop2;       @QueryParam("prop3")       public String prop3;       @QueryParam("prop4")       public String prop4; } 

I prefer public properties on my parameter beans, but you can use getters/setters and private fields if you like, too.

like image 95
Patrick Avatar answered Sep 18 '22 03:09

Patrick