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>

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.