1.自定义注解配合拦截器
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
@RestController
public class MyController {
@GetMapping("/myEndpoint")
@MyAnnotation
public String myEndpoint() {
return "Hello, World!";
}
}
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
MyAnnotation myAnnotation = handlerMethod.getMethod().getAnnotation(MyAnnotation.class);
if (myAnnotation != null) {
System.out.println("Intercepted request with MyAnnotation");
}
}
return true;
}
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
private final MyInterceptor myInterceptor;
public InterceptorConfig(MyInterceptor myInterceptor) {
this.myInterceptor = myInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
2. 自定义注解与过滤器(需要前端约定好一个属性,不推荐)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
@RestController
public class MyController {
@GetMapping("/myEndpoint")
@MyAnnotation
public String myEndpoint() {
return "Hello, World!";
}
}
@Component
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HandlerMethod handlerMethod = (HandlerMethod) httpRequest.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
if (handlerMethod != null) {
MyAnnotation myAnnotation = handlerMethod.getMethod().getAnnotation(MyAnnotation.class);
if (myAnnotation != null) {
System.out.println("Filtered request with MyAnnotation");
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
@Configuration
public class FilterConfig {
private final MyFilter myFilter;
public FilterConfig(MyFilter myFilter) {
this.myFilter = myFilter;
}
@Bean
public FilterRegistrationBean<MyFilter> myFilterRegistration() {
FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(myFilter);
registration.addUrlPatterns("/*");
return registration;
}
}
3.AOP …