Display list of values on JSP using Spring

谁说胖子不能爱 提交于 2019-12-05 16:15:08

As you are populating ModelAndView return ModelAndView itself and not map.getViewName() which return only name of the name without data as stated in docs:

public String getViewName() Return the view name to be resolved by the DispatcherServlet via a ViewResolver, or null if we are using a View object.

as follows:

@RequestMapping(value = { "/employee" }, method = RequestMethod.GET)
public ModelAndView listEmployee() {
    System.out.println("Kontroler EmployeeController");
    LinkedList<String> list = getList();
    ModelAndView map = new ModelAndView("index");
    map.addObject("lists", list);

    return map;
}

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:

<html>
<head>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<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>
</body>

<c:if test="${not empty lists}">
    <c:forEach items="${lists}" var="lists">
       ${lists}
</c:forEach>
</c:if>

Also, make sure you have JSTL dependency in your classpath:

<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Just add Model to your controller method params and then add attribute to this model.

RequestMapping(value={"/employee"}, method = RequestMethod.GET)
public String listEmployee(Model model){    
    System.out.println("Kontroler EmployeeController");
    LinkedList<String> list = getList();
    model.addAttribute("lists", list);

    return "index";
}

One more way to do this, is to return ModelAndView instead of String

@RequestMapping(value={"/employee"}, method = RequestMethod.GET)
public ModelAndView listEmployee(){    
    System.out.println("Kontroler EmployeeController");
    LinkedList<String> list = getList();
    ModelAndView map = new ModelAndView("index");
    map.addObject("lists", list);

    return map;
}

Just choose which way is better for you.

And also change listEmployee in your index page to lists as in the ModelAndView you have an attribute as lists not listEmployee`.

Change the key name and try it : listEmployee --> lists as you are setting it as map.addObject("lists", list);

<ul>
    <c:forEach var="listValue" items="${lists}">
        <li>${listValue}</li>
    </c:forEach>
</ul>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!