使用Spring显示JSP上的值列表

我想在我的jsp视图中显示我的值列表,但我无法做到这一点。

这是我的控制器类,它只是将List添加到ModelAndView映射,而不是重定向到我的index.jsp页面。

EmployeeController

 @Controller public class EmployeeController { @RequestMapping(value={"/employee"}, method = RequestMethod.GET) public String listEmployee(){ System.out.println("Kontroler EmployeeController"); LinkedList list = getList(); ModelAndView map = new ModelAndView("index"); map.addObject("lists", list); return map.getViewName(); } private LinkedList getList(){ LinkedList list = new LinkedList(); list.add("Item 1"); list.add("Item 2"); list.add("Item 3"); return list; } } 

的index.jsp

    Welcome to Spring Web MVC project   

Index page

${msg}

Zaměstnanci
  • ${listValue}

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

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

在填充ModelAndView返回ModelAndView本身而不是map.getViewName() ,它只返回名称中没有数据的名称,如docs中所述:

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

如下:

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

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

   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  Welcome to Spring Web MVC project   

Index page

${lists}

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

  jstl jstl 1.2  

只需将Model添加到控制器方法参数,然后将属性添加到此模型。

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

另一种方法是返回ModelAndView而不是String

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

只需选择哪种方式更适合您。

并且还将索引页面中的listEmployee更改为lists就像在ModelAndView lists一样,您将属性列为lists而不是listEmployee`。

更改密钥名称并尝试: listEmployee --> lists as you are setting it as map.addObject("lists", list);

 
  • ${listValue}