配置了permit-all_urls=/**的时候,当异常发生在Servlet(eg:TokenAuthenticationFilter,xxxFilter)时,

代码进入到 ApiAccessLogInterceptor 的时候,拿到的是原始的request而不是CacheRequestBodyWrapper,这时候不能 getBody from request, 否则会抛异常 request 已经被消费或者流已经被关闭
This commit is contained in:
housewu@aslcn.com.cn 2025-03-15 19:38:26 +08:00
parent 2a9dffb6ed
commit 970722d9b1
3 changed files with 18 additions and 1 deletions

View File

@ -77,6 +77,12 @@ public class ServletUtils {
public static String getBody(HttpServletRequest request) { public static String getBody(HttpServletRequest request) {
// 只有在 json 请求在读取因为只有 CacheRequestBodyFilter 才会进行缓存支持重复读取 // 只有在 json 请求在读取因为只有 CacheRequestBodyFilter 才会进行缓存支持重复读取
if (isJsonRequest(request)) { if (isJsonRequest(request)) {
// 优先从请求属性中获取缓存的请求体
String body = (String) request.getAttribute("cache_body");
if (StrUtil.isNotEmpty(body)) {
return body;
}
return JakartaServletUtil.getBody(request); return JakartaServletUtil.getBody(request);
} }
return null; return null;

View File

@ -19,7 +19,10 @@ public class CacheRequestBodyFilter extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException { throws IOException, ServletException {
filterChain.doFilter(new CacheRequestBodyWrapper(request), response); CacheRequestBodyWrapper cacheRequestBodyWrapper = new CacheRequestBodyWrapper(request);
String body = ServletUtils.getBody(cacheRequestBodyWrapper);
request.setAttribute(CacheRequestBodyWrapper.CACHE_BODY, body);
filterChain.doFilter(cacheRequestBodyWrapper, response);
} }
@Override @Override

View File

@ -18,6 +18,11 @@ import java.io.InputStreamReader;
*/ */
public class CacheRequestBodyWrapper extends HttpServletRequestWrapper { public class CacheRequestBodyWrapper extends HttpServletRequestWrapper {
/**
* 缓存在 request.attribute body
*/
public static final String CACHE_BODY = "cache_body";
/** /**
* 缓存的内容 * 缓存的内容
*/ */
@ -26,6 +31,9 @@ public class CacheRequestBodyWrapper extends HttpServletRequestWrapper {
public CacheRequestBodyWrapper(HttpServletRequest request) { public CacheRequestBodyWrapper(HttpServletRequest request) {
super(request); super(request);
body = ServletUtils.getBodyBytes(request); body = ServletUtils.getBodyBytes(request);
if (body != null) {
request.setAttribute(CacheRequestBodyWrapper.CACHE_BODY, new String(body));
}
} }
@Override @Override