从控制器到jsp和<c:foreach>的对象列表

时间:2015-12-08 08:11:27

标签: java spring jsp spring-mvc

我尝试从Spring MVC控制器发送Employee列表,然后在带有forEach循环的jsp中使用它,但是接收空白页面。

有什么问题?

这是我的代码:

@RequestMapping(value = "getuserbylastname", method = RequestMethod.GET)
Employee employee, ModelMap model) {
public ModelAndView searchUserByLastname(@ModelAttribute("employee")Employee employee, ModelMap model) {
    List emplList = new ArrayList();
    EmployeeDAO employeeDAO = new EmployeeDAOImpl();
    emplList = employeeDAO.getByLastname(employee.getLastName());// here list size is 2
    model.addAttribute("listOfEmployees", emplList);
    return new ModelAndView("redirect:/searchbysurnameresult", "Model", emplList);
}

JSP:

<html>
 <body>
 <c:forEach var="employee" items="${Model}">
   <c:out value="${employee.firstName}"/>
 </c:forEach>
 </body>
</html>

P.S.I在JSP中有一个taglib url但是在这个站点的代码中显示它有一个问题

2 个答案:

答案 0 :(得分:2)

当您重定向页面时,会出现此问题,并且模型属性中的数据将变为空。 Spring MVC添加了新类型的属性,称为FlashAttributes。用它们来解决这个问题。

link提供了有关如何使用Flash属性的更多信息。

答案 1 :(得分:1)

这有效:

    @RequestMapping(value = "getuserbylastname", method = RequestMethod.GET)
    public RedirectView searchUserByLastname(@ModelAttribute("employee") Employee employee, RedirectAttributes redirectAttrs) {
      List emplList = new ArrayList();
      EmployeeDAO employeeDAO = new EmployeeDAOImpl();
      emplList = employeeDAO.getByLastname(employee.getLastName());
      redirectAttrs.addFlashAttribute("listOfEmployees", emplList);
      return new RedirectView("searchbysurnameresult", true);
}