Study/Spring

[Spring] Handler Method(ResponseEntity)

개발개발개발 2021. 9. 12. 22:52

ResponseEntity

"개발자가 직접 데이터와 HTTP 상태 코드를 제어할 수 있는 클래스"

스프링에서는 HttpEntity라는 클래스가 있다. 이 클래스를 타고 들어가면 HttpHeader와 HttpBody를 포함하고 있는 것을 볼 수 있다. 

HttpEntity 클래스

그리고 이 HttpEntity를 상속받아 구현한 클래스가 RequestEntity, ResponseEntity 클래스이다. 그렇다면 나는 이 클래스들을 이용하여 좀 더 세밀하게 요청&응답 값을 작업할 수 있을 것이다.

ResponseEntity
RequestEntity

 

간단한 예시를 들어보자.

컨트롤러는 전에 modelattribute를 공부할 때 썼던 메서드를 재활용하였다.

중간 값은 무시하고 값을 return 할 때,  ResponseEntity에 dante 클래스와 http 상태 코드를 함께 담아서 보낸다. 

이때 httpstatus는 서버 에러로 응답할 것이다. 

@RequestMapping(method = RequestMethod.POST, path = "/DDante") 
public ResponseEntity<Object> valueDante(@ModelAttribute("Dante") Dante dante, BindingResult bindingResult ) {
	System.out.println("Dead : " + dante.getDeadLift());
	System.out.println("Squat : " + dante.getSquat());
	System.out.println("Bench : " + dante.getBenchPress());
		
	if(bindingResult.hasErrors()) { //바인딩 에러 처리 
		System.out.println("=======================");
		System.out.print("Error");
		bindingResult.getAllErrors().forEach(c -> { //에러가 발생할 시 출력
               System.out.println(c.toString());
           });
	}		
		//리턴 값
	return new ResponseEntity<Object>(dante,HttpStatus.INTERNAL_SERVER_ERROR);
}

 

그리고 아래와 같이 코드를 짜고 post로 요청하였다.

@Test
void test5() throws Exception {
	mockMvc.perform(post("/DDante")
			.param("deadLift", "120")
			.param("squat", "110")
			.param("benchPress", "70")
			.param("conventional", "nolimit")
			)
		.andDo(print())
		.andExpect(status().isOk());
}

 

그 후 다음과 같이 응답 값을 확인할 수 있다.

상태 코드는 500으로 응답받았고 Body 안에는 처음에 내가 보냈던 파라미터 그대로 body안에 담겨서 온 것을 확인하였다. 

 

이렇게 클라이언트에 응답할 때 좀 더 세밀한 작업이 가능한 것을 확인하였다. 

 

 

'Study > Spring' 카테고리의 다른 글

[Spring] spring JDBC  (0) 2021.10.04
[Spring] RestTemplate  (0) 2021.09.23
[Spring] @ModelAttribute  (0) 2021.09.08
[Spring] Spring IoC Container 그리고 Bean  (0) 2021.08.29
[Spring] Dispatcher Servlet  (0) 2021.08.24