Reputation: 523
I have a string of parameters in URL and I want to convert this string into a bean object.
For example, I have the URL www.domain.com/book?authorFirstName=Dostoevsky
and I want to get a bean, a capsule for criterias:
public class BookCriterias {
...
public String getAuthorFirstName() {...}
public void setAuthorFirstName(String fName) {...}
public String getAuthorLastName() {...}
public void setAuthorLastName(String lName) {...}
public String getGenre() {...}
public void setGenre(String genre) {...}
}
Does some ready-to-use library exist for this purpose?
Upvotes: 1
Views: 1892
Reputation: 869
In Jersey or Dropwizard, you can have your own implementation of javax.ws.rs.container.ContainerRequestFilter
where you can get hold of URIInfo Object from javax.ws.rs.container.ContainerRequestContext
and convert QueryParameters to whatever object you want and set it back into javax.ws.rs.container.ContainerRequestContext
.
By this way, you can get criteria as a bean in your Resource class.
Upvotes: 0
Reputation: 3305
You can also try like this:
String authorFirstName = request.getParameter("authorFirstName");
BookCriterias bc = new BookCriterias();
if(authorFirstName!=null && authorFirstName!=""){
bc.setAuthorFirstName(authorFirstName);
}
Upvotes: 1
Reputation: 44942
This will depend on your libraries but a standard javax.servlet.ServletRequest
class has a Map<String, String[]> getParameterMap()
method:
Returns:
an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.
After that it's a simple Map to Bean scenario which can be accomplished with most bean mapping tools like Orika Mapper or Commons BeanUtils. You can try to use the latter with:
BookCriterias bc = new BookCriterias();
BeanUtils.populate(bc, request.getParamterMap());
Upvotes: 1