Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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" uri="http://www.springframework.org/tags/form" %>
    
    <form:form method="POST" modelAttribute="defaultUser">
      <form:input path="firstName" />
      <form:input path="age" />
      <input type="submit" value="Submit" /&gt...