Pravat Panda
Pravat Panda

Reputation: 1090

Spring model attribute/jsp not visible

Learning spring + jsp.

I am setting a model attribute in a method in a controller

@RequestMapping("/viewExpenses")
public String viewAllExpenses(Model model){

    List<Expense> expenses;
    expenses = expenseService.getAllExpenses();
    model.addAttribute(expenses);
    for(Expense e : expenses)
    System.out.println(e);
    return "viewExpenses";
}

where expenses size is > 1

Following is my jsp page:
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<h2>
    Hello ${user.firstName} <br> <a href="homepage">HOME</a>
</h2>
<div>All Expenses</div>
<span style=""></span>
<c:forEach var="expense" items="${expenses}">
    <c:out value="${expense.expenseId}"></c:out>
    <c:out value="${expense.expenseName}"></c:out>
    <c:out value="${expense.expenseType}"></c:out>
    <c:out value="${expense.expensePrice}"></c:out>
    <c:out value="${expense.purchaseDate}"></c:out>
    <c:out value="${expense.expenseComments}"></c:out>
</c:forEach>
</body>
</html>

Following is my output from the jsp(no errors): Hello Pravat HOME All Expenses

I wonder why the expenses are not populated in my jsp

Upvotes: 0

Views: 2694

Answers (2)

Reimeus
Reimeus

Reputation: 159864

You need to give your attribute an attribute name:

model.addAttribute("expenses", expenses);

Background: When a name is not supplied, Spring uses a generated name which is not the same as the variable name. The docs explain this:

Determine the conventional variable name for the supplied Object based on its concrete type. The convention used is to return the uncapitalized short name of the Class, according to JavaBeans property naming rules: So, com.myapp.Product becomes product; com.myapp.MyProduct becomes myProduct; com.myapp.UKProduct becomes UKProduct.

Upvotes: 1

Vitaly
Vitaly

Reputation: 2800

  1. Give it a name

    model.addAttribute("expenses", expenses);
    
  2. Return ModelAndView.

  3. Always enclose body of if/for/etc into { } even it's single-lined.

Upvotes: 1

Related Questions