2014-08-29 61 views
1

在我的程序中,/Controller/*形式的任何url被我的servlet映射重定向到Controller類。我的servlet映射破壞我的過濾器

我試圖爲authantication添加一個過濾器,如果用戶沒有登錄並且路徑不是/Controller/RegForm它將重定向到/Controller/RegForm

問題是因爲我的servlet映射重定向到/Controller,過濾器始終獲取/Controller作爲路徑。

如何使用過濾器和servlet映射?

這是我web.xml

<filter> 
    <filter-name>AuthFilter</filter-name> 
    <filter-class>AuthFilter</filter-class> 
</filter> 
<filter-mapping> 
    <filter-name>AuthFilter</filter-name> 
    <url-pattern>/Controller/*</url-pattern> 
</filter-mapping> 
<servlet> 
    <servlet-name>Controller</servlet-name> 
    <servlet-class>Controller</servlet-class> 
</servlet> 

<servlet-mapping> 
    <servlet-name>Controller</servlet-name> 
    <url-pattern>/Controller/*</url-pattern> 
</servlet-mapping> 

<session-config> 
    <session-timeout> 
     30 
    </session-timeout> 
</session-config> 

我的過濾器:

@WebFilter("/Controller/*") 
public class AuthFilter implements Filter { 

@Override 
public void init(FilterConfig config) throws ServletException { 
    // If you have any <init-param> in web.xml, then you could get them 
    // here by config.getInitParameter("name") and assign it as field. 
} 

@Override 
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
    HttpServletRequest request = (HttpServletRequest) req; 
    HttpServletResponse response = (HttpServletResponse) res; 
    HttpSession session = request.getSession(false); 
    String path = ((HttpServletRequest) request).getServletPath(); 

    if ((session != null && session.getAttribute("student") != null)||(excludeFromFilter(path))) { 
      chain.doFilter(req, res); // Log 
     } 
    else { 
     response.sendRedirect("/registration-war/Controller/RegForm"); // No logged-in user found, so redirect to login page. 
    } 
} 

private boolean excludeFromFilter(String path) { 
    if (path.equals("/Controller/RegForm")) { 
     return true; // add more page to exclude here 
    } else { 
     return false; 
    } 
} 
+0

你能告訴我們你的過濾器實現嗎? – icza 2014-08-29 07:27:27

+0

編輯帖子 – hece 2014-08-29 07:30:10

回答

1

您使用HttpServletRequest.getServletPath()返回servlet的URL是(根據你的servlet映射)"/Controller"

您希望path info沒有servlet路徑:

返回與當提出這個要求客戶端發送的URL相關的任何額外的路徑信息。額外的路徑信息在servlet路徑之後,但在查詢字符串之前,並以「/」字符開頭。

因此,例如,如果您的用戶請求/Controller/RegForm頁面,這將返回"/RegForm"

String pathInfo = HttpServletRequest.getPathInfo(); 
+0

感謝您的幫助 – hece 2014-08-29 07:43:19