레알윙 2020. 9. 7. 22:05
반응형

영문 설명

 

HTTP 메시지 컨버터

  • 요청 본문에서 메시지를 읽어들이거나(@RequestBody), 응답 본문에 메시지를 작성할 때(@ResponseBody) 사용한다. 기본 HTTP 메시지 컨버터
  • 바이트 배열 컨버터
  • 문자열 컨버터
  • Resource 컨버터
  • Form 컨버터 (폼 데이터 to/from MultiValueMap)
  • (JAXB2 컨버터)
  • (Jackson2 컨버터)
  • (Jackson 컨버터)
  • (Gson 컨버터)
  • (Atom 컨버터)
  • (RSS 컨버터)

 

설정 방법

  • 기본으로 등록해주는 컨버터에 새로운 컨버터 추가하기: extendMessageConverters
  • 기본으로 등록해주는 컨버터는 다 무시하고 새로 컨버터 설정하기
    • configureMessageConverters
    • 기본으로 사용한 컨버터는 사용하지 못함
  • 의존성 추가로 컨버터 등록하기 (추천)
    • 메이븐 또는 그래들 설정에 의존성을 추가하면 그에 따른 컨버터가 자동으로 등록 된다.
    • WebMvcConfigurationSupport
    • (이 기능 자체는 스프링 프레임워크의 기능임, 스프링 부트 아님.)

 

 

예제

@RestController
public class SampleController {
	
	@GetMapping("/jsonMessage")
	public PersonJson jsonMessage() {
		PersonJson person = new PersonJson(30, "json진석스");
		return person;
	}
}

 

public class PersonJson {
	private int age;
	private String name;

	public PersonJson(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

테스트 코드

import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.fasterxml.jackson.databind.ObjectMapper;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SampleControllerTest {

	@Autowired
	MockMvc mockMvc;
	
	@Autowired
	ObjectMapper objectMapper;
	

	@Test
	public void jsonMessage() throws Exception{
		PersonJson person = new PersonJson(30, "json진석스");
		String jsonString = objectMapper.writeValueAsString(person);
		
		this.mockMvc.perform(get("/jsonMessage")
				.contentType(MediaType.APPLICATION_JSON_UTF8)
				.accept(MediaType.APPLICATION_JSON_UTF8)
				.content(jsonString))
			.andDo(print())
			.andExpect(status().isOk());
	}
}

 

참고

반응형