十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Spring统一修改Controller的RequestBody

Spring统一修改Controller的RequestBody 我们编写RestController时有可能多个接口使用了相同的RequestBody在一些场景下需求修改传入的RequestBody的值如果是每个controller中都去修改代码会比较繁琐最好的方式是在一个地方统一修改比如将header中的某个值赋值给RequestBody对象的某个属性。 示例项目 https://github.com/qihaiyan/springcamp/tree/master/spring-modify-request-body一、概述在spring中可以使用RequestBodyAdviceAdapter修改RestController的请求参数。二、自定义 RequestBodyAdviceAdapter以下代码为自定义 ModifyBodyAdvice 实现 RequestBodyAdviceAdapterControllerAdvicepublicclassModifyBodyAdviceextendsRequestBodyAdviceAdapter{AutowiredHttpServletRequesthttpServletRequest;OverrideNonNullpublicObjectafterBodyRead(NonNullObjectbody,NonNullHttpInputMessageinputMessage,NonNullMethodParameterparameter,NonNullTypetargetType,NonNullClass?extendsHttpMessageConverter?converterType){StringrequestMethodhttpServletRequest.getMethod();StringfieldNamefoo;if(StringUtils.startsWithIgnoreCase(requestMethod,HttpMethod.PUT.name())||StringUtils.startsWithIgnoreCase(requestMethod,HttpMethod.POST.name())){FieldfieldReflectionUtils.findField(body.getClass(),fieldName);if(field!null){ReflectionUtils.makeAccessible(field);StringparamValueOptional.ofNullable(httpServletRequest.getHeader(fieldName)).orElse();MethodmethodReflectionUtils.findMethod(body.getClass(),setStringUtils.capitalize(fieldName),field.getType());if(method!null){ReflectionUtils.invokeMethod(method,body,paramValue);}}}returnsuper.afterBodyRead(body,inputMessage,parameter,targetType,converterType);}Overridepublicbooleansupports(NonNullMethodParametermethodParameter,NonNullTypetargetType,NonNullClass?extendsHttpMessageConverter?converterType){returntrue;}}便于演示处理过程我们在代码中写死了要修改的请求对象的属性为 foo 从请求header中获取foo这个header的值然后通过反射赋值到请求对象的foo属性。三、验证统一修改逻辑我们通过编写单元测试的方式验证RequestBody的值是否能够正常修改。在DemoApplicationTest这个单元测试程序中进行接口调用并验证返回结果。Testpublicvoidtest(){ReqBodyreqBodynewReqBody();ResponseEntityReqBodyresptestRestTemplate.exchange(RequestEntity.post(/test).header(foo,test).body(reqBody),ReqBody.class);log.info(result : {},resp);assertThat(resp.getBody().getFoo(),is(test));}我们调用controller时传入了的RequestBody为 ReqBody的一个对象这个对象没有对属性进行赋值在请求header中发送了foo这个header按照处理逻辑controller中接收到的ReqBody对象的foo的值应该是header的值。
返回列表