2011-02-13 61 views

回答

4

這樣做:

  1. 當用戶登錄,設置User對象在HttpSession中該用戶。這樣,httpRequest.getSession().setAttribute("LOGGED_USER", userObject)

  2. 現在,每次你點擊過濾器/安全過濾器。你要做的第一件事就是檢查這個屬性。

  3. 如果該屬性不存在,請將該請求重定向/轉發到登錄servlet。

的僞碼是這樣的:

//in your login servlet, on successful login 
request.getSession().setAttribute("LOGGED_USER", userObject); 

//in your security filter 
if(request.getSession().getAttribute("LOGGED_USER") == null){ 
//optionally, you may like to check if that attribute has a valid userId as well 
    RequestDispatcher rd = request.getRequestDispatcher("relative/path/to/login/servlet") 
    rd.forward(request, response); 
    return; 
} 

編輯1:看到此http://download.oracle.com/javaee/5/tutorial/doc/bncbx.html

+0

@Saska更新答案 – Nishant 2011-02-13 17:27:38

2

在過濾器: IF UserObjectInSession存在=>用戶登錄 否則重定向到servlet

在servlet的: 如果驗證()是正確=>把UserObjectInSession會話

public void doFilter(ServletRequest request, ServletResponse response, 
     FilterChain chain) throws IOException, ServletException {  
    HttpServletRequest httpReq = (HttpServletRequest) request; 
    HttpServletResponse httpRes = (HttpServletResponse) response; 

    HttpSession session = httpReq.getSession(); 
    User currentUser = (User)session.getAttribute("userInSession"); 

    if (currentUser == null) { 
     httpRes.sendRedirect("...") //redirect to LoginServlet 
    } else {   
     chain.doFilter(request, response); 
    } 
} 
相關問題