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

Displaying and processing a form


To display a form and retrieve the data the user entered when it's submitted, use a first controller method to display the form. Use a second controller method to process the form data when the form is submitted.

How to do it…

Here are the steps to display and process a form:

  1. Create a controller method to display the form:

    @RequestMapping("/addUser")
    public String addUser() {
      return "addUser";
    }
  2. Create a JSP with an HTML form:

    <form method="POST">
      <input type="text" name="firstName" />
      <input type="submit" />
    </form>
  3. Create another controller method to process the form when it's submitted:

    @RequestMapping(value="/addUser", method=RequestMethod.POST)
    public String addUserSubmit(HttpServletRequest request) {
      String firstName = request.getParameter("firstName");
      ...
      return "redirect:/home";
    }

How it works…

The first controller method displays the JSP containing the HTML form. For more details, refer to the Using a JSP view recipe in...