2012-04-19 56 views
3

我試圖讓一個過濾器,以阻止誰沒有在訪問某些pages.For登錄的用戶頁面這個我犯了一個過濾器類有以下doFilter方法Java過濾器重定向誰沒有登錄用戶登錄

HttpServletRequest request = (HttpServletRequest) req; 
HttpServletResponse response = (HttpServletResponse) res; 
String url = request.getRequestURI(); 
boolean allowedRequest = false; 

System.out.println(url); 

if(urlList.contains(url)) { 
    allowedRequest = true; 
    System.out.println("in list"); 
} 

if (!allowedRequest) { 
    Object o = request.getSession().getAttribute("UserInfo"); 
    if (null == o) { 
     System.out.println("Hey i am in"); 
     response.sendRedirect("/login.jsp"); 
    } 
} 

chain.doFilter(req, res); 

} // end of doFilter 

要允許我在init建立一個ArrayList的URL列表()

現在一個很奇怪的愚蠢的事情是發生在登錄其不列入需要用戶的頁面。假設我有兩個頁面home.jsp和dcr.jsp。當我嘗試訪問home.jsp而無需登錄,我成功重定向到login.jsp,但是當我試圖訪問dcr.jsp時,雖然它進入循環,但如果(空== o)我不能重定向因爲我得到這條線在console.THis打印的是,我在服務器 得到的輸出。這是我在服務器

/dcrmaintenance.jsp 

Hey i am in 

告訴我,空== o視爲真正得到的輸出。

頁面dcr.jsp訪問一個會話對象,因爲用戶沒有登錄它得到java.lang.NullPointerException異常,但我不明白爲什麼即使進入循環後重定向不發生。如果某人可以找出我犯了一個錯誤,這將不勝感激。

回答

9

response.sendRedirect("/login.jsp");後做return;

3

我相信你應該調用sendRedirect或doFilter。例如。

if (requiresLogin) 
    response.sendRedirect("/login.jsp"); 
else 
    chain.doFilter(req,resp); 
0
chain.doFilter(req, res); 

在您的應用程序中運行了哪些其他過濾器?您發送重定向,但繼續使用過濾器鏈。我想另一個過濾器是再次修改響應。如果你留在你的過濾器,只需在重定向後返回。

而不是過濾器,在Java WebApp中,您可以在web.xml中定義安全約束。看看安全約束

短的例子:

<security-constraint> 
    <web-resource-collection> 
    <web-resource-name>Restricted Area</web-resource-name> 
    <url-pattern>*</url-pattern> 
    </web-resource-collection> 
    <auth-constraint> 
    <role-name>Authorized</role-name> 
    </auth-constraint> 
</security-constraint> 
+0

我沒有任何其他的濾波器。其他的解決辦法worked.But我會檢查出來我怎麼可以使用安全約束!謝謝。 – Shamik 2012-04-19 10:43:27

0

我認爲你必須改變你的web.xml ...... 你必須把你的資源有限,以相應的文件夾。通過這種方式,Filter Servlet將限制在「受限制」文件夾中分配的文件。(http://www.developer.com/security/article.php/3467801/Securing-J2EE-Applications-with-a-Servlet-Filter.htm)(我認爲使用Filter Servlet的原因是編寫自己的授權系統 - 通過這種方式,您不必在Web中定義安全約束.XML,你必須在數據庫中定義它;))))

<!--Servlet Filter that handles site authorization.--> 
<filter> 
    <filter-name>AuthorizationFilter</filter-name> 
    <filter-class>examples.AuthorizationFilter</filter-class> 
    <description>This Filter authorizes user access to application 
        components based upon request URI.</description> 
    <init-param> 
     <param-name>error_page</param-name> 
     <param-value>../../login.html</param-value> 
    </init-param> 
</filter> 

<filter-mapping> 
    <filter-name>AuthorizationFilter</filter-name> 
    <url-pattern>/restricted/*</url-pattern> 
</filter-mapping> 
相關問題