users@jersey.java.net

[Jersey] Re: 2.x, how to populate the parameter bean on Jersey GET request ?

From: Simon Roberts <simon_at_dancingcloudphotography.com>
Date: Thu, 5 Mar 2015 11:34:49 -0700

I can't help with your specific request, but if you do these as what I call
"instance" injection, rather than method param injection, I think you could
clean your code up somewhat.

You might well know what I'm talking about, so I'll keep this brief, but if
you are using the default lifecycle (one instance per request) you could do
something like this:

@Path("/myresource")
public class MyResource {
  private MyBean bean;
  public MyResource(@QueryParam... @QueryParam...
   // create/populate the bean from the constructor params
  }

  @Path("/find")
  public Response find() {
    // use the bean here...

At least this way you achieve two things:

1) the clutter of the parameter pickup is "swept under the carpet" and
doesn't clutter up your primary service method
2) if you have more than one method that does this kind of thing, they can
both share the one behavior of the constructor, so duplication of clutter
is also avoided

You could combine this with using the UriInfo class to process the query
params, rather than injecting them explicitly by name. That would also fit
well with pushing them into a map, rather than an explicit bean,
simplifying future modifications.

HTH
Simon


> 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_at_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_at_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();}
>
> Somebody said that to use @BeanParam, but it need
> add @QueryParam for every property in my bean.
>
> So,
> is there any way I can avoid placing @QueryParam for every property in my bean?
>
> In Struts2 application, if there's a quest URL like this:
> http://../queryUser.do?user.name=x&user.address=y
> Struts 2 can auto populate parameter bean in Action, the User bean
> just has setter()/getter().
> public String queryUser(User user){
> ..
> ..
> ..
> }
>
>
>
>
>
-- 
Simon Roberts
Certified Professional Photographer
http://dancingcloudphotography.com
(303) 249 3613