Spring中添加打印请求头的拦截器

问题

因为最近这个项目没有调用链监控系统的支持,但是,本地PostMan调试的时候又需要请求头才能正常调试。

思路

喊ChatGPT实现一下能够打印所有请求头的拦截器,然后,集成到已有代码即可。

解决

RequestHeaderInterceptor.java

package cn.xxxx.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 打印接受到的所有请求头
 * @author zhangyalin
 */
@Slf4j
@Component
public class RequestHeaderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取所有请求头的名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            // 获取请求头的值并打印
            String headerValue = request.getHeader(headerName);
            log.debug(headerName + ": " + headerValue);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

WebMvcConfiguration.java

在Springboot的配置类中集成上面的拦截器即可。

package cn.xxxx.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 基础配置
 * @author zhangyalin
 */
@RefreshScope
@ComponentScan({"cn.xxxx", "cn.xxx.sxa"})
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Resource
    private RequestHeaderInterceptor requestHeaderInterceptor;

    @Value("${interceptors.requestHeaderInterceptor:false}")
    private boolean requestHeaderInterceptorEnable;

    /**
     * 注入拦截器
     *
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (requestHeaderInterceptorEnable){
            // 打印所有请求头
            registry.addInterceptor(requestHeaderInterceptor).order(Ordered.HIGHEST_PRECEDENCE).addPathPatterns("/**");
        }
    }
}

配置中心

logging:
  level:
    cn.xxxx.interceptor: DEBUG
interceptors:
  requestHeaderInterceptor: true

总结

这就是简单使用HandlerInterceptor,实现自己的请求头打印拦截器。我这里配置中心,动态性还是不很完善。interceptors.requestHeaderInterceptor配置修改后,得重启服务才能生效。

你可能感兴趣的:(spring,java,后端,http,header,interceptor)