英文:
Keep a user session on Spring MVC
问题
我有一个Spring MVC网络应用程序,在该应用程序上用户能够登录并注册账户。我正尝试在用户登录后保持会话,一旦用户登出,会话就结束了。
实现这一目标的最佳方法是什么?
以下是我的登录控制器。
@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", "用户名或密码错误!");
}
return mav;
}
}
英文:
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;
}
}
答案1
得分: 1
好的,以下是翻译好的内容:
-
如果你想要“练习”一些底层的东西是如何工作的,你可以简单地调用
request.getSession()
在登录时创建会话并保存一些信息在其中。在登出时调用session.invalidate()
,就完成了。 -
如果你觉得准备好了,想要更加流畅的处理事情,你也可以尝试在你的Spring MVC项目中使用 Spring Security。不过,如果你没有之前的经验,开始使用它可能会相当复杂。
英文:
It depends:
-
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. Callsession.invalidate()
on logout and you are done. -
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论