Filter过滤器

1.过滤器要实现Filter接口   import javax.servlet.*

public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request,response);  //如果不写chain 将被阻塞在这
    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }
}

2. 在web.xml中注册Filter

<filter>
        <filter-name>filter</filter-name>
        <filter-class>com.cai.filter.EncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>*</url-pattern>  
    </filter-mapping>

 

posted on 2020-11-23 22:12  Difcipo  阅读(81)  评论(0编辑  收藏  举报

导航