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

Passing attributes from a controller to a JSP view


In this recipe, you'll learn how to set attributes in a controller method and use them in a JSP view.

How to do it…

Here are the steps to pass data from a controller to a view:

  1. Add a Model argument to the controller method:

      @RequestMapping("/user/list")
      public void userList(Model model) {
      ...
  2. In the controller method, add attributes to the Model object:

    model.addAttribute("nbUsers", 13);
  3. Use the attributes in the JSP file:

    <p>There are ${nbUsers} users</p>

How it works…

The nbUsers variable is set to 13 in the controller. In the JSP file, the ${nbUsers} EL (Expression Language) element will be rendered to 13, so that the following HTML will be returned:

<p>There are 13 users</p>