【发布时间】:2018-09-11 07:05:05
【问题描述】:
我想在重定向后将数据传递给视图。例如,我按下一个按钮,它会将我重定向到包含来自控制器的数据的页面。我正在尝试使用每个人都建议的 RedirectAttribute,但我无法让它工作。任何帮助表示赞赏。
index.jsp:
<a href="user.htm">Display All Users</a>
控制器:
@RequestMapping(value = "/user.htm")
public ModelAndView addUser(RedirectAttributes redirAtt) {
ModelAndView mv = new ModelAndView("redirect:user");
String out = "All User Details: ";
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List result = session.createQuery("from Users").list();
mv.addObject("users", result);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
redirAtt.addFlashAttribute("message", out);
return mv;
}
我希望数据显示在的jsp:user.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${message}</title>
</head>
<body>
<h1>${message}</h1><br>
<table>
<tr>
<th>Username</th>
<th>Nickname</th>
<th>Email</th>
<th>Password</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.username}"/></td>
<td><c:out value="${user.nickname}"/></td>
<td><c:out value="${user.email}"/></td>
<td><c:out value="${user.password}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
页面重定向时不显示数据。
我的控制器也是这样设计的:
@RequestMapping(value = "/test.htm")
public String addUser(RedirectAttributes redirectAttributes) {
String out = "All User Details: ";
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List result = session.createQuery("from Users").list();
session.getTransaction().commit();
redirectAttributes.addAttribute("message", "testing testing tesing");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/user.jsp";
}
@RequestMapping(value = "/user.jsp")
public ModelAndView test(@ModelAttribute("message") String myMessage) {
ModelAndView mv = new ModelAndView("user");
mv.addObject("message", myMessage);
return mv;
}
当我尝试这个时,重定向的 url 是:
http://localhost:8080/projname/user.jsp?message=testing+testing+tesing
所以我认为属性被传递了,但也许我输出错误?
【问题讨论】:
-
如果你使用redirect,你可以通过URL传递参数,这意味着值来自你在浏览器中看到的url,你可以使用它放置单个对象,但如果传递多个对象,url大小可能会达到GET方式的限制,建议换一种方式:redirect后查询对象
-
我现在只想得到一个消息值。我该怎么做?
-
你可以使用 RedirectAttrbutes addAttribute 方法来做,见docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
标签: java spring jsp spring-mvc controller