@WebFilter用于不同类型的不同init参数

时间:2013-09-17 15:38:25

标签: servlets annotations servlet-filters web.xml servlet-3.0

我正在将基于Servlet 2.5的webapp迁移到Servlet 3.0,并遇到了这个问题,我不知道如何将这些不同的过滤器映射压缩为该类的一个@WebFilter注释。

过滤器:

<!-- Day is 12 hours, so if we update at night the new content will be fetched first     thing in the morning -->
<filter>
    <filter-name>CacheForDay</filter-name>
    <filter-class>x.web.client.filter.CacheHeaderFilter</filter-class>
    <init-param>
        <param-name>CacheTime</param-name>
        <param-value>43200</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>CacheForWeek</filter-name>
    <filter-class>x.web.client.filter.CacheHeaderFilter</filter-class>
    <init-param>
        <param-name>CacheTime</param-name>
        <param-value>604800</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>CacheForMonth</filter-name>
    <filter-class>x.web.client.filter.CacheHeaderFilter</filter-class>
    <init-param>
        <param-name>CacheTime</param-name>
        <param-value>18144000</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>noCache</filter-name>
    <filter-class>x.web.client.filter.CacheHeaderFilter</filter-class>
    <init-param>
        <param-name>CacheTime</param-name>
        <param-value>0</param-value>
    </init-param>
</filter> 

过滤器 - 映射:

<filter-mapping>
    <filter-name>CacheForDay</filter-name>
    <url-pattern>*.png</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>CacheForDay</filter-name>
    <url-pattern>*.gif</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>CacheForDay</filter-name>
    <url-pattern>*.js</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>CacheForDay</filter-name>
    <url-pattern>*.css</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>CacheForMonth</filter-name>
    <url-pattern>*.ico</url-pattern>
  </filter-mapping>

如何通过@WebFilter替换它们?

1 个答案:

答案 0 :(得分:3)

使用@WebFilter注释的单个类是不可能的。你必须要么:

  • 继续使用web.xml方式;考虑到这种情况,这还不错。
  • 在基类中实现逻辑并编写简单的扩展,并使用相应的@WebFilter进行注释。我觉得这样看起来不太好。

后来的例子:

public class BaseCacheFilter implements Filter
{
    public void doFilter(...) {
        ...implementation here...
    }
    ....
}

@WebFilter(
    urlPatterns={"*.png","*.gif",...},
    initParams=@WebInitParam(name="CacheTime",value="43200")
)
public class CacheForDay extends BaseCacheFilter
{ /* EMPTY */ }