对于POST请求,若参数通过请求体(如JSON或表单数据)传递,直接调用 request.getParameter()可能无法获取(尤其是JSON格式)
解决:
表单参数:若参数在请求体的表单中(Content-Type: application/x-www-form-urlencoded),仍可使用 request.getParameter()。
JSON参数:需从输入流中解析:
// 读取请求体并解析JSON
String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
JSONObject json = JSON.parseObject(body);
String param = json.getString("key");
直接读取输入流会导致后续Controller无法再次读取,需通过包装类缓存输入流
使用 HttpServletRequestWrapper包装请求,缓存输入流数据
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private final byte[] cachedBody;
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
cachedBody = IOUtils.toByteArray(request.getInputStream());
}
@Override
public ServletInputStream getInputStream() {
return new CachedBodyServletInputStream(cachedBody);
}
// 其他方法(如getReader)需同步重写
}
在Filter中包装请求
public class CacheRequestBodyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
if (request instanceof HttpServletRequest) {
CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest((HttpServletRequest) request);
chain.doFilter(wrappedRequest, response);
} else {
chain.doFilter(request, response);
}
}
}
使用AOP(面向切面)拦截Controller方法,直接获取 @RequestBody参数
@Around("@annotation(org.springframework.web.bind.annotation.PostMapping)")
public Object around(ProceedingJoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
// 解析args中的@RequestBody参数
return joinPoint.proceed(args);
}
8733

被折叠的 条评论
为什么被折叠?



