Spring/boot

[Spring-boot] 웹MVC (1부) : 소개 , ViewResolver

jay Joon 2021. 1. 19. 01:27

이제 spring-boot 가 자동 설정하는 Configuration 중 WebMvcAutoConfiguration에 대해 서 알아보자.

 

WebMvcAutoConfiguration 은

 

SpringMvc의 자동 설정 Configuration이며 Springboot를 사용하면서 많은 자동 설정들을 도와준다.

 

Spring-boot를 실행하면서 자동 설정을 확장하거나 재정의 하는 방법은 다음과 같이 진행하면 된다.

  1. SpringMvc 확장

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
    }

    하나의 설정 파일에 WebMvcConfigurer를 구현하면 된다.

    여기서 WebMvcConfigurer 인터페이스가 제공하는 콜백 함수를 이용하여 사용자가 필요한 설정을 정의하면 된다.

    image

    이와 같은 방법은 SpringMvc의 자동 설정을 유지하며 확장해서 기능을 추가할 수 있기 때문에 이 방법을 추천한다.

  1. SpringMvc 재정의

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
    }

위 코드처럼 @EnableWebMvc을 사용하게 된다면 Spring-boot에서 제공해주는 자동 설정은 사용하지 않는다.

해당 방법은 스프링 부트가 제공해주는 편리한 자동 설정을 사용할 수 없음으로 권장하지 않는다.

 


ViewResolver

스프링 부트를 이용하면 다음과 같이 전략을 선택하여 등록할 수 있는데

image

이 중에서 ContentNegotiatingViewResolver를 살펴보자.

ContentNegotiatingViewResolver 은 요청 Headers 정보중 Accept를 확인하여 원하는 Data를 내려줄 수 있다.

image

Aceept 대한 자세한 내용:  https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/Accept

Test 코드로 보면 다음과 같다.

 @Test
    void getUser() throws Exception{
        User user =new User("JaeJoon",26);
        String content = objectMapper.writeValueAsString(user);

        mockMvc.perform(post("/user")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(content))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name",is(equalTo("JaeJoon"))))
                .andExpect(jsonPath("$.age",is(equalTo(26))));
    }
}

받고 싶은 data format을 accept에 선언한다면 해당 format 이 서버에 준비되어있다면 요청을 받을 수 있다.

 

spring-boot는 기본적으로 json 형태의 data format을 내려줄 수 있는 jackson 라이브러리를 들고 있으며

 

Xml 형태의 format을 받고 싶다면

<dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-xml</artifactId>
   <version>2.9.6</version>
</dependency>

pom.xml 에 추가해주면 된다.

@Test
void getXmlUser() throws Exception{
    User user =new User("JaeJoon",26);
    String content = objectMapper.writeValueAsString(user);

    mockMvc.perform(post("/user")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_XML)
            .content(content))
            .andExpect(status().isOk())
            .andExpect(xpath("/User/name").string("JaeJoon"))
            .andExpect(xpath("/User/age").string("26"));
}