下面使用@SessionAttributes
的示例。向导完成后如何清除user
会话属性?在我的示例中,返回/wizard0
会话后,属性仍然存在。我尝试过status.setComplete()
和session.removeAttribute("user")
,但它不起作用。
@Controller
@SessionAttributes("user")
public class UserWizard {
@RequestMapping(value = "/wizard0", method = RequestMethod.GET)
public String page1(Model model) {
if(!model.containsAttribute("user")) {
model.addAttribute("user", new User());
}
return "wizard/page1";
}
@RequestMapping(value = "/wizard1", method = RequestMethod.GET)
public String page2(@ModelAttribute User user) {
user.setFirstname(Utils.randomString());
return "wizard/page2";
}
@RequestMapping(value = "/wizard2", method = RequestMethod.GET)
public String page3(@ModelAttribute User user) {
user.setLastname(Utils.randomString());
return "wizard/page3";
}
@RequestMapping(value = "/finish", method = RequestMethod.GET)
public String page4(@ModelAttribute User user, HttpSession session, SessionStatus status) {
/**
* store User ...
*/
status.setComplete();
session.removeAttribute("user");
return "redirect:/home";
}
}
我的错误。 status.setComplete();
效果很好。 session.removeAttribute("user")
在这里无关。
答案 0 :(得分:10)
尝试使用WebRequest.removeAttribute
方法而不是HttpSession.setAttribute
方法(示例1)。或者使用'SessionAttributeStore.cleanupAttribute'(示例2)完全相同的另一种方式。
示例1
@RequestMapping(value = "/finish", method = RequestMethod.GET)
public String page4(@ModelAttribute User user, WebRequest request, SessionStatus status) {
/**
* store User ...
*/
status.setComplete();
request.removeAttribute("user", WebRequest.SCOPE_SESSION);
return "redirect:/home";
}
示例2
@RequestMapping(value = "/finish", method = RequestMethod.GET)
public String page4(@ModelAttribute User user, WebRequest request, SessionAttributeStore store, SessionStatus status) {
/**
* store User ...
*/
status.setComplete();
store.cleanupAttribute(request, "user");
return "redirect:/home";
}
答案 1 :(得分:0)
以下为我工作-
@RequestMapping(value = "/finish", method = RequestMethod.GET)
public String page4(HttpSession httpsession, SessionStatus status) {
/*Mark the current handler's session processing as complete, allowing for cleanup of
session attributes.*/
status.setComplete();
/* Invalidates this session then unbinds any objects boundto it. */
httpsession.invalidate();
return "redirect:/home";
}