springboot 拦截器

1、编写拦截器

  

package com.ne.scrm.org.interceptor;


import com.software.boot.common.ThreadContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ne.scrm.org.api.consts.MyConstants.DEALER_ID;
import static com.ne.scrm.org.api.consts.MyConstants.EMP_ID;

/**
 * @author Yunugi
 * @since 2020-12-21
 */
public class CommonDataHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ThreadContext.put(EMP_ID, request.getHeader(EMP_ID));
        ThreadContext.put(DEALER_ID, request.getHeader(DEALER_ID));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadContext.remove(EMP_ID);
        ThreadContext.remove(DEALER_ID);
    }
}

  

2、注册

  

package com.ne.scrm.org.config;


import com.ne.scrm.org.interceptor.CommonDataHandlerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.net.URLDecoder;


/**
 * Make use of MVC pattern to process args.
 * Called before calling HandlerAdapter.
 *
 * @author Yungui
 * @since 20201221
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(headerDataInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public CommonDataHandlerInterceptor headerDataInterceptor() {
        return new CommonDataHandlerInterceptor();
    }

}

  

 

posted on 2020-12-23 10:34  滚动的蛋  阅读(108)  评论(0编辑  收藏  举报

导航