如何在 spring 3 中结束会话 [英] How to end the session in spring 3

查看:39
本文介绍了如何在 spring 3 中结束会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 spring 中使用 @SessionAttributes,但我不知道如何结束会话,我尝试了下面的代码但出现错误,请举个例子.

I am using @SessionAttributes in spring, but I don't know how to end the session, I tried the below code but I am getting error, Please give me some example.

谢谢.

@RequestMapping(value = "/LogoutAction")
public String logout(HttpServletRequest request) {
    Resource res = new ClassPathResource("spring-context.xml");
    BeanFactory factory = new XmlBeanFactory(res);
    HttpSession session = request.getSession();
    session.invalidate();
    return "Login";
}

推荐答案

我认为使用 @SessionAttributes 时的常见问题是在您使当前会话无效后,Spring MVC 将模型属性附加回新会话——因此造成它永远不会失效的印象

I think the common problem when using @SessionAttributes is after you invalidate your current session, Spring MVC attach the model attributes back into the new session -- hence causing the impression it never invalidates

您可以在 & 之前检查 JSESSIONID 的值在您使其无效之后.您将获得一个全新的 JSESSIONID,但之前的模型属性会直接附加到新会话中

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

我发现自己必须这样做才能在使会话无效后从会话中擦除名称为counter"的模型属性

I found myself having to do this to wipe a model attribute of name "counter" from session after invalidating it

@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();

但在我看来,更好的方法是使用一个没有 @SessionAttribute 的不同控制器来无效.因此,其他控制器的任何模型属性都不会直接附加到新会话中.例如:

But in my opinion better approach is to invalidate using a different controller that doesn't have @SessionAttribute on it. Hence whatever model attributes other controllers have won't be attached straight into the new session. Eg:

@Controller
@RequestMapping("/logout")
public class LogoutController {

  @RequestMapping(method=RequestMethod.POST)
  public String logout(HttpSession session) {
    session.invalidate();
    return "redirect:/login";
  }
}

这篇关于如何在 spring 3 中结束会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆