Book Image

SPRING COOKBOOK

By : Jerome Jaglale, Yilmaz
Book Image

SPRING COOKBOOK

By: Jerome Jaglale, Yilmaz

Overview of this book

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.
Table of Contents (14 chapters)
13
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>