[전자정부프레임워크 3.9] @RequestBody 를 Nullable 처리 하기
출처입니다 : java - Use @RequestBody with optional body in latest Spring v4 - Stack Overflow
Use @RequestBody with optional body in latest Spring v4
How do I make body optional in REST API calls when using @RequestBody annotation in Spring? With Spring's latest version, if you use @RequestBody annotation, it makes client to send body all the t...
stackoverflow.com
아래와 같은 메서드를 테스트로 URL 만 호출 시에 해당 Controller 메서드로 진입 전에 , 400 오류가 발생하면서
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing:
이라는 메시지가 표시 되었습니다.
@RequestMapping(value="/v1/parameterTest.json")
public Object parameterTest(@RequestHeader HttpHeaders headers,@RequestBody Map<String,Object> requestBody, HttpServletResponse response, HttpServletRequest request, ModelMap model) throws Exception {
String methodName = String.format("[%s][%s]", CLASSNAME, new Exception().getStackTrace()[0].getMethodName());
LOGGER.error(String.format("%s Occurred", methodName));
ResTestObject resTestObject = null;
try {
// 1. Request로 받은 Body
//@RequestBody Map<String,Object> requestBody,
if(requestBody != null)
LOGGER.error(String.format("%s RequestBody=%s",methodName,requestBody ));
// 2. Sample Response 처리 진행
String smpResp = "{\"result_code\":\"0\",\"result_message\":\"SUCCEEDED\"}";
Gson gson = new GsonBuilder().create();
resTestObject = gson.fromJson(smpResp, ResTestObject.class);
} catch(Exception exception) {
LOGGER.error(methodName,exception);
}
return resTestObject;
}
위 메서드의 매개변수 @RequestBody Map<String,Object> requestBody 를
-> @RequestBody Optional<Map<string,object>> requestBody 로 변경 하니 ( Optional 키워드로 감싸주니 )
log4j error 레벨로 기록한 RequestBody도
RequestBody=Optional.empty 로 출력 되었습니다.
[RequestBody 존재 시에도 정상적으로 JSON Parameter의 Key , Value가 출력 된 것을 확인 하였습니다.]