一.实现注解式拦截器
1.首先实现自定义注解,该注解只能作用在方法
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAn {}
2.编写自定义拦截器
参数说明 :
Object handler: 调用的目标方法。
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(handler instanceof HandlerMethod){ HandlerMethod han = (HandlerMethod) handler; MyAn methodAnnotation = han.getMethodAnnotation(MyAn.class); Method method = han.getMethod(); if(methodAnnotation!=null){ System.out.println(method.getName()); return true; } } response.setContentType("text/html;charset=utf-8"); response.getWriter().write("没有权限"); return false; } }
3.将该拦截器添加到拦截器配置中
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); } }
二.实现注解将值注入到参数
1.自定义注解,作用于参数中
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface MyParam {}
2.编写自定义参数解析器
@Component public class MyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override //当扫描到注解为MyParam时执行 public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.hasParameterAnnotation(MyParam.class); } @Override //示例:将请求地址注入到该参数 public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { HttpServletRequest nativeRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class); String requestURI = nativeRequest.getRequestURI(); Class<?> parameterType = methodParameter.getParameterType(); if(parameterType.isAssignableFrom(String.class)){ return requestURI; } return null; } }
3.添加到参数解析器
@Configuration public class MyAddArgumentResolvers extends WebMvcConfigurationSupport { @Override protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(new MyHandlerMethodArgumentResolver()); } }