你看过Spring的RedirectAttributes吗?我自己并没有使用它,但它听起来像它应该做你想做的事情。 RedirectAttributes通常用于GET /重定向/ POST模式,并且at least one user似乎认为以这种方式传递会话属性是不好的做法,但是他们继续提到似乎没有更好的解决方案。总之,在文档中所示的例子:
@RequestMapping(value = "/accounts", method = RequestMethod.POST)
public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return "accounts/new";
}
// Save account ...
redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
return "redirect:/accounts/{id}";
}
将添加“消息”属性的RedirectModel,如果你的控制器重定向,那么无论方法处理重定向可以访问像这样的数据:
@RequestMapping(value = "/accounts", method = RequestMethod.POST)
public String handleRedirect(Model model) {
String message = (String) model.asMap().get("message");
return new ModelAndView();
}
因此添加会话属性应该可以用同样的方法。另有参考文献here。
编辑 我在浏览Spring文档,他们也提到了这个注释@SessionAttributes。从文档:
类型级别@SessionAttributes注释声明特定处理程序使用的会话属性。这通常会列出应该透明地存储在会话或某些会话存储中的模型属性或模型属性类型的名称,作为后续请求之间的表单支持bean。
这是你需要的吗?
还有a link to documentation on flash attributes。
redirectAttributes的主要问题是我需要将所有变量放在单独的属性中,如果它们不是html的形式。 – Raider