JavaWeb过滤器Filter(附tomcat部分源码分析)

实现接口 Filter// 由web容器调用在filter实例化后调用一次,可以用来配置filter的初始信息等// 执行该过滤器逻辑,由ApplicationFilterChain过滤器链统一调用// 有web容器调用进行销毁}写一个简单的过滤器,当用户已登录或者请求的页面是首页时不进行过滤拦截继续请求下一个过滤器,否则跳转回首页进行登录。...
摘要由CSDN通过智能技术生成

🚀 优质资源分享 🚀

学习路线指引(点击解锁) 知识定位 人群定位
🧡 Python实战微信订餐小程序 🧡 进阶级 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。
💛Python量化交易实战💛 入门级 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统

过滤器Filter

过滤器通常对一些web资源进行拦截,做完一些处理器再交给下一个过滤器处理,直到所有的过滤器处理器,再调用servlet实例的service方法进行处理。过滤器可以对request进行处理也可以对response进行处理。

处理顺序

如果过滤器链顺序如上图所示,那么对request请求的处理顺序为1、2、3,对response响应的处理顺序为3、2、1.

使用场景

用户权限验证

防止乱码统一对请求和响应设置编码

对响应数据压缩等等

自定义过滤器

实现接口 Filter

public interface Filter {
    
    // 由web容器调用在filter实例化后调用一次,可以用来配置filter的初始信息等
    public void init(FilterConfig filterConfig) throws ServletException;

   
    // 执行该过滤器逻辑,由ApplicationFilterChain过滤器链统一调用 
    public void doFilter(ServletRequest request, ServletResponse response,
 FilterChain chain) throws IOException, ServletException;

    // 有web容器调用进行销毁 
    public void destroy();
}

写一个简单的过滤器,当用户已登录或者请求的页面是首页时不进行过滤拦截继续请求下一个过滤器,否则跳转回首页进行登录。可以看到给LoginFilter类加了WebFilter注解,表明过滤器的名称、作用的servlet以及需要拦截的请求路径表达式,后续会将这个过滤器注册添加到web容器的过滤器链中。

@Slf4j(topic = "e")
@WebFilter(filterName = "loginFilter", servletNames = "dispatcher", urlPatterns = "*")
public class LoginFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    log.info("LoginFilter init");
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    log.info("LoginFilter doFilter");
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // 判断用户是否登录
    HttpSession session = req.getSession();
    String uri = req.getRequestURI();
    log.info("requestUri:" + uri);
    // 已经登录 | 首页 | 登录接口不拦截,其他情况重定向回首页
    if (LoginUtil.isLogin(session.getAttribute("username"))) {
      log.info("用户已登录");
      chain.doFilter(req, res);
    } else if (uri.equals(req.getContextPath() + "/") || uri.contains("login")) {
      log.info("请求首页/登录接口");
      chain.doFilter(req, res);
    } else {
      log.info("未登录请求转发到登录页");
      RequestDispatcher requestDispatcher = req.getRequestDispatcher("/");
      requestDispatcher.forward(req, res);
    }
  }

  @Override
  public void destroy() {

  }
}

当然也可以在web.xml文件中配置此过滤器同使用注解是相同的效果,如下:

  
 LoginFilter
 com.monian.study.filter.LoginFilter
 

  
 LoginFilter
 dispatcher
 *
 

请求接口日志如下

源码分析

FilterDef

这个类定义了过滤器的名称、全限定名、初始化参数等信息,有了这些信息web容器就可以实例化这个过滤器并进行一些初始化的配置操作,用来生成后续的ApplicationFilterConfig对象

FilterDef

 public class FilterDef implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final StringManager sm =
        StringManager.getManager(Constants.PACKAGE_NAME);

    // ------------------------------------------------------------- Properties


    /**
 * The description of this filter.
 */
    private String description = null;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }


    /**
 * The display name of this filter.
 */
    private String displayName = null;

    public String getDisplayName() {
        return this.displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }


    /**
 * The filter instance associated with this definition
 */
    private transient Filter filter = null;

    public Filter getFilter() {
        return filter;
    }

    public void setFilter(Filter filter) {
        this.filter = filter;
    }


    /**
 * The fully qualified name of the Java class that implements this filter.
 */
    private String filterClass = null;

    public String getFilterClass() {
        return this.filterClass;
    }

    public void setFilterClass(String filterClass) {
        this.filterClass = filterClass;
    }


    /**
 * The name of this filter, which must be unique among the filters
 * defined for a particular web application.
 */
    private String filterName = null;

    public String getFilterName() {
        return this.filterName;
    }

    public void setFilterName(String filterName) {
        if (filterName == null || filterName.equals("")) {
            throw new IllegalArgumentException(
                    sm.getString("filterDef.invalidFilterName", filterName));
        }
        this.filterName = filterName;
    }


    /**
 * The large icon associated with this filter.
 */
    private String largeIcon = null;

    public String getLargeIcon() {
        return this.largeIcon;
    }

    public void setLargeIcon(String largeIcon) {
        this.largeIcon = largeIcon;
    }


    /**
 * The set of initialization parameters for this filter, keyed by
 * parameter name.
 */
    private final Map parameters = new HashMap<>();

 public Map getParameterMap() {
 return this.parameters;
 }


 /**
 * The small icon associated with this filter.
 */
 private String smallIcon = null;

 public String getSmallIcon() {
 return this.smallIcon;
 }

 public void setSmallIcon(String smallIcon) {
 this.smallIcon = smallIcon;
 }

 private String asyncSupported = null;

 public String getAsyncSupported() {
 return asyncSupported;
 }

 public void setAsyncSupported(String asyncSupported) {
 this.asyncS
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值