Spring使用Filter添加自定义header

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

定义Request包装类

  • MutableHttpServletRequest
final class MutableHttpServletRequest extends HttpServletRequestWrapper {
    private final Map 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 getHeaderNames() {
        if (customHeaders.isEmpty()) {
            return super.getHeaderNames();
        }

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

自定义Filter

  • CustomFilter
@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");
    }
}

验证

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

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

注意

  • 当使用@WebFilter时(自动注册),需要再Spring Boot上添加注解@ServletComponentScan

参考

  • Adding custom headers to Java HttpServletRequest
  • Using Servlet components: @WebServlet, @WebFilter and @WebListener in Spring boot application

你可能感兴趣的:(Spring使用Filter添加自定义header)