zoukankan      html  css  js  c++  java
  • 自定义注解拦截(比如自定义注解,登陆拦截)

    1.注解类

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Mytest {
    
        String value();
    }

    2.拦截类

    @Configuration
    public class Login extends WebMvcConfigurerAdapter {
    
        @Bean
        public SessionInterceptor getSessionInterceptor() {
            System.out.println("bean加载了!");
            return new SessionInterceptor();
        }
        
        
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            InterceptorRegistration addInterceptor = registry.addInterceptor(getSessionInterceptor());
            addInterceptor.addPathPatterns("/**");
        }
    
    
        private class SessionInterceptor extends HandlerInterceptorAdapter {
    
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
                System.out.println("==================>");
                if(!(handler instanceof HandlerMethod)) {
                    System.out.println(0);
                    return true;
                }
                HandlerMethod handlerMethod = (HandlerMethod)handler;            
                Mytest methodAnnotation = handlerMethod.getMethodAnnotation(Mytest.class);            
                if(methodAnnotation == null){
                    System.out.println(1);
                    return true; 
                }
                String str = methodAnnotation.value(); 
                System.out.println("拦截value:"+str);
                System.out.println(2);
                return true;
            }
    
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                System.out.println("<=======*=======*========*======华丽的请求分割线======*=========*========*=======>");
            }
        }
        
    }

    3.使用类

    @RestController
    public class MyController {
    
        @Mytest(value = "true")
        @RequestMapping(value = "/test1/{id}", method = RequestMethod.GET)
        public  String getById(@PathVariable("id") Long id) {
             System.out.println("请求成功");
            return "1";
        }
        
        @RequestMapping(value = "/test2/{id2}", method = RequestMethod.GET)
        public  String getById2(@PathVariable("id2") Long id2) {
            System.out.println("请求成功");
            return "2";
        }
        
    }

    通过使用@Mytest注解,完成登陆拦截校验.

  • 相关阅读:
    MFC中的菜单(Menu)
    MFC中获取系统无任何操作的时间
    MFC中使用快捷键Accelerator
    Git的安装和使用
    给pdf添加目录
    练习题2
    练习题1
    主键和外键
    数据库知识点
    多表查询
  • 原文地址:https://www.cnblogs.com/wonder2636/p/9639108.html
Copyright © 2011-2022 走看看