问题场景:
postman的POST请求在body里传json格式的参数。
自定义filter过滤Controller,filter用于记录接口调用日志,filter里记录日志时,需要获取json格式的body数据,使用了
request.getReader();
或
request.getInputStream()
那么Controller就报错:
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing
原因:body数据不能被二次读取。filter里读取后,Controller里再次使用就会入坑。
解决方法:
一种、不使用body的json格式数据,可使用params(路径里?后面的)、headers、body(form-data)。
二种、使用spring AOP面向切面编程,一般用于事务、日志、鉴权、在用户请求时做一些统一处理等等,建@Aspect类,实现@Around方法,通过取Controller的方法参数。
调用顺序:内部顺序:@Around (point.proceed();前) —— @Before —— method —— @Around (point.proceed();后)—— @After —— @AfterReturning
在使用Postman进行POST请求并传递JSON格式参数时,遇到Controller报错`HttpMessageNotReadableException: Required request body is missing`。问题源于尝试在自定义filter中通过`request.getReader()`或`request.getInputStream()`读取body内容后,Controller无法再次解析body。解决方案包括不使用JSON格式的数据,改用params、headers或form-data,或者利用Spring AOP在方法调用前后记录日志。AOP的执行顺序为:@Around(point.proceed();前) —— @Before —— method —— @Around(point.proceed();后) —— @After —— @AfterReturning。
1260





