zoukankan      html  css  js  c++  java
  • SpringBoot_使用拦截器

    首先我们定义一个拦截器:

    @Component
    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("preHandle method is running!");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle method is running!");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("afterCompletion method is running!");
        }
    }

    然后定义配置类,注册拦截器:

    @Configuration
    public class MvcConfiguration implements WebMvcConfigurer {
    
        @Autowired
        private HandlerInterceptor myInterceptor;
    
        /**
         * 重写接口中的addInterceptors方法,添加自定义拦截器
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor).addPathPatterns("/**");
        }
    }

    接下来运行并查看日志:

    preHandle method is running!
    postHandle method is running!
    afterCompletion method is running!
    学习中,博客都是自己学习用的笔记,持续更新改正。。。
  • 相关阅读:
    浅谈c#中使用lock的是与非
    C#设计模式学习笔记单例模式
    ArrayList c.toArray might (incorrectly) not return Object[] (see 6260652)
    java.lang.Object 之 clone() 使用

    把以前的补齐 张
    String的方法 张
    随便写写 张
    集合框架 张
    java 张
  • 原文地址:https://www.cnblogs.com/Tunan-Ki/p/11774152.html
Copyright © 2011-2022 走看看