简体   繁体   English

在 Spring MVC 上保留用户 session

[英]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.我有一个 Spring MVC web 应用程序,用户可以在该应用程序上登录并注册一个帐户。 I am trying to keep a session once a user is logged in and once the user logs out the session is over.我试图在用户登录后保留 session 并且一旦用户注销 session 就结束了。

What would be the best way to implement this?实现这一点的最佳方法是什么?

The following is my login controller.以下是我的登录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.如果你想“练习”低级别的东西是如何工作的,你可以简单地调用request.getSession()在登录时创建 session 并在那里保存一些东西。 Call session.invalidate() on logout and you are done.注销时调用session.invalidate()就完成了。

  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.如果您对此感到满意并希望事情更加精简,您还可以尝试在 Spring MVC 项目之上进入Spring Security Though, it is quite complex to get started if you have no prior experience with it.但是,如果您之前没有这方面的经验,那么上手非常复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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