sel*_*rce 8 java spring spring-mvc
我使用以下代码注册了我的拦截器
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
...
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( myInterceptor() );
}
...
}
Run Code Online (Sandbox Code Playgroud)
这里是拦截器定义
public class MyInterceptorimplements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Check to see if the handling controller is annotated
for (Annotation annotation : Arrays.asList(handler.getClass().getDeclaredAnnotations())){
if (annotation instanceof MyAnnotation){
... do something
Run Code Online (Sandbox Code Playgroud)
但是,handler.getClass().getDeclaredAnnotations()不会返回截获的Controller的类级别注释.
我只能得到方法级注释,这不是我想要的.
相同的拦截器适用于xml配置(使用Spring 3):
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="myInterceptor"/>
</list>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
有没有办法在Spring 4中提供类级信息?
根据 In-Spring-mvc拦截器,我如何访问处理程序控制器方法? "HandlerInterceptors将仅使用上述配置为您提供对HandlerMethod的访问权限".但是获取类级别信息的替代配置是什么?
小智 8
您可以使用处理程序方法访问拦截器中的spring控制器类级别注释.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre-handle");
HandlerMethod hm;
try {
hm = (HandlerMethod) handler;
} catch (ClassCastException e) {
return super.preHandle(request, response, handler);
}
Method method = hm.getMethod();
HandlerMethod hm = (HandlerMethod) handler;
Method method = hm.getMethod();
// Sometimes Controller.class wont work and you have to use RestController.class just depends on what you use.
if (method.getDeclaringClass().isAnnotationPresent(Controller.class)) {
if (method.isAnnotationPresent(ApplicationAudit.class)) {
System.out.println(method.getAnnotation(ApplicationAudit.class).value());
request.setAttribute("STARTTIME", System.currentTimemillis());
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7342 次 |
最近记录: |