servlet中Filter接口介绍

本文介绍了Servlet中的Filter接口,讲述了过滤器在处理请求和响应中的作用,以及其生命周期中的init、doFilter和destroy方法。init方法在应用启动时调用,用于初始化过滤器;doFilter方法在每次请求时调用,可以访问并处理ServletRequest和ServletResponse;destroy方法在过滤器停止服务前调用。此外,还强调了FilterChain在调用链中的角色和顺序的重要性。
摘要由CSDN通过智能技术生成

      过滤器是指拦截请求,并对传给被请求资源的ServletRequest 或 ServletResponse 进行处理的一个对象。过滤器可以用于登录、加密和解密、会话检查等等。过滤器可以配置为拦截一个或多个资源。如果同一个资源或同一组资源中应用了多个过滤器,则调用顺序有显示显得比较重要,这时候就需要部署描述符(web.xml)来控制其先后顺序。


       filter过滤器中使用的接口包括Filter、FilterConfig和FilterChain。每个接口中包含若干方法,接下来我们按照filter的生命周期来介绍接口及中间对应的方法。


       过滤器类必须实现javax.servlet.Filter接口。这个接口为每个过滤器暴露3个生命周期方法,init、doFilter 和 destory。

package javax.servlet;

import java.io.IOException;

/**
 * A filter is an object that performs filtering tasks on either the request to
 * a resource (a servlet or static content), or on the response from a resource,
 * or both. <br>
 * @since Servlet 2.3
 */
public interface Filter {

    /**
     * Called by the web container to indicate to a filter that it is being
     * placed into service. The servlet container calls the init method exactly
     * once after instantiating the filter. The init method must complete
     * successfully before the filter is asked to do any filtering work. <br>
     * <br>
     * The web container cannot place the filter into service if the init method
     * either<br>
     * 1.Throws a ServletException <br>
     * 2.Does not return within a time period defined by the web container
     */
    public void init(FilterConfig filterConfig) throws ServletException;

    /**
     * The <code>doFilter</code> method of the Filter is called by the container
     * each time a request/response pair is passed through the chain due to a
     * client request for a resource at the end of the chain. The FilterChain
     * passed in to this method allows the Filter to pass on the request and
     * response to the next entity in the chain.
     * <p>
     * A typical implementation of this method would follow the following
     * pattern:- <br>
     * 1. Examine the request<br>
     * 2. Optionally wrap the request object wi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值