过滤器Filter使用

2019-07-14 11:58发布

过滤器Filter也具有生命周期:init()->doFilter()->destroy(),由部署文件中的filter元素驱动。在servlet2.4中,过滤器同样可以用于请求分派器,但须在web.xml中声明,INCLUDE或FORWARD或REQUEST或ERROR该元素位于filter-mapping中。

一、批量设置请求编码


Java代码
public class EncodingFilter implements Filter {   
  
    private String encoding = null;   
  
    public void destroy() {   
         encoding = null;   
     }   
  
    public void doFilter(ServletRequest request, ServletResponse response,   
             FilterChain chain) throws IOException, ServletException {   
         String encoding = getEncoding();   
        if (encoding == null){   
             encoding = "gb2312";   
         }   
         request.setCharacterEncoding(encoding);// 在请求里设置上指定的编码   
         chain.doFilter(request, response);   
     }   
  
    public void init(FilterConfig filterConfig) throws ServletException {   
        this.encoding = filterConfig.getInitParameter("encoding");   
     }   
  
    private String getEncoding() {   
        return this.encoding;   
     }   
  
 

Xml代码
  
    EncodingFilter  
    com.logcd.filter.EncodingFilter  
      
       encoding  
       gb2312  
      
  
  
  
   EncodingFilter  
   /*  
  


二、用filter控制用户访问权限


Java代码
public class SecurityFilter implements Filter {
   public void doFilter(ServletRequest request,