일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- autocomplete
- Mockito #Reflection #Sigleton #Test #JUnit
- spring
- Spring Framework
- tomcat
- LiveTemplate
- 외장톰캣
- 디자인패턴 #싱글톤
- 톰캣
- Today
- Total
자라선
16. Spring MVC 본문
Spring MVC는 기존의 MVC 디자인 패턴을 Spring Framework에 접목하여 개발된 의존성 라이브러리 이다.
https://docs.spring.io/spring/docs/5.0.7.RELEASE/spring-framework-reference/web.html#spring-web
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/")
public String hello(){
return "hello";
}
}
위 코드와 같이 쉽게 핸들러를 만들고 매핑까지 간단하게 구현할수 있다.
이렇게 쉽게 구현할수 있는 이유는 @SpringBootApplication 어노테이션이 시작될때
@EnableAutoConfiguration 어노테이션이 실행되며 spring.factories에 명시된 리스트 중 WebMvcAutoConfiguration 클래스가 빈으로 등록되고 이러한 클래스 내부에는 자동설정 파일이 적용이 되어있다.
모든 클래스는 Boot에서 제공하는게 아닌 Spring Framework의 기반하여 Boot로 만들어진 클래스들도 있다.
· 스프링 MVC 확장
o @Configuration + WebMvcConfigurer
· 스프링 MVC 재정의
o @Configuration + @EnableWebMvc
HttpMessageConverters
스프링 프레임워크에서 제공하는 인터페이스이며 스프링 MVC의 일부분
요청이 들어온 Http 본문을 객체로 변경 하거나 응답으로 보낼 객체를 Http 본문으로 컨버팅할 때 사용
@RequestBody
@ResponseBody
사용 예)
· public @ResponseBody User create (@RequestBody User user)
요청을 보낼 때 ContentType 이 JSON 포맷 이고 본문도 JSON 포맷이라면 JsonHttpMessageConverter 가 사용이 되고 응답할때 @ResponseBody 이고 String 이라면 StringHttpMessageConverter, Json이라면 json converter가 사용이 된다.
@RestController 가 정의 되어있다면 클래스 내부의 모든 메소드의 반환에는 @ResponseBody가 묵시적으로 정의 되어있다.
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.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void createUser_JSON() throws Exception {
String userJson = "{\"username\":\"thkong\", \"password\":\"123\"}";
mockMvc.perform(post("/users/create")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8) // 응답으로 원하는 타입
.content(userJson))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username", is(equalTo("thkong"))))
.andExpect(jsonPath("$.password", is(equalTo("123"))));
}
}
ViewResole
스프링 프레임워크는 ContentNegotationViewResolver 를 사용하여 응답을 보내줄 뷰를 찾게 되는데 모든 뷰를 search하고 accept header의 정보로 가장 적합한 뷰를 사용자에게 응답해준다.
XML 테스트
xml로 응답되는 테스트는 별도의 의존성을 추가해줘야한다.
이는 제공되는 xmlHttpMessageConverter에서 xmlMapper의 값이 없기 때문에.
HttpMessageConvertersAutoConfiguration의 @Import 에서 JacksonHttpMessageConvertersConfiguration의 XmlMapper.class 가 사용된다.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.6</version>
</dependency>
@Test
public void createUserXml() throws Exception {
String jsonData ="{\"username\":\"thkong\", \"password\":\"123\"}";
mockMvc.perform(post("/createJson")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_XML)
.content(jsonData))
.andDo(print())
.andExpect(status().isOk())
.andExpect(xpath("/User/username").string("thkong"))
.andExpect(xpath("/User/password").string("123"));
}
'Develop > Spring Boot' 카테고리의 다른 글
19. Thymeleaf (0) | 2020.07.27 |
---|---|
18. webJars (0) | 2020.07.27 |
15. devtools (0) | 2020.07.27 |
14. Test (0) | 2020.07.27 |
13. Logging (0) | 2020.07.27 |