如何在 spring 3 中结束会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17205841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to end the session in spring 3
提问by kavi
I am using @SessionAttributesin spring, but I dont know how to end the session, I tried the below code but I am getting error, Please give me some example.
我@SessionAttributes在 spring 中使用,但我不知道如何结束会话,我尝试了下面的代码,但出现错误,请给我一些例子。
Thanks.
谢谢。
@RequestMapping(value ="/LogoutAction")
public String logout(HttpServletRequest request)
{
System.out.println("inside controller");
Resource res = new ClassPathResource("spring-context.xml");
BeanFactory factory = new XmlBeanFactory(res);
HttpSession session = request.getSession();
session.invalidate();
return "Login";
}
回答by gerrytan
I think the common problem when using @SessionAttributesis after you invalidate your current session, Spring MVC attach the model attributes back into the new session-- hence causing the impression it never invalidates
我认为使用时的常见问题@SessionAttributes是在您使当前会话无效之后,Spring MVC 将模型属性附加回新会话- 因此造成它永远不会无效的印象
You can check the value of JSESSIONID before & after you invalidate it. You will get a brand new JSESSIONID, yet previous model attributes are attached straight into the new session
您可以在使其无效之前和之后检查 JSESSIONID 的值。您将获得一个全新的 JSESSIONID,但之前的模型属性会直接附加到新会话中
I found myself having to do this to wipe a model attribute of name "counter" from session after invalidating it
我发现自己必须这样做才能在使会话无效后从会话中擦除名称为“counter”的模型属性
@RequestMapping(value="/invalidate", method=RequestMethod.POST)
public String invalidate(HttpSession session, Model model) {
session.invalidate();
if(model.containsAttribute("counter")) model.asMap().remove("counter");
return "redirect:/counter";
}
If you have plenty attributes, ofcourse you can try wiping everything off using
如果你有很多属性,当然你可以尝试使用
model.asMap().clear();
But in my opinion better approach is to invalidate using a different controller that doesn't have @SessionAttributeon it. Hence whatever model attributes other controllers have won't be attached straight into the new session. Eg:
但在我看来,更好的方法是使用不同的控制器使其无效@SessionAttribute。因此,其他控制器的任何模型属性都不会直接附加到新会话中。例如:
@Controller
@RequestMapping("/logout")
public class LogoutController {
@RequestMapping(method=RequestMethod.POST)
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/login";
}
}

