简体   繁体   中英

how to invalidate session in spring mvc for implementing logout

I have set the session attributes using

@SessionAttribute annotation.
@RequestMapping(value = "/login_action")
public ModelAndView login_action(@RequestParam("email") String email,@RequestParam("password") String password){
                Query q=session.createSQLQuery("SELECT User_ID,User_First_Name,User_Last_Name,Email,User_Type,Program,Level,Gender FROM Users  WHERE Email=:email AND Password=:password");
q.setParameter("email",email);
q.setParameter("password",password);
Object u = (Object) q.uniqueResult();
model=new ModelAndView("profile");
model.addObject("user",u);
return model;
}

Now i need to invalidate this session while logging out. I tried like

    @RequestMapping(value = "/logout")
    public ModelAndView logout(HttpSession sess){
        sess.invalidate();
        model.addObject("view","home");
        return model;
    }

can i have some answers with some examples.

Thanks for helping

From the javadocs

NOTE: Session attributes as indicated using this annotation correspond to a specific handler's model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session. Therefore, use this facility for such conversational attributes which are supposed to be stored in the session temporarily during the course of a specific handler's conversation.

For permanent session attributes, eg a user authentication object, use the traditional session.setAttribute method instead. Alternatively, consider using the attribute management capabilities of the generic WebRequest interface.

When using SessionAttributes typically you use SessionStatus setComplete

I think you might be better off using spring security with an authentication provider and something like UsernamePasswordAuthenticationToken. Your user/principal would be accessible via SecurityContextHolder and included in the HttpSession. When using spring security you then could use/configure a LogoutConfigurer to invalidate the session and clears the SecurityContextHolder context and sets the authentication to null.

Side note: I hope this isn't for anything other than a demo/poc as it appears that you are storing passwords as plain text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM