[英]How to manage Session in Spring mvc
我的問題是:我需要使用Spring mvc實現登錄/注銷功能。 我的方法如下。 我有一個LoginController處理get和post方法。
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
if (sessionController.getSessionUserDto() != null) {
return "redirect:/secure/admin/index";
}
UserDto dto = new UserDto();
model.addAttribute("userDto", dto);
return "/login";
}
我有一個SessionController,它是一個保存用戶憑證的會話范圍的bean。 這是我的POST方法。
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String executeLogin(@ModelAttribute("userDto") UserDto userDto, BindingResult result,
HttpServletRequest request) {
String[] suppressedFields = result.getSuppressedFields();
if (suppressedFields.length > 0) {
throw new RuntimeException("Attempting to bind disallowed fields: "
+ StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
if (userDto.getUser() == null || userDto.getUser().isEmpty()) {
return "/login";
}
if (userDto.getPassword() == null || userDto.getPassword().isEmpty()) {
return "/login";
}
try {
UserDto dto = userManager.login(userDto.getUser(), userDto.getPassword());
if (dto != null) {
sessionController.setSessionUserDto(dto);
request.getSession().setAttribute("terminal", request.getRemoteAddr());
return "redirect:/secure/admin/index";
} else {
return "/login";
}
} catch (DaoException ex) {
System.out.println("DaoException: " + ex.getMessage());
return "redirect:/login";
}
}
問題在於,每個登錄到系統的用戶始終會覆蓋存儲在SessionController中的用戶。 也就是說,sessionController在整個應用程序中僅持有一個用戶。 如果我登錄計算機A,然后打開計算機B並請求http:// localhost:8080 / webapp / login ,則將被重定向到索引,就像登錄一樣。 所以我該怎么做?
我強烈建議您使用Spring Security。 您可以使用默認配置並對應用程序進行身份驗證。
http://www.mkyong.com/tutorials/spring-security-tutorials/ https://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
如果需要自定義身份驗證,則需要使用Authentication Provider 。 這里有一個例子
http://www.baeldung.com/spring-security-authentication-provider
首先,“ if(sessionController.getSessionUserDto()!= null)”在首次登錄后可能始終為true,因此請查看您的代碼。 其次,不要在Controller中使用類范圍變量,因為它是單例的,用戶將互相覆蓋數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.