2012-05-25 40 views
0

我新的春天和春天 Tomcat的出於某種原因
我不使用春季安全開發動態Web應用程序。我想阻止用戶訪問登錄頁面誰
已經在session.Here是我的代碼:如何限制登錄用戶在春季訪問登錄頁面而不使用彈簧安全性?

@Controller 
@RequestMapping("/login") 
@SessionAttributes("userAuthenticator") 
public class LoginController { 

    @RequestMapping(method = RequestMethod.GET) 
    public String showLogin(ModelMap model, HttpServletRequest request) { 
    System.out.println("Current Session: " + request.getSession(false)); 

    if (request.getSession(false) == null) { 
    System.out.println("This means a new user wants to access the login page"); 
    return "login"; 
    } 

    else{ 
    //means the user is already in session.So move him to another page say display.jsp 
    //actually I have done here with some other checking like getUserName() from 
    the model "UserAuthenticator" and if its again null redirect to login page. 
    } 

現在忘了其他 part.When我輸入的網址在我瀏覽器
第一次:..../AccountCreation/login.htm
控制檯輸出:

Current Session: null 
This means a new user wants to access the login page 

由於新用戶正在訪問該頁面,因此看起來絕對正常(登錄頁面也出現)。

當我重新進入的URL甚至刷新控制檯輸出來的頁面:

Current Session: [email protected] 

沒有那屆從何而來?
(出於這個原因,在我的其他部分我:「該網頁有重定向循環」在我的瀏覽器)

任何人都可以給我建議的方式來實現我的目標,而無需使用春季安全
這是非常需要的,我現在.....

謝謝...

回答

2

您可以使用會話變量。

HttpSession ses=request.getSession(false); 
if(ses.getAttribute("sessionVar") == null) 
    //show login page 
else 
    // don't show login page 

設置會話變量:

HttpSession ses=request.getSession(); 
ses.setAttribute("sessionVar","someValueToShowSession"); 
1

環節,儘快啓動用戶發出第一個請求的頁面。所以第二次訪問總是會給一個有效的會話。

如果你想檢查他是否是認證用戶,那麼你需要在會​​話中自己設置一些標誌/值。就像userId一樣。 Tehn你可以檢查

如果userId在會話 - >有效用戶 - >重定向中設置。

如果userId未在會話中設置 - >未登錄用戶 - >允許登錄頁面。

+0

我發現Spring在用戶向登錄頁面發出請求時是否啓動會話,無論是否存在'@SessionAttributes()'。所以唯一的方法就是像你說的那樣存儲特定的會話值。 – mukund

0

這只是預期的行爲。當您第一次登錄會話時,jsessionid cookie會存儲在瀏覽器中。除非使用session.invalidate()使會話無效,否則會話超時將導致HttpSession可用於該瀏覽器窗口。

如果您想限制已登錄的用戶通過鍵入登錄頁面url來查看登錄頁面,則創建一個攔截器並檢查用戶是否已登錄。如果用戶已經登錄,那麼將他重定向到主頁...否則允許他進入登錄頁面。