使用 Spring 在 JSP 上显示值列表

Ste*_*anu 5 java spring jsp spring-mvc modelandview

我想在我的 jsp 视图中显示我的值列表,但我不能这样做。

下面是我的控制器类,它只是将 List 添加到ModelAndView地图,然后重定向到我的index.jsp页面。

员工控制器

@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;
}

}
Run Code Online (Sandbox Code Playgroud)

索引.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>
Run Code Online (Sandbox Code Playgroud)

我能够访问控制器,因为每次我点击 时"Zam?stnanci",都会System.out.println("Kontroler EmployeeController")打印"Kontroler EmployeeController"到 Tomcat 日志,但index.jsp页面是空白的。

拜托,有人可以给我建议吗?

Arp*_*wal 6

由于您正在填充ModelAndView返回 ModelAndView 本身,而不是map.getViewName()仅返回名称的名称而没有文档中所述的数据:

public String getViewName() 返回要由 DispatcherServlet 通过 ViewResolver 解析的视图名称,如果我们使用的是 View 对象,则返回 null。

如下:

@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;
}
Run Code Online (Sandbox Code Playgroud)

其次,您<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>在索引页面上缺少 jstl 标记 ,并且您提供给 list 的变量名称是“lists”,因此迭代“lists”而不是“listEmployee”,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

另外,请确保您的类路径中有JSTL依赖项:

<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)