2015-11-26 71 views
1

我的問題是這樣的: 我需要使用Spring mvc實現登錄/註銷功能。我的方法如下。 我有一個LoginController處理get和post方法。如何在Spring中管理會話mvc

@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,我將被重定向到索引,就像我被記錄一樣。 那麼,我該怎麼辦?

+1

只需使用[SpringSecurity](http://projects.spring.io/spring-security/)。它很容易和成熟,並有幾十個接口 – Stefan

+0

這將是很好的。但是我沒有足夠的時間來了解它。你知道其他解決方法嗎? – Suncatcher

回答

0

首先,「if(sessionController.getSessionUserDto()!= null)」在首次登錄後可能始終爲真,因此請檢查您的代碼。 其次,不要在Controller中使用類作用域變量,因爲它是單例,用戶會覆蓋其他數據。

+0

我明白了。因此,如果我想在sessionController中存儲用戶憑據,並且不要在控制器中使用類作用域變量,那麼我應該在哪裏放置sessionController變量? – Suncatcher

+0

用戶信息應該存儲在請求或上下文範圍的會話變量中。每個客戶端(機器)應該與您的服務器開啓新的會話。 –

+0

你能提供一些代碼來理解嗎? – Suncatcher