星期四, 4月 11, 2013

[Java] Filter Url-Pattern 筆記

久久用一下常常會忘記怎麼正確的設定Filter Url-Pattern,
趁著昨天需要用到,筆記一遍。

第一種解法(舊方法):
http://fecbob.pixnet.net/blog/post/38258307-tomcat-default-servlet-%E7%9A%84url-pattern

filter-mapping在web.xml中定義的順序相同。
在web.xml檔中,以下語法用於定義映射:
  1.  以」/’開頭和以」/*」結尾的是用來做路徑映射的。
  2.  以首碼」*.」開頭的是用來做擴展映射的。
  3. 「/」 是用來定義default servlet映射的。
  4.  剩下的都是用來定義詳細映射的。比如: /aa/bb/cc.action


所以,為什麼定義」/*.action」這樣一個看起來很正常的匹配會錯?因為這個匹配即屬於路徑映射,也屬於擴展映射,導致容器無法判斷。

第二種解法:
http://k2java.blogspot.in/2011/04/servlet-filter-mapping-exclude-pattern.html

透過設定init-parm的方式帶入忽略的URL,並透過Regex來處理

Servlet filter mapping exclude pattern

Once you apply a filter to a URL pattern:
<filter-mapping>
    <filter-name>theFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
/*
there's no option in web.xml to exclude a more specific pattern such as: /public/*.

But you can put the exclusion logic in the filter itself:


<filter>
    <filter-name>theFilter</filter-name>
    <filter-class>org.demo.CustomServletFilter</filter-class>
    <init-param>
 <param-name>excludePatterns</param-name>
 <param-value>public/*</param-value>
    </init-param>
</filter>
org.demo.CustomServletFilter excludePatterns public/*

And in the filter code:
public void init(FilterConfig cfg) throws ServletException {
 this.excludePatterns = cfg.getInitParameter("excludePatterns");
 .
 .
 .
}

public void doFilter(ServletRequest request,
           ServletResponse response,
    FilterChain chain) 
 throws IOException, ServletException {
 String url = request.getRequestURL().toString();
 if (matchExcludePatterns(url)) {
     chain.doFilter(request, response);
     return;
 }
 .
 .
 .
}

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails