Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end the session in spring 3

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.

Thanks.

@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";
}
like image 253
kavi Avatar asked Jun 20 '13 05:06

kavi


1 Answers

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

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

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

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";
  }
}
like image 65
gerrytan Avatar answered Oct 07 '22 13:10

gerrytan