mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Monday, 22 February, 2016

Java EE 8 MVC: Working with form parameters

In the previous two posts we saw how to work with query and path parameters in the upcoming Java EE MVC framework. This post focuses on form parameters.

When you submit a web form using a post request, the form values are send as part of the request body. The media type (or content type) defines the format that is used to store the values inside the request body. Web forms usually use the media type application/x-www-form-urlencoded. Parameters that are send using this media type can be accessed using the @FormParam annotation.

Using form parameters

Assume we have the following simple HTML form, containing two text input fields and a select menu:

<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>

To process the form values we can use the following controller method:

public enum Role {
  admin, reporter, accountant
}
@Controller
@Path("form-params")
public class FormParamsController {

  @POST
  @Path("submit")
  public String submitParams(
      @FormParam("id") long id,
      @FormParam("name") String name,
      @FormParam("role") Role role) {

    ...
  }
}

With @FormParam form parameters can automatically be mapped to method arguments. Form parameters use the same type conversion rules as query or path parameters (described here). This makes it easy to convert form parameters to primitives, enums or objects.

Using @FormParam on fields and methods

Like other parameter annotations @FormParam can be used to annotate fields and methods.

For example:

@Controller
@Path("form-params-fields")
public class FormParamsFieldController {

  @FormParam("id")
  private long id;

  @FormParam("role")
  private Role role;

  private String name;

  @FormParam("name")
  public void setNameField(String name) {
    this.name = name;
  }

  @POST
  public String submitParams() {
     // use id, role, name
  }
}

In this example the submitted form parameters are mapped to fields (id, role) and a setter (setNameField()). Inside submitParams() we can then simply access the fields to obtain the form parameters.

Quick Summary

Parameters submitted via HTML forms can be obtained with @FormParam. Like @QueryParam and @PathParam it is possible to annotate fields, methods and method parameters with @FormParam.

You can find the source code for all examples on GitHub.

Leave a reply