zoukankan      html  css  js  c++  java
  • Spring Boot 拦截器

    首先,需要一个自定义拦截器,这个拦截器需要实现HandlerInterceptor接口

    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    @Component
    public class MyInterceptor implements HandlerInterceptor {
        // false 拦截    true 通行
    
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            return false;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            
        }
    }

    然后在三个Handle里面完成自己的逻辑

    填写完成之后,需要将这个类注册为拦截器

    另建一个拦截器配置类,添加@Configuration注解

    package cnki.tpi.interceptor;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class myInterceptorConfig implements WebMvcConfigurer {
    
        @Autowired
        private MyInterceptor myInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor)
              .addPathPatterns(
    "/**") .excludePathPatterns("/aaa/**"); } }

    此时需要注意的是,拦截器一定是通过@Autowired注入的,而不是在registry.addInterceptor(new MyInterceptor())是通过new出来的,不然会造成在MyInterceptor类的方法中,所有通过@Autowird注入进来的类都为null。

  • 相关阅读:
    Hive初识(一)
    图解HTTP总结(8)——确认访问用户身份的认证
    Android 7.0 照相 FileUriExposedException
    activity跳转的一些坑
    gopath配置
    android项目中记录
    一些趣味性总结(JAVA)
    http的response遇到illegalstateexception解决办法
    django demo
    Error:Execution failed for task ':app:transformClassesWithDexForDebug'解决方法
  • 原文地址:https://www.cnblogs.com/wulisz/p/14836933.html
Copyright © 2011-2022 走看看