Setting a form's default values using a model object

In this recipe, you will learn how to display a form with initial values that the user can change.

How to do it…

Create an object containing the default values in the controller. In the view, use Spring form tags to generate the form using that object:

  1. In the controller, add a method annotated with @ModelAttribute, which returns an object with default values:
    @ModelAttribute("defaultUser")
    public User defaultUser() {
      User user = new User();
      user.setFirstName("Joe");
      user.setAge(18);
      return user;
    }
  2. In the controller, add a method to display the form:
    @RequestMapping("addUser")
    public String addUser() {
      return "addUser";
    }
  3. In the JSP, use Spring form tags to generate the form:
    <%@ taglib prefix="form" ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.