JAX-RS @BeanParam Example
The @BeanParam
annotation is added to the JAX-RS 2.0 specification. It allows you to inject a pojo whose property methods or fields are annotated with any of the injection parameters supported by JAX-RS. To name a few: @FormParam
, @PathParam
, @QueryParam
and @HeaderParam
and etc..
Suppose we have the following form which will submit a name form parameter and a count query parameter.
<!DOCTYPE html>
<html>
<body>
<h1>JAX-RS @BeanParam Example</h1>
<form action="api/users?count=10" method="post">
<label for="name">Name: </label>
<input id="name" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
We can map those parameters inside a POJO. Also note we also added a @HeaderParam
which’ll retrieve the content-type request header.
package com.memorynotfound.rs;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.QueryParam;
public class UserInput {
@FormParam("name")
private String name;
@QueryParam("count")
private int count;
@HeaderParam("Content-Type")
private String contentType;
@Override
public String toString() {
return "UserInput{" +
"name='" + name + '\'' +
", count=" + count +
", contentType='" + contentType + '\'' +
'}';
}
}
Using the JAX-RS @BeanParam
The @BeanParam
will be introspected by JAX-RS at runtime for injection annotations and then set them accordingly.
package com.memorynotfound.rs;
import javax.ws.rs.*;
@Path("/users")
public class UserResource {
@POST
public void createCustomer(@BeanParam UserInput user){
System.out.println(user);
}
}
When the form is submitted, we simply print out the values to the console. This is the result:
UserInput{name='John', count=10, contentType='application/x-www-form-urlencoded'}
Demo
URL: http://localhost:8081/jaxrs-bean-param/
thanks you ,Nice explanation
A doubt: Can I put the same in get request like this…
@GET
Response getResource(@BeanParam UserInput user){
}
I want to wrap up all the user inputs at one place (in one object).
but if its coming a GET request, It ill not initialise
@FormParam(“name”)
private String name;
and throws error;
please comment on this scenario.
thanks again.