创建一个过滤器,在该过滤器中使用 ContentCachingRequestWrapper 包装 HttpServletRequest 对象。
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Configuration
@Order(0)
@Slf4j
public class RequestLoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (contentType == null || !contentType.contains("application/json")) {
filterChain.doFilter(request, response);
return;
}
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
try {
filterChain.doFilter(requestWrapper, response);
} finally {
// 将请求参数从缓存中读取,并记录在日志中
byte[] content = requestWrapper.getContentAsByteArray();
if (content.length > 0) {
log.info("Request body: {}", new String(content, 0, content.length, StandardCharsets.UTF_8));
}
// 清除 ContentCachingRequestWrapper 中的缓存
requestWrapper.resetContent();
}
}
}
注册过滤器
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<Filter> requestLoggingFilter() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new RequestLoggingFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(0);
return registrationBean;
}
}
本文由 GY 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2023/03/22 11:04