Spring使用Filter添加自定义header

2019-07-16  本文已影响0人  十毛tenmao

项目中有时候为了简化业务逻辑,可以在Filter中统一添加一些header信息,比如使用token获取到userId后,添加到header中,这样各个业务就可以直接使用useId。

定义Request包装类

final class MutableHttpServletRequest extends HttpServletRequestWrapper {
    private final Map<String, String> customHeaders;
 
    public MutableHttpServletRequest(HttpServletRequest request){
        super(request);
        this.customHeaders = new HashMap<>();
    }
    
    public void putHeader(String name, String value){
        this.customHeaders.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        String headerValue = customHeaders.get(name);
        
        if (headerValue != null){
            return headerValue;
        }
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        if (customHeaders.isEmpty()) {
            return super.getHeaderNames();
        }

        Set<String> set = new HashSet<String>(customHeaders.keySet());
        // 添加自定义header
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            String n = e.nextElement();
            set.add(n);
        }
 
        return Collections.enumeration(set);
    }
}

自定义Filter

@Slf4j
@WebFilter(urlPatterns = "/*")
public class CustomFilter implements Filter {

    @Override
    public void destroy() {
        log.info("filter destroy");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        log.info("filter doFilter");
        HttpServletRequest req = (HttpServletRequest) request;
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
        mutableRequest.putHeader("x-custom-header", "custom value");
        chain.doFilter(mutableRequest, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("filter init");
    }
}

验证

@ServletComponentScan
@SpringBootApplication
@RestController
public class CustomFilterApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyFilterApplication.class, args);
    }

    @GetMapping("ping")
    public String ping() {
        return "success";
    }
}

注意

参考

上一篇下一篇

猜你喜欢

热点阅读