【发布时间】:2020-05-06 13:01:30
【问题描述】:
对不起,如果这是一件显而易见的事情,但我对编程很陌生。我的应用程序能够登录/注册用户,但是一旦我导航到应用程序中的不同页面然后返回用户页面,它就像我没有登录一样。我不确定如何让它记住我已经登录。我假设我需要将会话数据从我的用户控制器传递到我的另一个控制器类。但老实说,我只是迷路了。任何帮助将不胜感激。
我的验证码
public static final String userSessionKey = "user";
public User getUserFromSession(HttpSession session) {
Integer userId = (Integer) session.getAttribute(userSessionKey);
if (userId == null) {
return null;
}
Optional<User> user = userDao.findById(userId);
if (user.isEmpty()) {
return null;
}
return user.get();
}
public static void setUserInSession(HttpSession session, User user) {
session.setAttribute(userSessionKey, user.getId());
}
我的登录代码(我登录后的事件,如果我再次点击登录选项卡,它会将我带到登录路径而不是用户帐户路径。)
@RequestMapping(value = "login", method = RequestMethod.GET)
public String displayLogin(HttpServletRequest session, Model model){
if (session.getAttribute(userSessionKey) == null){
model.addAttribute("title", "Login");
model.addAttribute("users", userDao.findAll());
return "user/login";
}
return "user/account";
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String processLogin(@RequestParam(name = "password") String password,
@RequestParam(name = "email")String email,
Model model){
for(User theUser: userDao.findAll()){
if(theUser.getEmail().equals(email) && theUser.getPassword().equals(password)) {
model.addAttribute("userAccount", theUser);
return "user/account";
}else{
model.addAttribute("invalidCredentials", true);
}
}
return "user/account";
}
我如何尝试在我的其他课程中对其进行测试的示例(真的不确定我的方法是否接近)
@OneToOne
public UserController userController;
@Autowired
private PaoDao paoDao;
@Autowired
private UserDao userDao;
@RequestMapping(value = "remove", method = RequestMethod.GET)
public String displayRemovePaoForm(HttpSession session, Model model) {
if (userController.getUserFromSession() == null){
model.addAttribute("title", "Login");
model.addAttribute("users", userDao.findAll());
return "redirect:login";
}
model.addAttribute("paos", paoDao.findAll());
model.addAttribute("title", "Remove Pao");
return "pao/remove";
}
我只想登录并保持登录状态,直到我退出,我不知道该怎么做。感谢您的帮助。
【问题讨论】:
标签: java spring-boot spring-mvc authentication session