This post will explain the use of BeanParam annotation in JAX-RS with an example.
The purpose of BeanParam annotation is to consolidate all the user input (i.e., input through QueryParam, HeaderParam, FormParam, etc) and inject into a
given class instance variables.
Below is an example of webresource whose only method “retrieveRecord1” has a parameter annotated with @BeanParam annotation
WebResource
1 package resource;
2
3 import javax.ws.rs.BeanParam;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.Response;
8
9 @Path("webresource6")
10 public class WebResource6 {
11 @GET
12 public Response retrieveRecord1(@BeanParam ConsolidatedParam consolidatedParam) {
13 Response response = Response.ok(consolidatedParam, MediaType.TEXT_PLAIN).build();
14 return response;
15 }
16 }
At line 12, the “retrieveRecord1” has parameter of class ConsolidatedParam and it is annotated with @BeanParam annotation.
The class details of ConsolidatedParam is as shown below
ConsolidatedParam
1 package resource;
2
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.QueryParam;
5
6 public class ConsolidatedParam {
7 @QueryParam("param1")
8 private String param1;
9
10 @QueryParam("param2")
11 private String param2;
12
13 @HeaderParam("param3")
14 private String param3;
15
16 @HeaderParam("param4")
17 private String param4;
18
19 @Override
20 public String toString() {
21 StringBuilder sb = new StringBuilder();
22 sb.append("param1:").append(param1).append(";");
23 sb.append("param2:").append(param2).append(";");
24 sb.append("param3:").append(param3).append(";");
25 sb.append("param4:").append(param4).append(";");
26 return sb.toString();
27 }
28 }
The instance variables of the class are annotated with various annotations which indicate the source of the value.
For example at line 7 and 8, param1 is annotated with QueryParam. It means we need to get the value of param1 variable from query string having the key param1
So when we access the webresource using the below url
http://localhost:8080/JAXRSConcepts/myresources/webresource6?param1=1¶m2=2
and header variables param3=3 and param4=4, the output will be as shown below
Output
param1:1;param2:2;param3:3;param4:4;