spring拦截器栈_spring mvc中的几类拦截器对比

本文详细对比了Spring MVC中的Filter和HandlerInterceptor。Filter属于Servlet规范,适用于所有支持Servlet的容器,其doFilter方法无返回值,异常无法被Spring处理。而HandlerInterceptor是Spring MVC特有,preHandle返回true则继续执行,异常可由ExceptionHandler捕获。通常,Filter常用于设置编码、跨域等全局操作,HandlerInterceptor更适合做权限验证和耗时记录。
摘要由CSDN通过智能技术生成

本文主要对比一下spring mvc中可以使用的几类拦截器。

分类

主要分Filter及interceptor。

Filter

是servlet规范中的Filter,spring中有一个基本的实现叫做org/springframework/web/filter/GenericFilterBean.java

public abstract class GenericFilterBean implements

Filter, BeanNameAware, EnvironmentAware, ServletContextAware, InitializingBean, DisposableBean {

@Override

public final void setBeanName(String beanName) {

this.beanName = beanName;

}

@Override

public void setEnvironment(Environment environment) {

this.environment = environment;

}

@Override

public final void setServletContext(ServletContext servletContext) {

this.servletContext = servletContext;

}

@Override

public void afterPropertiesSet() throws ServletException {

initFilterBean();

}

}

//......

这个类主要实现了spring生命周期的几个接口,方便作为bean纳入IOC容器管理。

如果是在web.xml定义的话,支持将参数映射到bean中的属性

OncePerRequestFilter

在spring中,filter都默认继承OncePerRequestFilter,他确保一次请求只通过一次filter,而不重复执行。

此方式是为了兼容不同的web container,特意而为之(JSR168),也就是说并不是所有的container都像我们期望的只过滤一次,servlet版本不同.为了兼容各种不同的运行环境和版本,默认filter继承OncePerRequestFilter是一个比较稳妥的选择。

public abstract class OncePerRequestFilter extends GenericFilterBean {

public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED";

protected String getAlreadyFilteredAttributeName() {

String name = getFilterName();

if (name == null) {

name = getClass().getName();

}

return name + ALREADY_FILTERED_SUFFIX;

}

//......

}

通过filtername+ALREADY_FILTERED_SUFFIX来标识filter是否已经执行过。

HandlerInterceptor

org/springframework/spring-webmvc/4.3.9.RELEASE/spring-webmvc-4.3.9.RELEASE-sources.jar!/org/springframework/web/servlet/HandlerInterceptor.java

基于execution chains来执行

public interface HandlerInterceptor {

/**

* Intercept the execution of a handler. Called after HandlerMapping determined

* an appropriate handler object, but before HandlerAdapter invokes the handler.

*

DispatcherServlet processes a handler in an execution chain, consisting

* of any number of interceptors, with the handler itself at the end.

* With this method, each interceptor can decide to abort the execution chain,

* typically sending a HTTP error or writing a custom response.

*

Note: special considerations apply for asynchronous

* request processing. For more details see

* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.

* @param request current HTTP request

* @param response current HTTP response

* @param handler chosen handler to execute, for type and/or instance evaluation

* @return {@code true} if the execution chain should proceed with the

* next interceptor or the handler itself. Else, DispatcherServlet assumes

* that this interceptor has already dealt with the response itself.

* @throws Exception in case of errors

*/

boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

throws Exception;

/**

* Intercept the execution of a handler. Called after HandlerAdapter actually

* invoked the handler, but before the DispatcherServlet renders the view.

* Can expose additional model objects to the view via the given ModelAndView.

*

DispatcherServlet processes a handler in an execution chain, consisting

* of any number of interceptors, with the handler itself at the end.

* With this method, each interceptor can post-process an execution,

* getting applied in inverse order of the execution chain.

*

Note: special considerations apply for asynchronous

* request processing. For more details see

* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.

* @param request current HTTP request

* @param response current HTTP response

* @param handler handler (or {@link HandlerMethod}) that started asynchronous

* execution, for type and/or instance examination

* @param modelAndView the {@code ModelAndView} that the handler returned

* (can also be {@code null})

* @throws Exception in case of errors

*/

void postHandle(

HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)

throws Exception;

/**

* Callback after completion of request processing, that is, after rendering

* the view. Will be called on any outcome of handler execution, thus allows

* for proper resource cleanup.

*

Note: Will only be called if this interceptor's {@code preHandle}

* method has successfully completed and returned {@code true}!

*

As with the {@code postHandle} method, the method will be invoked on each

* interceptor in the chain in reverse order, so the first interceptor will be

* the last to be invoked.

*

Note: special considerations apply for asynchronous

* request processing. For more details see

* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.

* @param request current HTTP request

* @param response current HTTP response

* @param handler handler (or {@link HandlerMethod}) that started asynchronous

* execution, for type and/or instance examination

* @param ex exception thrown on handler execution, if any

* @throws Exception in case of errors

*/

void afterCompletion(

HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

throws Exception;

}

主要定义了三个方法,preHandle,postHandle,afterCompletion

preHandle

这个里头返回false,则会停止继续往下执行

postHandle

后处理回调方法,实现处理器的后处理,但在渲染视图之前执行,可以在这里额外往视图添加额外的变量等(在preHandle成功执行完,返回true的情况下执行)

afterCompletion

在preHandle成功执行完,返回true的情况下执行.整个请求处理完毕回调方法,即在视图渲染完毕时回调

对比

类型

范围

执行链处理

异常

经典实用

filter

filter是servlet是定义,在支持servlet的容器中都可以支持

doFilter方法没有返回值,每个filter里头去控制是否往下执行,不想往下执行的话,可以自己设定response body和status然后提前返回

异常无法被spring的ExceptionHandler捕获,直接500

CharacterEncodingFilter

CorsFilter

CsrfFilter

MetricsFilter

MultipartFilter

OpenEntityManagerInViewFilter

WebRequestTraceFilter

HandlerInterceptor

在spring mvc中支持

preHandle方法返回布尔值,当布尔值为true的时候继续往下一个interceptor执行,返回false则立即返回,可以自己设定response body和status,也可以抛异常,spring会统一拦截处理

异常可以被ExceptionHandler捕获

MvcEndpointSecurityInterceptor

UserRoleAuthorizationInterceptor

记录耗时等用filter的比较多,比较全面;执行鉴权相关的用HandlerInterceptor的比较多,当然用filter也可以。

doc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值