编写filter过滤器有两种方法,一种是使用注解配置,另一种是使用web.xml配置,此处使用web.xml配置来实现过滤器

(1)使用web.xml配置过程

  <filter>
    <filter-name>setCharacterFilter</filter-name>
    <filter-class>com.qst.setCharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>setCharacterFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

(2)过滤器主体demo

public class setCharacterEncodingFilter implements Filter{
    
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        //Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response);
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        //Filter.super.init(filterConfig);
    }

}

通过过滤器,我们可以实现统一的对请求和响应中文乱码问题的配置,不用在每次请求和响应的demo中都去设置utf-8的编码

posted on 2020-04-12 09:30  樱花飘落の季節  阅读(356)  评论(0编辑  收藏  举报