spring中有没有注解拦截器,只拦截注解

2025-05-14 09:37:47
推荐回答(1个)
回答1:

spring拦截器只拦截path, 或者说方法名称, 它并不知道注解, 但是比servletfilter丰富的事是,这里可以比较方便的做反射操作.

比如可以继承HandlerInterceptorAdapter类 或者实现HandlerInterceptor接口,放过没有指定注解的请求即可(前者要求只要override preHandle, 后者要实现postHandle,preHandle和afterCompletion)
举个Adapter的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
* 2016/08/30
* @author sleest
*/
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
HandlerMethod hm = (HandlerMethod) handler;
Method method = hm.getMethod();

// 这里就可以处理某些注解下要做的事情或者放过

// Is Annotation On Method's Class
method.getDeclaringClass().isAnnotationPresent(RequestMapping.class);
// Is Annotation On Method
method.isAnnotationPresent(RequestMapping.class);

// Get Method Annotation, Perhaps null
RequestMapping requestMappingAt = method.getAnnotation(RequestMapping.class);
// Get Annnotation Attribute
requestMappingAt.name();
requestMappingAt.method();

// ...

return true;
}
}