Use of filter filter in java web

There are two ways to write a filter filter, one is to use annotation configuration, the other is to use web.xml configuration, here use web.xml configuration to implement the filter

(1) Use web.xml configuration process

  <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 of filter body

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);
    }

}

Through the filter, we can achieve a unified configuration of the Chinese character garbled request and response, without having to set the UTF-8 encoding in each request and response demo

Guess you like

Origin www.cnblogs.com/yinghuapiaoluo/p/12683747.html