레알윙 2020. 5. 8. 09:09
반응형

탬플릿 엔진이란?

  • view만 만드는데 사용하는게 아니라 code generation, e-mail 등 사용할 수 있으나 주로 view를 사용한다.
  • 동적 컨텐츠를 생성을한다.

 

 

스프링 부트가 자동 설정을 지원하는 템플릿 엔진

  • FreeMarker
  • Groovy
  • Thymeleaf
  • Mustache

 

 

스프링 부트가 JSP를 권장하지 않는 이유

 

 

Thymeleaf 사용

pom.xml 에 의존성 추가

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

파일 구조 및 위치

SamplecontrollerTest 코드

@RunWith(SpringRunner.class)
@WebMvcTest(Samplecontroller.class)
public class SamplecontrollerTest {
	
	@Autowired
	MockMvc mockMvc;
	
	@Test
	public void hello() throws Exception {
		// 요청 "/"
		// 응답
		// - 모델 name : jinseok
		// - 뷰이름 : hello
		mockMvc.perform(get("/hello"))
				.andExpect(status().isOk())
				.andDo(print())   // 랜더링이된 결과
				.andExpect(view().name("hello"))
				.andExpect(model().attribute("name", is("jinseok")));
	}
}

 

Samplecontroller 코드

@Controller
public class Samplecontroller {
	
	
	@GetMapping("/hello")
	public String hello(Model model) {
		model.addAttribute("jinseok");
		return "hello";
	}
}

 

 

hello.html 코드

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 th:text="${name}"> Name</h1>
</body>
</html>

 

반응형