I would like to display my List of values in my jsp view, but i am not able to do this.
Here is my controller class below, which is only add List to the ModelAndView
map and than it redirects to my index.jsp
page.
EmployeeController
@Controller
public class EmployeeController {
@RequestMapping(value={"/employee"}, method = RequestMethod.GET)
public String listEmployee(){
System.out.println("Kontroler EmployeeController");
LinkedList<String> list = getList();
ModelAndView map = new ModelAndView("index");
map.addObject("lists", list);
return map.getViewName();
}
private LinkedList<String> getList(){
LinkedList<String> list = new LinkedList<>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
return list;
}
}
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Spring Web MVC project</title>
</head>
<body>
<h1>Index page</h1>
<h1>${msg}</h1>
<a href="/MavenHello/employee">Zaměstnanci</a>
</body>
<c:if test="${not empty listEmployee}">
<ul>
<c:forEach var="listValue" items="${listEmployee}">
<li>${listValue}</li>
</c:forEach>
</ul>
</c:if>
I am able to access the controller, because every time I hit "Zaměstnanci"
, the System.out.println("Kontroler EmployeeController")
prints "Kontroler EmployeeController"
in to Tomcat Log, but the index.jsp
page is blank.
Please, can someone give me an advice?
Just add
Model
to your controller method params and then add attribute to this model.One more way to do this, is to return
ModelAndView
instead ofString
Just choose which way is better for you.
And also change
listEmployee
in your index page tolists
as in theModelAndView
you have an attribute aslists
not listEmployee`.As you are populating
ModelAndView
return ModelAndView itself and notmap.getViewName()
which return only name of the name without data as stated in docs:as follows:
Secondly, you are missing jstl tag
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
on your index page and variable name you given to list is "lists" so iterate over "lists" rather than "listEmployee", as follows:Also, make sure you have JSTL dependency in your classpath:
Change the key name and try it :
listEmployee --> lists as you are setting it as map.addObject("lists", list);