In the last posts we saw how to access query, path and form parameters in MVC Controllers. This post shows how multiple parameters can be mapped to an object using the @BeanParam annotation.
Let's reuse the simple HTML form from the post about form parameters:
<form action="submit" method="post"> <label>ID:</label> <input type="text" name="id" /> <label>Name:</label> <input type="text" name="name" /> <label>Role:</label> <select name="role"> <option value="admin">Admin</option> <option value="reporter">Reporter</option> <option value="accountant">Accountant</option> </select> <input type="submit"/> </form>
This defines a simple form containing two text input fields and a select menu with three options.
In the previous post about form parameters, we learned that we can access these parameters by annotating controller parameters with @FormParam.
However, this approach is cumbersome if the form has more than a few parameters. In these situations we typically want to map form parameters to a separate object. @BeanParams helps us with doing exactly this.
With @BeanParam we can write:
@POST @Path("submit") @Controller public String submit(@BeanParam User user) { // use user .. }
The User class looks like this:
public class User { @FormParam("id") private long id; @FormParam("name") private String name; @FormParam("role") private Role role; // getters and setters }
When the controller method is called a new instance of User will automatically be created. The fields of the created object will be filled with the passed form parameters.
@BeanParam and other parameter annotations
Classes used with @BeanParam are not limited to form parameters. All parameter annotations shown in previous blog posts (@QueryParam, @PathParam, etc.) can be used inside bean parameters.
For example:
@GET @Path("/date/{year}/{month}") public String get(@BeanParam RequestData data) { ... }
public class RequestData { @PathParam("year") private int year; @PathParam("month") private int month; @QueryParam("name") private String name; // getters and setters }
If we now send a HTTP GET request to
/date/2016/02?name=john
the values 2016, 2 and john will be injected to the fields year, month and name of RequestData.
Quick Summary
With @BeanParam you can inject request parameters into beans. This is especially useful if you have more than a few parameters. Inside bean parameters all other parameter annotations can be used.
You can find the example source code on GitHub.
Leave a reply