JavaWeb中过滤器Filter的用法详解

目录
  • 过滤器Filter
    • 处理顺序
    • 使用场景
    • 自定义过滤器
  • 源码分析
    • FilterDef
    • FilterMap
    • 初始化过滤器
    • 创建过滤器链 ApplicationFilterChain
    • 执行过滤器链

过滤器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文件中配置此过滤器同使用注解是相同的效果,如下:

 <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>com.monian.study.filter.LoginFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>

请求接口日志如下

源码分析

FilterDef

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

 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<String, String> parameters = new HashMap<>();

    public Map<String, String> 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.asyncSupported = asyncSupported;
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Add an initialization parameter to the set of parameters associated
     * with this filter.
     *
     * @param name The initialization parameter name
     * @param value The initialization parameter value
     */
    public void addInitParameter(String name, String value) {

        if (parameters.containsKey(name)) {
            // The spec does not define this but the TCK expects the first
            // definition to take precedence
            return;
        }
        parameters.put(name, value);

    }

    /**
     * Render a String representation of this object.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("FilterDef[");
        sb.append("filterName=");
        sb.append(this.filterName);
        sb.append(", filterClass=");
        sb.append(this.filterClass);
        sb.append("]");
        return sb.toString();
    }

}

FilterMap

这个类主要定义了过滤器的名称、作用的serlvet、拦截的路径以及调度类型等信息,主要用来作为判断过滤器是否能应用在request上。

 public class FilterMap extends XmlEncodingBase implements Serializable {

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

    private static final long serialVersionUID = 1L;

    /**
     * The name of this filter to be executed when this mapping matches
     * a particular request.
     */

    public static final int ERROR = 1;
    public static final int FORWARD = 2;
    public static final int INCLUDE = 4;
    public static final int REQUEST = 8;
    public static final int ASYNC = 16;

    // represents nothing having been set. This will be seen
    // as equal to a REQUEST
    private static final int NOT_SET = 0;

    private int dispatcherMapping = NOT_SET;

    private String filterName = null;

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

    public void setFilterName(String filterName) {
        this.filterName = filterName;
    }

    // 过滤器作用的servlet的名称
    private String[] servletNames = new String[0];

    public String[] getServletNames() {
        if (matchAllServletNames) {
            return new String[] {};
        } else {
            return this.servletNames;
        }
    }

    public void addServletName(String servletName) {
        if ("*".equals(servletName)) {
            this.matchAllServletNames = true;
        } else {
            String[] results = new String[servletNames.length + 1];
            System.arraycopy(servletNames, 0, results, 0, servletNames.length);
            results[servletNames.length] = servletName;
            servletNames = results;
        }
    }

    /**
     * The flag that indicates this mapping will match all url-patterns
     */
    private boolean matchAllUrlPatterns = false;

    public boolean getMatchAllUrlPatterns() {
        return matchAllUrlPatterns;
    }

    /**
     * The flag that indicates this mapping will match all servlet-names
     */
    private boolean matchAllServletNames = false;

    public boolean getMatchAllServletNames() {
        return matchAllServletNames;
    }

    /**
     * 过滤器作用拦截的路径
     */
    private String[] urlPatterns = new String[0];

    public String[] getURLPatterns() {
        if (matchAllUrlPatterns) {
            return new String[] {};
        } else {
            return this.urlPatterns;
        }
    }

    public void addURLPattern(String urlPattern) {
        addURLPatternDecoded(UDecoder.URLDecode(urlPattern, getCharset()));
    }
    public void addURLPatternDecoded(String urlPattern) {
        if ("*".equals(urlPattern)) {
            this.matchAllUrlPatterns = true;
        } else {
            String[] results = new String[urlPatterns.length + 1];
            System.arraycopy(urlPatterns, 0, results, 0, urlPatterns.length);
            results[urlPatterns.length] = UDecoder.URLDecode(urlPattern);
            urlPatterns = results;
        }
    }

    /**
     * This method will be used to set the current state of the FilterMap
     * representing the state of when filters should be applied.
     * @param dispatcherString the dispatcher type which should
     *  match this filter
     */
    public void setDispatcher(String dispatcherString) {
        String dispatcher = dispatcherString.toUpperCase(Locale.ENGLISH);

        if (dispatcher.equals(DispatcherType.FORWARD.name())) {
            // apply FORWARD to the global dispatcherMapping.
            dispatcherMapping |= FORWARD;
        } else if (dispatcher.equals(DispatcherType.INCLUDE.name())) {
            // apply INCLUDE to the global dispatcherMapping.
            dispatcherMapping |= INCLUDE;
        } else if (dispatcher.equals(DispatcherType.REQUEST.name())) {
            // apply REQUEST to the global dispatcherMapping.
            dispatcherMapping |= REQUEST;
        }  else if (dispatcher.equals(DispatcherType.ERROR.name())) {
            // apply ERROR to the global dispatcherMapping.
            dispatcherMapping |= ERROR;
        }  else if (dispatcher.equals(DispatcherType.ASYNC.name())) {
            // apply ERROR to the global dispatcherMapping.
            dispatcherMapping |= ASYNC;
        }
    }

    public int getDispatcherMapping() {
        // per the SRV.6.2.5 absence of any dispatcher elements is
        // equivalent to a REQUEST value
        if (dispatcherMapping == NOT_SET) return REQUEST;

        return dispatcherMapping;
    }

    public String[] getDispatcherNames() {
        ArrayList<String> result = new ArrayList<>();
        if ((dispatcherMapping & FORWARD) != 0) {
            result.add(DispatcherType.FORWARD.name());
        }
        if ((dispatcherMapping & INCLUDE) != 0) {
            result.add(DispatcherType.INCLUDE.name());
        }
        if ((dispatcherMapping & REQUEST) != 0) {
            result.add(DispatcherType.REQUEST.name());
        }
        if ((dispatcherMapping & ERROR) != 0) {
            result.add(DispatcherType.ERROR.name());
        }
        if ((dispatcherMapping & ASYNC) != 0) {
            result.add(DispatcherType.ASYNC.name());
        }
        return result.toArray(new String[result.size()]);
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Render a String representation of this object.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("FilterMap[");
        sb.append("filterName=");
        sb.append(this.filterName);
        for (int i = 0; i < servletNames.length; i++) {
            sb.append(", servletName=");
            sb.append(servletNames[i]);
        }
        for (int i = 0; i < urlPatterns.length; i++) {
            sb.append(", urlPattern=");
            sb.append(urlPatterns[i]);
        }
        sb.append("]");
        return sb.toString();
    }

}

初始化过滤器

org.apache.catalina.core.StandardContext#filterStart

     /**
     * Configure and initialize the set of filters for this Context.
     * 为此上下文配置和初始化过滤器
     * @return <code>true</code> if all filter initialization completed
     * successfully, or <code>false</code> otherwise.
     */
    public boolean filterStart() {

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Starting filters");
        }
        // Instantiate and record a FilterConfig for each defined filter
        boolean ok = true;
        synchronized (filterConfigs) {
            filterConfigs.clear();
            // 遍历过滤器定义
            for (Entry<String,FilterDef> entry : filterDefs.entrySet()) {
                String name = entry.getKey();
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug(" Starting filter '" + name + "'");
                }
                try {
                    // 实例化应用过滤器配置
                    ApplicationFilterConfig filterConfig =
                            new ApplicationFilterConfig(this, entry.getValue());
                    filterConfigs.put(name, filterConfig);
                } catch (Throwable t) {
                    t = ExceptionUtils.unwrapInvocationTargetException(t);
                    ExceptionUtils.handleThrowable(t);
                    getLogger().error(sm.getString(
                            "standardContext.filterStart", name), t);
                    ok = false;
                }
            }
        }

        return ok;
    }

通过构建ApplicationFilterConfig主要是实例化filter,以及初始化init(只会调用一次),并且该类实现了FilterConfig接口,可以通过ApplicationFilterConfig实例获取过滤器的名称、全限定名以及配置的一些初始化参数信息。

public final class ApplicationFilterConfig implements FilterConfig, Serializable {

    private static final long serialVersionUID = 1L;

    static final StringManager sm =
        StringManager.getManager(Constants.Package);

    private transient Log log = LogFactory.getLog(ApplicationFilterConfig.class); // must not be static

    /**
     * Empty String collection to serve as the basis for empty enumerations.
     */
    private static final List<String> emptyString = Collections.emptyList();

    // ----------------------------------------------------------- Constructors

    // 构造方法
    ApplicationFilterConfig(Context context, FilterDef filterDef)
            throws ClassCastException, ClassNotFoundException, IllegalAccessException,
            InstantiationException, ServletException, InvocationTargetException, NamingException,
            IllegalArgumentException, NoSuchMethodException, SecurityException {

        super();

        this.context = context;
        this.filterDef = filterDef;
        // 过滤器初始化
        if (filterDef.getFilter() == null) {
            getFilter();
        } else {
            this.filter = filterDef.getFilter();
            getInstanceManager().newInstance(filter);
            initFilter();
        }
    }

    // ----------------------------------------------------- Instance Variables

    /**
     * The Context with which we are associated.
     */
    private final transient Context context;

    /**
     * The application Filter we are configured for.
     */
    private transient Filter filter = null;

    /**
     * The <code>FilterDef</code> that defines our associated Filter.
     */
    private final FilterDef filterDef;

    /**
     * the InstanceManager used to create and destroy filter instances.
     */
    private transient InstanceManager instanceManager;

    /**
     * JMX registration name
     */
    private ObjectName oname;

    // --------------------------------------------------- FilterConfig Methods

    /**
     * Return the name of the filter we are configuring.
     */
    @Override
    public String getFilterName() {
        return filterDef.getFilterName();
    }

    /**
     * @return The class of the filter we are configuring.
     */
    public String getFilterClass() {
        return filterDef.getFilterClass();
    }

    /**
     * Return a <code>String</code> containing the value of the named
     * initialization parameter, or <code>null</code> if the parameter
     * does not exist.
     *
     * @param name Name of the requested initialization parameter
     */
    @Override
    public String getInitParameter(String name) {

        Map<String,String> map = filterDef.getParameterMap();
        if (map == null) {
            return null;
        }

        return map.get(name);

    }

    /**
     * Return an <code>Enumeration</code> of the names of the initialization
     * parameters for this Filter.
     */
    @Override
    public Enumeration<String> getInitParameterNames() {
        Map<String,String> map = filterDef.getParameterMap();

        if (map == null) {
            return Collections.enumeration(emptyString);
        }

        return Collections.enumeration(map.keySet());
    }

    /**
     * Return the ServletContext of our associated web application.
     */
    @Override
    public ServletContext getServletContext() {
        return this.context.getServletContext();
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ApplicationFilterConfig[");
        sb.append("name=");
        sb.append(filterDef.getFilterName());
        sb.append(", filterClass=");
        sb.append(filterDef.getFilterClass());
        sb.append("]");
        return sb.toString();
    }

    // --------------------------------------------------------- Public Methods

    public Map<String, String> getFilterInitParameterMap() {
        return Collections.unmodifiableMap(filterDef.getParameterMap());
    }

    // -------------------------------------------------------- Package Methods

    Filter getFilter() throws ClassCastException, ClassNotFoundException, IllegalAccessException,
            InstantiationException, ServletException, InvocationTargetException, NamingException,
            IllegalArgumentException, NoSuchMethodException, SecurityException {

        // Return the existing filter instance, if any
        if (this.filter != null)
            return this.filter;

        // 根据过滤器的全限定名通过反射实例化
        String filterClass = filterDef.getFilterClass();
        this.filter = (Filter) getInstanceManager().newInstance(filterClass);

        // 初始化过滤器
        initFilter();

        return this.filter;

    }

    // 调用过滤器的init()方法,我们自定义的过滤器该init方法也由我们自定义
    private void initFilter() throws ServletException {
        if (context instanceof StandardContext &&
                context.getSwallowOutput()) {
            try {
                SystemLogHandler.startCapture();
                filter.init(this);
            } finally {
                String capturedlog = SystemLogHandler.stopCapture();
                if (capturedlog != null && capturedlog.length() > 0) {
                    getServletContext().log(capturedlog);
                }
            }
        } else {
            filter.init(this);
        }

        // Expose filter via JMX
        registerJMX();
    }

    /**
     * Return the filter definition we are configured for.
     */
    FilterDef getFilterDef() {
        return this.filterDef;
    }

    private InstanceManager getInstanceManager() {
        if (instanceManager == null) {
            if (context instanceof StandardContext) {
                instanceManager = ((StandardContext)context).getInstanceManager();
            } else {
                instanceManager = new DefaultInstanceManager(null,
                        new HashMap<String, Map<String, String>>(),
                        context,
                        getClass().getClassLoader());
            }
        }
        return instanceManager;
    }
}

创建过滤器链 ApplicationFilterChain

web容器会为request创建过滤器链,并且经过过滤器链中每个过滤器的处理后才会继续执行到servlet

org.apache.catalina.core.ApplicationFilterFactory#createFilterChain

 public static ApplicationFilterChain createFilterChain(ServletRequest request,
            Wrapper wrapper, Servlet servlet) {

        // If there is no servlet to execute, return null
        if (servlet == null)
            return null;

        // 创建并初始化一个拦截器对象
        ApplicationFilterChain filterChain = null;
        if (request instanceof Request) {
            Request req = (Request) request;
            if (Globals.IS_SECURITY_ENABLED) {
                // Security: Do not recycle
                filterChain = new ApplicationFilterChain();
            } else {
                // 从请求中取,复用过滤器链
                filterChain = (ApplicationFilterChain) req.getFilterChain();
                if (filterChain == null) {
                    filterChain = new ApplicationFilterChain();
                    req.setFilterChain(filterChain);
                }
            }
        } else {
            // Request dispatcher in use
            filterChain = new ApplicationFilterChain();
        }

        // 设置servlet
        filterChain.setServlet(servlet);
        // 是否支持异步
        filterChain.setServletSupportsAsync(wrapper.isAsyncSupported());

        // Acquire the filter mappings for this Context
        // 从上下文中获取过滤器映射信息
        StandardContext context = (StandardContext) wrapper.getParent();
        FilterMap filterMaps[] = context.findFilterMaps();

        // If there are no filter mappings, we are done
        // 未设置过滤器直接返回
        if ((filterMaps == null) || (filterMaps.length == 0))
            return filterChain;

        // Acquire the information we will need to match filter mappings
        // 从request获取dispatcher以匹配 (REQUEST)
        DispatcherType dispatcher =
                (DispatcherType) request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);

        // 获取请求路径
        String requestPath = null;
        Object attribute = request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);
        if (attribute != null){
            requestPath = attribute.toString();
        }

        // 获取servlet名称
        String servletName = wrapper.getName();

        // Add the relevant path-mapped filters to this filter chain
        // 过滤器链中添加路径匹配的过滤器
        for (int i = 0; i < filterMaps.length; i++) {
            // 先匹配dispatcher类型,默认是REQUEST
            if (!matchDispatcher(filterMaps[i] ,dispatcher)) {
                continue;
            }
            // 再匹配请求路径
            if (!matchFiltersURL(filterMaps[i], requestPath))
                continue;
            ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)
                context.findFilterConfig(filterMaps[i].getFilterName());
            if (filterConfig == null) {
                // FIXME - log configuration problem
                continue;
            }
            // 添加到过滤器链中
            filterChain.addFilter(filterConfig);
        }

        // Add filters that match on servlet name second
        // 在根据servlet名称匹配过滤器添加到过滤器链中
        for (int i = 0; i < filterMaps.length; i++) {
            if (!matchDispatcher(filterMaps[i] ,dispatcher)) {
                continue;
            }
            if (!matchFiltersServlet(filterMaps[i], servletName))
                continue;
            ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)
                context.findFilterConfig(filterMaps[i].getFilterName());
            if (filterConfig == null) {
                // FIXME - log configuration problem
                continue;
            }
            filterChain.addFilter(filterConfig);
        }

        // Return the completed filter chain
        // 返回完整的过滤器链对象
        return filterChain;
    }

执行过滤器链

ApplicationFilterChain执行过滤器方法

 public final class ApplicationFilterChain implements FilterChain {

    // Used to enforce requirements of SRV.8.2 / SRV.14.2.5.1
    private static final ThreadLocal<ServletRequest> lastServicedRequest;
    private static final ThreadLocal<ServletResponse> lastServicedResponse;

    static {
        if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
            lastServicedRequest = new ThreadLocal<>();
            lastServicedResponse = new ThreadLocal<>();
        } else {
            lastServicedRequest = null;
            lastServicedResponse = null;
        }
    }

    // -------------------------------------------------------------- Constants

    public static final int INCREMENT = 10;

    // ----------------------------------------------------- Instance Variables

    /**
     * Filters.
     */
    private ApplicationFilterConfig[] filters = new ApplicationFilterConfig[0];

    /**
     * The int which is used to maintain the current position
     * in the filter chain.
     */
    private int pos = 0;

    /**
     * The int which gives the current number of filters in the chain.
     */
    private int n = 0;

    /**
     * The servlet instance to be executed by this chain.
     */
    private Servlet servlet = null;

    /**
     * Does the associated servlet instance support async processing?
     */
    private boolean servletSupportsAsync = false;

    /**
     * The string manager for our package.
     */
    private static final StringManager sm =
      StringManager.getManager(Constants.Package);

    /**
     * Static class array used when the SecurityManager is turned on and
     * <code>doFilter</code> is invoked.
     */
    private static final Class<?>[] classType = new Class[]{
        ServletRequest.class, ServletResponse.class, FilterChain.class};

    /**
     * Static class array used when the SecurityManager is turned on and
     * <code>service</code> is invoked.
     */
    private static final Class<?>[] classTypeUsedInService = new Class[]{
        ServletRequest.class, ServletResponse.class};

    // ---------------------------------------------------- FilterChain Methods

    /**
     * Invoke the next filter in this chain, passing the specified request
     * and response.  If there are no more filters in this chain, invoke
     * the <code>service()</code> method of the servlet itself.
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet exception occurs
     */
    // 执行过滤器
    @Override
    public void doFilter(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {

        if( Globals.IS_SECURITY_ENABLED ) {
            final ServletRequest req = request;
            final ServletResponse res = response;
            try {
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedExceptionAction<Void>() {
                        @Override
                        public Void run()
                            throws ServletException, IOException {
                            internalDoFilter(req,res);
                            return null;
                        }
                    }
                );
            } catch( PrivilegedActionException pe) {
                Exception e = pe.getException();
                if (e instanceof ServletException)
                    throw (ServletException) e;
                else if (e instanceof IOException)
                    throw (IOException) e;
                else if (e instanceof RuntimeException)
                    throw (RuntimeException) e;
                else
                    throw new ServletException(e.getMessage(), e);
            }
        } else {
            internalDoFilter(request,response);
        }
    }

    private void internalDoFilter(ServletRequest request,
                                  ServletResponse response)
        throws IOException, ServletException {

        // Call the next filter if there is one
        // pos表示当前正在使用的过滤器在过滤器数组filters中的序号,每执行一次加1
        // n表示过滤器数目
        if (pos < n) {
            ApplicationFilterConfig filterConfig = filters[pos++];
            try {
                Filter filter = filterConfig.getFilter();

                if (request.isAsyncSupported() && "false".equalsIgnoreCase(
                        filterConfig.getFilterDef().getAsyncSupported())) {
                    request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
                }
                if( Globals.IS_SECURITY_ENABLED ) {
                    final ServletRequest req = request;
                    final ServletResponse res = response;
                    Principal principal =
                        ((HttpServletRequest) req).getUserPrincipal();

                    Object[] args = new Object[]{req, res, this};
                    SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);
                } else {
                    // 调用doFilter执行过滤器的方法
                    filter.doFilter(request, response, this);
                }
            } catch (IOException | ServletException | RuntimeException e) {
                throw e;
            } catch (Throwable e) {
                e = ExceptionUtils.unwrapInvocationTargetException(e);
                ExceptionUtils.handleThrowable(e);
                throw new ServletException(sm.getString("filterChain.filter"), e);
            }
            return;
        }

        // We fell off the end of the chain -- call the servlet instance
        // 当所有过滤器执行完后,调用servlet的service()方法
        try {
            if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
                lastServicedRequest.set(request);
                lastServicedResponse.set(response);
            }

            if (request.isAsyncSupported() && !servletSupportsAsync) {
                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
                        Boolean.FALSE);
            }
            // Use potentially wrapped request from this point
            if ((request instanceof HttpServletRequest) &&
                    (response instanceof HttpServletResponse) &&
                    Globals.IS_SECURITY_ENABLED ) {
                final ServletRequest req = request;
                final ServletResponse res = response;
                Principal principal =
                    ((HttpServletRequest) req).getUserPrincipal();
                Object[] args = new Object[]{req, res};
                SecurityUtil.doAsPrivilege("service",
                                           servlet,
                                           classTypeUsedInService,
                                           args,
                                           principal);
            } else {
                servlet.service(request, response);
            }
        } catch (IOException | ServletException | RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            throw new ServletException(sm.getString("filterChain.servlet"), e);
        } finally {
            if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
                lastServicedRequest.set(null);
                lastServicedResponse.set(null);
            }
        }
    }

    /**
     * The last request passed to a servlet for servicing from the current
     * thread.
     *
     * @return The last request to be serviced.
     */
    public static ServletRequest getLastServicedRequest() {
        return lastServicedRequest.get();
    }

    /**
     * The last response passed to a servlet for servicing from the current
     * thread.
     *
     * @return The last response to be serviced.
     */
    public static ServletResponse getLastServicedResponse() {
        return lastServicedResponse.get();
    }

    // -------------------------------------------------------- Package Methods

    /**
     * Add a filter to the set of filters that will be executed in this chain.
     *
     * @param filterConfig The FilterConfig for the servlet to be executed
     */
    // 添加过滤器配置信息到过滤器链
    void addFilter(ApplicationFilterConfig filterConfig) {

        // Prevent the same filter being added multiple times
        for(ApplicationFilterConfig filter:filters)
            if(filter==filterConfig)
                return;

        if (n == filters.length) {
            ApplicationFilterConfig[] newFilters =
                new ApplicationFilterConfig[n + INCREMENT];
            System.arraycopy(filters, 0, newFilters, 0, n);
            filters = newFilters;
        }
        filters[n++] = filterConfig;

    }

    /**
     * Release references to the filters and wrapper executed by this chain.
     */
    void release() {
        for (int i = 0; i < n; i++) {
            filters[i] = null;
        }
        n = 0;
        pos = 0;
        servlet = null;
        servletSupportsAsync = false;
    }

    /**
     * Prepare for reuse of the filters and wrapper executed by this chain.
     */
    void reuse() {
        pos = 0;
    }

    /**
     * Set the servlet that will be executed at the end of this chain.
     *
     * @param servlet The Wrapper for the servlet to be executed
     */
    void setServlet(Servlet servlet) {
        this.servlet = servlet;
    }

    void setServletSupportsAsync(boolean servletSupportsAsync) {
        this.servletSupportsAsync = servletSupportsAsync;
    }

    /**
     * Identifies the Filters, if any, in this FilterChain that do not support
     * async.
     *
     * @param result The Set to which the fully qualified class names of each
     *               Filter in this FilterChain that does not support async will
     *               be added
     */
    public void findNonAsyncFilters(Set<String> result) {
        for (int i = 0; i < n ; i++) {
            ApplicationFilterConfig filter = filters[i];
            if ("false".equalsIgnoreCase(filter.getFilterDef().getAsyncSupported())) {
                result.add(filter.getFilterClass());
            }
        }
    }
}

到此这篇关于JavaWeb中过滤器Filter的用法详解的文章就介绍到这了,更多相关JavaWeb过滤器Filter内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java Filter过滤器的使用教程

    目录 一.过滤器的使用以及实现原理 当前的oa项目还存在什么缺陷 Filter作用与执行原理 过滤器怎么写 过滤器的调用顺序 Filter的生命周期 二.责任链设计模式改造oa项目 一.过滤器的使用以及实现原理 当前的oa项目还存在什么缺陷 ①对于DeptServlet.EmpServlet.OrderServlet,每一个Servlet都是处理自己相关的业务:在这些Servlet执行之前都是需要判断用户是否登录了.如果用户登录了,可以继续操作,如果没有登录,需要用户登录. ②这段判断用户是否登

  • 详解JavaWeb过滤器 Filter问题解决

    目录 基本概念 1.过滤器概述 2.使用过滤器解决中文编码异常问题 3.使用过滤器实现用户登录权限拦截 基本概念 1. Filter 过滤器它是 JavaWeb 的三大组件之一. 三大组件分别是: Servlet 程序. Listener 监听器. Filter 过滤器2. Filter 过滤器它是 JavaEE 的规范. 也就是接口3. Filter 过滤器它的作用是: 拦截请求, 过滤响应        过滤器的三要素: ①拦截 过滤器之所以能够对请求进行预处理,关键是对请求进行拦截,把请求

  • Java中使用Filter过滤器的方法

    Filter过滤器 着重记录下 public void doFilter(){} 方法参数: (1) ServletRequest servletRequest 请求reqeust: (2)ServletResponse servletResponse 响应response: (3)FilterChain filterChain 参数 filterChain,有一个doFilter() 方法,调用这个方法,可以使程序继续往下走,执行后续代码,如果有多个过滤器,它会继续执行下一个过滤器逻辑(开发中

  • Java过滤器Filter详解

    目录 Filter学习 Filter功能 Filter的工作原理 多个Filter的实现 Filter的执行逻辑 总结 Filter学习 Filter功能 拦截jsp.静态图片文件.静态html资源文件 实现URL级别的权限访问控制 过滤敏感词汇 压缩相应信息 Filter的工作原理 看源码可以看出来,Filter接口中有3个方法:init.doFilter.destory init方法,初始化Filter,Filter在服务器启动阶段被实例化.并且调用init方法,init方法只执行一次,因为

  • 详解JavaWeb中的过滤器Filter

    一.什么是过滤器 1.Filter过滤器的作用:拦截请求 2.拦截请求常见场景: (1)权限检查 (2)日记操作 (3)事务管理 1.1 使用步骤 Filter 过滤器的使用步骤: 1.编写一个类去实现Filter 接口 2.实现过滤方法doFilter() 3.到web.xml 中去配置Filter 的拦截路径 二.初体验 web工程下新建一个admin目录,作为需要权限才能访问的目录,其中有两个文件 2.1 mynav.html <!DOCTYPE html> <html lang=

  • 深入了解Java中的过滤器Filter和监听器Listener

    目录 Filter:过滤器 概念 快速入门 过滤器细节 Listener:监听器 Filter:过滤器 概念 生活中的过滤器:净水器,空气净化器,土匪. web中的过滤器:当访问服务器的资源时,过滤器可以将请求拦截下来,完成一些特殊的功能. 过滤器的作用: 一般用于完成通用的操作.如:登录验证.统一编码处理.敏感字符过滤... 快速入门 步骤 1.定义一个类,实现接口Filter 2.复写方法 3.配置拦截路径 web.xml 注解 代码 @WebFilter("/*")//访问所有资

  • JavaWeb中过滤器Filter的用法详解

    目录 过滤器Filter 处理顺序 使用场景 自定义过滤器 源码分析 FilterDef FilterMap 初始化过滤器 创建过滤器链 ApplicationFilterChain 执行过滤器链 过滤器Filter 过滤器通常对一些web资源进行拦截,做完一些处理器再交给下一个过滤器处理,直到所有的过滤器处理器,再调用servlet实例的service方法进行处理.过滤器可以对request进行处理也可以对response进行处理. 处理顺序 如果过滤器链顺序如上图所示,那么对request请

  • Java Web开发中过滤器和监听器使用详解

    目录 1 Filter 1.1 Filter简介 1.2 Filter的快速入门 1.2.1 创建Filter类 1.2.2 访问index.jsp 1.3 Filter的拦截路径的配置 1.4 过滤器链 1.4.1 过滤器链简介 1.4.2 过滤器链的例子 2 Listener 2.1 概念 2.2 监听器的使用 1 Filter 1.1 Filter简介 Filter表示过滤器,是JavaWeb三大组件(Servlet.Filter.Listener)之一. 过滤器可以把资源的请求拦截下来,

  • SpringBoot 过滤器 Filter使用实例详解

    目录 简介 用法 功能 实现 简介 过滤器是AOP(面向切面编程)思想的具体实现.可以过滤浏览器发出的请求,并且决定放行请求还是中断请求. 在浏览器对服务器发起请求或者服务器对浏览器响应,都会经过过滤器. 基于过滤器的机制,我们可以在过滤器中对请求和响应做一些处理,可以在过滤器中决定是否放行,例如:校验请求中有没有敏感字符串,校验有没有Session,实现URL级别的权限控制.压缩响应信息.编码格式等. 用法 在spring的应用中我们存在两种过滤的用法,一种是拦截器.另外一种当然是过滤器.我们

  • django model 条件过滤 queryset.filter(**condtions)用法详解

    1.下述代码查询model对应数据库中日期等于2018-05-22的数据: queryset = model.objects.all() condtions: {'date': '2018-05-22'} query_res = queryset.filter(**condtions) 2.下述代码查询model对应数据库中日期小于2018-05-22的数据: queryset = model.objects.all() condtions: {'date__lt': '2018-05-22'}

  • Oracle中游标Cursor基本用法详解

    查询 SELECT语句用于从数据库中查询数据,当在PL/SQL中使用SELECT语句时,要与INTO子句一起使用,查询的 返回值被赋予INTO子句中的变量,变量的声明是在DELCARE中.SELECT INTO语法如下: SELECT [DISTICT|ALL]{*|column[,column,...]} INTO (variable[,variable,...] |record) FROM {table|(sub-query)}[alias] WHERE............ PL/SQL

  • JSP中EL表达式的用法详解(必看篇)

    EL 全名为Expression Language EL 语法很简单,它最大的特点就是使用上很方便.接下来介绍EL主要的语法结构: ${sessionScope.user.sex} 所有EL都是以${为起始.以}为结尾的.上述EL范例的意思是:从Session的范围中,取得 用户的性别.假若依照之前JSP Scriptlet的写法如下: User user =(User)session.getAttribute("user"); String sex =user.getSex( );

  • oracle数据库中sql%notfound的用法详解

    SQL%NOTFOUND 是一个布尔值.与最近的sql语句(update,insert,delete,select)发生交互,当最近的一条sql语句没有涉及任何行的时候,则返回true.否则返回false.这样的语句在实际应用中,是非常有用的.例如要update一行数据时,如果没有找到,就可以作相应操作.如: begin update table_name set salary = 10000 where emp_id = 10; if sql%notfound then insert into

  • JavaScript中的splice方法用法详解

    JavaScript中的splice主要用来对js中的数组进行操作,包括删除,添加,替换等. 注意:这种方法会改变原始数组!. 1.删除-用于删除元素,两个参数,第一个参数(要删除第一项的位置),第二个参数(要删除的项数) 2.插入-向数组指定位置插入任意项元素.三个参数,第一个参数(插入位置),第二个参数(0),第三个参数(插入的项) 3.替换-向数组指定位置插入任意项元素,同时删除任意数量的项,三个参数.第一个参数(起始位置),第二个参数(删除的项数),第三个参数(插入任意数量的项) 示例:

  • 对pandas中apply函数的用法详解

    最近在使用apply函数,总结一下用法. apply函数可以对DataFrame对象进行操作,既可以作用于一行或者一列的元素,也可以作用于单个元素. 例:列元素 行元素 列 行 以上这篇对pandas中apply函数的用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们. 您可能感兴趣的文章: 浅谈Pandas中map, applymap and apply的区别

  • Python3网络爬虫中的requests高级用法详解

    本节我们再来了解下 Requests 的一些高级用法,如文件上传,代理设置,Cookies 设置等等. 1. 文件上传 我们知道 Reqeuests 可以模拟提交一些数据,假如有的网站需要我们上传文件,我们同样可以利用它来上传,实现非常简单,实例如下: import requests files = {'file': open('favicon.ico', 'rb')} r = requests.post('http://httpbin.org/post', files=files) print

随机推荐