javaweb中filter的配置和使用

  • 2015-09-10
  • 浏览 (93)

Servlet过滤器是在Java Servlet规范2.3中定义的,它能够对Servlet容器的请求和响应对象进行检查和修改。下面是filter的简单配置和使用:


在web.xml中的配置:

<filter>
    <description>acess filter</description>
    <display-name>accessFilter</display-name>
    <filter-name>AccessFilter</filter-name>
    <filter-class>com.seaxiang.interceptor.AccessFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>AccessFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

个别参数说明:

init-param        为过滤器实例提供初始化参数,可以有多个
url-pattern       指定和过滤器关联的URL,”/*”表示所有URL,"/*.jsp"表示匹配所有的jsp页面


java代码:

public class AccessFilter implements Filter {
    private final Logger log = LoggerFactory.getLogger(AccessFilter.class);
    String encoding = null;
    public AccessFilter() {
        
    }

    public void destroy() {
        //filter销毁前的处理
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        //在该请求向后续传递之前做一些处理

        doSomething.....
      
        chain.doFilter(request, response);  //将该请求向后续传递
        
        //后续操作返回后做一些处理
        HttpServletResponse rep = (HttpServletResponse) response;
        int status = rep.getStatus();
        if(status == 404){
            log.info("404");
        }
    }

    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("encoding");//获取filter配置的参数值
        System.out.println(encoding);
    }
}

正文到此结束