[Spring Tip] controller에서 @RequstBody, @RequestHeader 를 같이 사용해보자 :: 소림사의 홍반장!

스프링 사용하다가... 


controller에서 이렇게 선언해보았다...


public TestDTO businessTest(@RequestBody TestDTO dto2, @RequestHeader(value="api-key") String key) throws Exception {


안된다.. ㅋㅋ


대부분 controller에 @RestController 가 선언되어 있을텐데 내부에 @ResponseBody를 포함하고 있다.


@ResponseBody 사용시에는 @RequestBody와 @RequestHeader 를 혼용하여 사용할 수 없다는군..


그래서 해결법은


@RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
  String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));
  byte[] requestBody = requestEntity.getBody();
  // do something with request header and body

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.set("MyResponseHeader", "MyValue");
  return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}


이런식으로 하면 된답니다..


참고 ) http://stackoverflow.com/questions/14447731/optional-request-header-in-spring-rest-service



근데 그냥 저는....


@RequestMapping(value = "/businesses/test/{bizId}/{testId}", method = RequestMethod.POST)

public TestDTO businessTest(RemainDTO model1, @RequestBody TestDTO model2, HttpServletRequest req) throws Exception {

System.out.println("model1 : "+model1);

System.out.println("model2 : "+model2);

System.out.println("key : "+req.getHeader("api_key"));

return null;

}


HttpServletRequest 가져와서 getHeader 하는게 훨씬 낫네요 ㅋㅋ



다른 카테고리의 글 목록

Dev. 스프링/참고소스 및 예제 카테고리의 포스트를 톺아봅니다