• 通过注解方式实现拦截器功能interceptor,通过注解实现对参数的值注入


    一.实现注解式拦截器

    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());
        }
    }
  • 相关阅读:
    Atitit 图像金字塔原理与概率 attilax的理解总结qb23
    Atiti  attilax主要成果与解决方案与案例rsm版 v4
    Atitit 常用比较复杂的图像滤镜 attilax大总结
    Atitit. Api 设计 原则 ---归一化
    Atitit 面向对象弊端与问题 坏处 缺点
    Atitit  记录方法调用参数上下文arguments
    Atitit 作用域的理解attilax总结
    Atitit usrQBM1603短信验证码规范
    atitit 短信验证码的源码实现  .docx
    Atitit 图片 验证码生成attilax总结
  • 原文地址:https://www.cnblogs.com/kelelipeng/p/16018383.html
Copyright © 2020-2023  润新知