ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 핸들러 메소드 15부: @RequestBody & HttpEntity
    SPRING/스프링 MVC 2021. 7. 10. 16:00

    @RequestBody 

    - 요청 본문(body)에 들어있는 데이터를 HttpMessageConveter를 통해 변환한 객체로 받아올 수 있다. 

    -  @Valid 또는 @Validated를 사용해서 값을 검증 할 수 있다. 

    - BindingResult 아규먼트를 사용해 코드로 바인딩 또는 검증 에러를 확인할 수 있다. 

     

    HttpMessageConverter 

    - 스프링 MVC 설정 (WebMvcConfigurer)에서 설정할 수 있다. 

    - configureMessageConverters: 기본 메시지 컨버터 대체 

    - extendMessageConverters: 메시지 컨버터에 추가 

    - 기본 컨버터 

    - WebMvcConfigurationSupport.addDefaultHttpMessageConverters 

     

    HttpEntity 

    - @RequestBody와 비슷하지만 추가적으로 요청 헤더 정보를 사용할 수 있다. 

     

    @RestController
    @RequestMapping("/api/events")
    public class EventApi {
    
        @PostMapping
        public Event createEvent(@RequestBody @Valid Event event, BindingResult bindingResult) {
            // save event
            // Binding 에러 있을 시에 Sys.out 으로 출력
            if(bindingResult.hasErrors()) {
                bindingResult.getAllErrors().forEach(error->{
                    System.out.println(error);
                });
            }
            return event;
        }
    }

     

     

    @Valid를 통해 Validation Check 또한 가능하다. BindingResult를 사용하여 BindingException으로 Exception 처리하는 것도 가능하다.

     

    테스트코드

    @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))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("name").value("spring"))
                    .andExpect(jsonPath("limit").value(-20));
        }
    
    
    }

     

    HttpEntity

    HttpEntity를 사용하면 @RequestBody와 달리 Header 정보도 접근할 수 있다.

    @RestController
    @RequestMapping("/api/events")
    public class EventApi {
    
        @PostMapping(value = "/basic")
        public Event createEvent(@RequestBody @Valid Event event, BindingResult bindingResult) {
            // save event
            // Binding 에러 있을 시에 Sys.out 으로 출력
            if(bindingResult.hasErrors()) {
                bindingResult.getAllErrors().forEach(error->{
                    System.out.println(error);
                });
            }
    
            return event;
        }
    
        // HttpEntity는 헤더 정보에도 접근할 수 있다.
        @PostMapping(value = "/upgrade")
        public Event createEventWithHttpEntity(HttpEntity<Event> request) {
            // save event
            MediaType contentType = request.getHeaders().getContentType();
            System.out.println(contentType);
            return request.getBody();
        }
    
    
    
    }

     

Designed by Tistory.