request.getParameter无法在HandlerInterceptor中获取参数

对于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);
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值