Filter

Filter:过滤器,用来过滤网站的数据,如处理中文乱码、登陆验证等。

1. 步骤

  1. 编写一个类,实现Filter接口,并重写对应的方法。

    package com.gs.filter;
    
    import jakarta.servlet.*;
    import java.io.IOException;
    
    /**
     * @author admin
     */
    public class CharacterEncodingFilter implements Filter {
        @Override
        public void init(FilterConfig config) throws ServletException {
        }
    
        @Override
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            chain.doFilter(request, response);
        }
    }
    
  2. web.xml中配置Filter

    <filter>
      <filter-name>CharacterEncodingFilter</filter-name>
      <filter-class>com.gs.filter.CharacterEncodingFilter</filter-class>
    </filter>
    
    <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <url-pattern>/hello/*</url-pattern>
    </filter-mapping>
    
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:52

results matching ""

    No results matching ""