📗 configureContentNegotiation

반환하는 데이터의 content값을 협상하는 부분이다. 협상이란 특정 값에 따라 어떤 형식으로 반환을 해야할지를 정한다는 의미인데 해당 부분을 코드로 확인해보자.

📄 configureContentNegotiation 예제

✅ 데이터 만들기

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TempDto {
    private Long id;
    private String name;
}

다음과 같은 Dto를 생성했고

@V1
@RestController
public class HelloController {
	...
    
    @GetMapping("/json")
    public ResponseEntity<TempDto> json(){
        return ResponseEntity.ok(TempDto.builder()
                .id(1L)
                .name("테스터")
                .build());
    }
}

라는 반환 형식을 지정했다.

호출했을 때 json으로 정상 반환되는 것을 확인할 수 있다. 그럼 여기서 configureContentNegotiation()를 통해 xml로 변환해보자

✅ configureContentNegotiation 사용하기

dependencies {
    ...
    
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.2'
}

먼저 jackson-dataformat의 의존성을 추가해주어야 한다. default가 json 형태라서 xml foramt은 의존성을 추가해주지 않으면 따로 동작하지 않기 때문이다.

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.parameterName("contentType")
                .favorParameter(true)
                .ignoreAcceptHeader(true)
                .defaultContentType(MediaType.APPLICATION_JSON) // 기본 설정은 json
                .mediaType("json", MediaType.APPLICATION_JSON)  // json인 경우에는 json
                .mediaType("xml", MediaType.APPLICATION_XML)    // xml인 경우에는 xml
        ;
    }
}
  1. 그 후 다음과 같이 parameterName()을 통해 parameter 명을 지정해준다.
  2. favorParameter()를 true로 주어 파라미터에 따라 Content-Type을 적용하도록 적용한다.
  3. ignoreAcceptHeader() 를 통해 기본 정책인 header의 Content-Type을 우선적용하지 않도록 막는다.
  4. defaultContentType() 파라미터가 넘어오지 않을 경우 default 설정
  5. mediaType() 파라미터 값에 따라 어떤 반환 데이터를 지정할지 선언해준다.

✅ 테스트 해보자!

다음과 같이 json 기본 형태가 내려오고

contentType 파라미터 값이 json일 경우에도 동일하게 내려온다.

마지막으로 xml로 선언하면 다음과 같이 xml 데이터가 반환됨을 확인할 수 있다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN