JavaWeb_创建HttpFilter

package com.demo.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义HttpFilter,实现Filter接口
 */
public abstract class HttpFilter implements Filter {

    //用于保存filterConfig对象
    private FilterConfig filterConfig;

    /**
     * 不建议子类直接覆盖,若直接覆盖,有可能会导致filterConfig成员变量初始化失败
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        init();
    }

    /**
     * 供子类继承的初始化方法,可以通过getFilterConfig()获取FilterConfig对象
     */
    protected void init() {
    }

    /**
     * 直接返回init(ServletConfig)的FilterConfig对象
     * @return
     */

    public FilterConfig getFilterConfig() {
        return filterConfig;
    }

    /**
     * 原生的doFilter方法,在方法内部把ServletRequest和ServletResponse
     * 转为了HttpServletRequest和HttpServeltResponse,并调用了doFilter(HttpServletResponse response, HttpServletRequest request,FilterChain filterChain)
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        doFilter(servletRequest,servletResponse,filterChain);
    }
    //抽象方法,为Http请求定制,必须实现的方法
    public abstract void doFilter(HttpServletResponse response, HttpServletRequest request,FilterChain filterChain) throws IOException, ServletException;

    @Override
    public void destroy() {}
}

  

上一篇:基于SpringMVC的拦截器(Interceptor)和过滤器(Filter)的区别与联系


下一篇:java 获取客户端的ip地址