@ResponseBody
ResponseEntity
응답 데이터를 응답 본문 메시지로 보낼 때 HttpMessageConverter를 선택하는데 그 때 선택하는 기준이 요청의 Accept 헤더이다.
@RestController
@RequestMapping("/api/events")
public class EventApi {
@PostMapping
@ResponseBody
public Event createEvent(@Valid @RequestBody Event event,
BindingResult bindingResult){
// save event
if(bindingResult.hasErrors()){
bindingResult.getAllErrors().forEach(error -> {
System.out.println(error);
});
}
return event;
}
}
@RestController가 @Controller + @ResponseBody이기 때문에 @ResponseBody는 생략 가능하다.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EventApiTest {
@Autowired
ObjectMapper objectMapperr;
@Autowired
MockMvc mockMvc;
@Test
public void createEvent() throws Exception{
Event event = new Event();
event.setName("spring");
event.setLimit(-20);
String json = objectMapperr.writeValueAsString(event);
mockMvc.perform(post("/api/events")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("name").value("spring"))
.andExpect(jsonPath("limit").value(-20));
}
}
@ResponseBody 대신 ResponseEntity를 사용할 수 있다. ResponseEntity를 사용하면 헤더, 본문, 상태 정보를 모두 다룰 수 있다.
@RestController
@RequestMapping("/api/events")
public class EventApi {
@PostMapping
public ResponseEntity<Event> createEvent(@RequestBody @Valid Event event, BindingResult bindingResult){
// save event
if(bindingResult.hasErrors()){
bindingResult.getAllErrors().forEach(error -> {
System.out.println(error);
});
return ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(event);
//return new ResponseEntity<Event>(event, HttpStatus.CREATED); 200이 아닌 201 Created 응답
return ResponseEntity.ok(event);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EventApiTest {
@Autowired
ObjectMapper objectMapperr;
@Autowired
MockMvc mockMvc;
@Test
public void createEvent() throws Exception{
Event event = new Event();
event.setName("spring");
event.setLimit(-20);
String json = objectMapperr.writeValueAsString(event);
mockMvc.perform(post("/api/events")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isBadRequest());
}
}
참고