0
假设我有一个查看客户的控制器方法,如果他们无权查看该客户,则将错误消息添加为Flash属性,然后重定向到一个区域上市,但是;如果用户被分配了一个地区,那么地域处理方法将重定向到该地区内的客户列表。如何保留多个重定向上的模型Flash属性
@RequestMapping("/customers/{id}")
public ModelAndView customers(@PathVariable("id") long id,
Principal principal,
RedirectAttributes ra) {
// if user is not allowed
if (!svc.isAccessGrantedToCustomer(principal.getName(), id)) {
ra.addFlashAttribute("errorMessage",
"Access denied for customer " + id + ".");
return new ModelAndView("redirect:/territories");
}
// get customer and return new view...
}
@RequestMapping("/territories")
public ModelAndView territories(Principal principal,
RedirectAttributes ra) {
// get some territory for user.
Long id = svc.getUserTerritory(principal.getName());
if (id != null) {
return new ModelAndView("redirect:/territories/" + id);
}
// return new view.
}
@RequestMapping("/territories/{id}")
public ModelAndView territory(@PathVariable("id") long id,
Principal principal,
ModelAndView mav,
Model m,
RedirectAttributes ra) {
// mav is empty, it does not contain flash attributes.
// m does contain flash attributes.
// Fill model and return view.
mav.setViewName("territory");
// fill the model...
return mav;
}
所有重定向都按预期工作,但模型属性丢失。
我发现的是,模型属性存在于Model
。
然而,一种解决方案是将Model
的所有闪存属性重新添加到RedirectAttribute
;这似乎是不必要的,实际上比我想要的还要多。
m.asMap().forEach((k, v) -> ra.addFlashAttribute(k, v));
恕我直言的处理程序不应该担心它是怎么被调用(重定向,直接),所以不应该重新添加闪光属性。
会话属性不适合这里,因为我们只希望它活链接请求的用户,我们不想'errorMessage'坚持跨请求。除非被重定向,否则我们也希望这会在用户请求中丢失。 Flash属性起作用,我只需要它们为多个重定向工作。 –