【问题标题】:list of objects from controller to jsp and <c:forEach>从控制器到 jsp 和 <c:forEach> 的对象列表
【发布时间】:2015-12-08 08:11:26
【问题描述】:

我尝试从 Spring MVC 控制器发送员工列表,然后在带有 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.我在 JSP 中有一个 taglib url,但是在这个站点上显示它就像代码一样有问题

【问题讨论】:

  • 你必须在 JSP 页面的 c:forEach 标签中写 items=¨${listOfEmployees}¨。

标签: java spring jsp spring-mvc


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我刚刚尝试过 RedirectView,它工作正常!
【解决方案2】:

这行得通:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    相关资源
    最近更新 更多