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/

jaxrs-@BeanParam-example

References

Download

You may also like...