地方網(wǎng)站需要什么手續(xù)成免費crm軟件有哪些優(yōu)點
我們編寫RestController時,有可能多個接口使用了相同的RequestBody,在一些場景下需求修改傳入的RequestBody的值,如果是每個controller中都去修改,代碼會比較繁瑣,最好的方式是在一個地方統(tǒng)一修改,比如將header中的某個值賦值給RequestBody對象的某個屬性。 示例項目 https://github.com/qihaiyan/springcamp/tree/master/spring-modify-request-body
一、概述
在spring中可以使用RequestBodyAdviceAdapter修改RestController的請求參數(shù)。
二、自定義 RequestBodyAdviceAdapter
以下代碼為自定義 ModifyBodyAdvice 實現(xiàn) RequestBodyAdviceAdapter
@ControllerAdvice
public class ModifyBodyAdvice extends RequestBodyAdviceAdapter {@AutowiredHttpServletRequest httpServletRequest;@Override@NonNullpublic Object afterBodyRead(@NonNull Object body, @NonNull HttpInputMessage inputMessage,@NonNull MethodParameter parameter, @NonNull Type targetType,@NonNull Class<? extends HttpMessageConverter<?>> converterType) {String requestMethod = httpServletRequest.getMethod();String fieldName = "foo";if (StringUtils.startsWithIgnoreCase(requestMethod, HttpMethod.PUT.name())|| StringUtils.startsWithIgnoreCase(requestMethod, HttpMethod.POST.name())) {Field field = ReflectionUtils.findField(body.getClass(), fieldName);if (field != null) {ReflectionUtils.makeAccessible(field);String paramValue = Optional.ofNullable(httpServletRequest.getHeader(fieldName)).orElse("");Method method = ReflectionUtils.findMethod(body.getClass(), "set" +StringUtils.capitalize(fieldName), field.getType());if (method != null) {ReflectionUtils.invokeMethod(method, body, paramValue);}}}return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);}@Overridepublic boolean supports(@NonNull MethodParameter methodParameter,@NonNull Type targetType,@NonNull Class<? extends HttpMessageConverter<?>> converterType) {return true;}
}
便于演示處理過程,我們在代碼中寫死了要修改的請求對象的屬性為 foo ,從請求header中獲取foo這個header的值,然后通過反射賦值到請求對象的foo屬性。
三、驗證統(tǒng)一修改邏輯
我們通過編寫單元測試的方式驗證RequestBody的值是否能夠正常修改。
在DemoApplicationTest這個單元測試程序中進行接口調用,并驗證返回結果。
@Testpublic void test() {ReqBody reqBody = new ReqBody();ResponseEntity<ReqBody> resp = testRestTemplate.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中發(fā)送了foo這個header,按照處理邏輯,controller中接收到的ReqBody對象的foo的值應該是header的值。