简体   繁体   中英

Keep a user session on Spring MVC

I have a Spring MVC web application on which users are able to login and register an account. I am trying to keep a session once a user is logged in and once the user logs out the session is over.

What would be the best way to implement this?

The following is my login controller.

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("login");
        mav.addObject("login", new Login());
        return mav;
    }

    @RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
    public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute("login") Login login) {
        ModelAndView mav = null;
        User user = userService.validateUser(login);
        if (null != user) {
            mav = new ModelAndView("loginProcess", "firstname", user.getFirstname());
        } else {
            mav = new ModelAndView("login");
            mav.addObject("message", "Username or Password is wrong!!");
        }
        return mav;
    }
}

It depends:

  1. If you want to "practice" how lower-level stuff works, you could simple call request.getSession() to create the session upon login and save something there. Call session.invalidate() on logout and you are done.

  2. If you feel up for it and want things a bit more streamlined, you could also try and get into Spring Security on top of your Spring MVC project. Though, it is quite complex to get started if you have no prior experience with it.

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