Spring-MVC如何使用拦截器,官方文档只给出了非注解风格的例子。那么基于注解风格如何使用拦截器呢?
基于注解基本上有2个可使用的定义类,分别是DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
<
bean
class
="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"
/>
<
bean
class
="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
/>
1、DefaultAnnotationHandlerMapping
DefaultAnnotationHandlerMapping本身支持自定义拦截器,只需按如下进行配置:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
1
<
bean
class
="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"
>
2
<
property
name
="interceptors"
>
3
<
list
>
4
<
bean
class
="packageName.XXXInterceptor"
/>
5
</
list
>
6
</
property
>
7
</
bean
>
Interceptor的定义为:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
1
public
class
XXXInterceptor
extends
HandlerInterceptorAdapter {
2
@Override
3
public
boolean
preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {
4
5
String className
=
handler.getClass().getName();
//
package
Name
.ClassName
6
if
(Error) {
7
return
false
;
8
}
9
return
true
;
10
}
11
}
如果需要运行在GAE上面,对于Spring2.5.x会有问题,需要使用Srping3就没有问题了。