zoukankan      html  css  js  c++  java
  • 在springboot中添加拦截器

    1、首先定义一个拦截器

    package com.leyou.interceptor;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author houChen        拦截器在拦截之前 中 与之后的处理事件
     * @date 2020/5/14 20:25
     * @Description:
     */
    public class LoginInterceptor implements HandlerInterceptor {
    
        private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            logger.debug("preHandle method is now running!");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
            logger.debug("postHandle method is now running!");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            logger.debug("afterCompletion method is now running!");
        }
    }

    2、定义配置类,注册拦截器

    package com.leyou.config;
    
    import com.leyou.interceptor.LoginInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @author houChen
     * @date 2020/5/14 20:26
     * @Description:
     */
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
        /**
         * 通过@Bean注解,将我们定义的拦截器注册到Spring容器
         * @return
         */
        @Bean
        public LoginInterceptor loginInterceptor(){
            return new LoginInterceptor();
        }
    
        /**
         * 重写接口中的addInterceptors方法,添加自定义拦截器
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 通过registry来注册拦截器,通过addPathPatterns来添加拦截路径 
            registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/hello"); //这里表示对所有/hello的路径进行拦截
        }
    }

    3、效果如下

  • 相关阅读:
    About me
    判断IE和360浏览器
    windows系统下在Hbuilder和WebStorm使用autoprefixer插件
    从零到一详聊如何创建Vue工程及遇到的常见问题
    谈谈axios配置请求头content-type
    vue-router导航守卫(router.beforeEach())的使用
    vue-cli项目使用mock数据的方法(借助express)
    vue.js移动端配置flexible.js
    图解CSS3-flex布局
    vue工程利用pubsub-js实现兄弟组件之间的通信
  • 原文地址:https://www.cnblogs.com/houchen/p/12891290.html
Copyright © 2011-2022 走看看