1. 过滤器可以动态的拦截请求和响应, 且Filter在Servlet之前执行.
  2. 过滤器常用语编码过滤,用户是否登录,权限判断等.
  3. 通过 implements javax.servlet.Filter 实现一个过滤器

以字符编码过滤器为例

package cn.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharSetFilter implements Filter {

    private String encode = "utf-8";

    /**
     * init()用于初始化工作
     * filterConfig.getInitParameter("charset")获取web.xml中配置的内容
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String defaultCharset = filterConfig.getInitParameter("charset").trim();
        this.encode = "".equals(defaultCharset) ? this.encode : defaultCharset;
        System.out.println("init complete...");
    }

    
    /**
     * doFilter()完成实际的过滤工作 FilterChain用于访问后续过滤器
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        req.setCharacterEncoding(encode);
        res.setCharacterEncoding(encode);
                System.out.println("doFilter...");
        filterChain.doFilter(request, response);
    }

    /**
     * Servlet容器在销毁过滤器实例前调用destroy()方法,释放Servlet过滤器占用的资源。
     */
    @Override
    public void destroy() {
        System.out.println("destroy complete...");
    }

}
<filter>
        <filter-name>charSetFilter</filter-name>
        <filter-class>cn.config.CharSetFilter</filter-class>
        <init-param>
            <param-name>charset</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>contentType</param-name>
            <param-value>text/html;charset=UTF-8</param-value>
        </init-param>
    </filter>
        <!-- 
         多个filter,按照filter-mapping的执行顺序执行,
         而不是按照filter的定义顺序 
         -->
    <filter-mapping>
        <filter-name>charSetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

使用Servlet的示例代码,此处会先后输出init complete...和doFilter...

标签: Spring, Spring Boot

添加新评论