• 自定义注解拦截(比如自定义注解,登陆拦截)


    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注解,完成登陆拦截校验.

  • 相关阅读:
    在WPF中添加Windows Form控件
    LIST对象排序问题
    C# TreeView树节点上下移动
    C# listbox的上下移动,拖动排序,两个listbox相互拖动
    Nmap 扫描并生成HTML报告
    Windows 10 系统精简方案参考
    Windows10 子系统 Ubuntu安装
    VS2012 RC页面检查器
    新增功能.NET 框架 4.5 RC
    PowerPoint Storyboarding:Visual Studio 2012 RC带给开发者的秘密杀器
  • 原文地址:https://www.cnblogs.com/wonder2636/p/9639108.html
Copyright © 2020-2023  润新知