본문 바로가기
Spring Boot

Thymeleaf

by 상국이 2022. 2. 28.
728x90

탬플릿 엔진

JSP 단점 

  > 서블릿 엔진이 JSP 스펙을 구현하여 최종적인 뷰가 나옴 - 랜더링된 결과를 확인하기 힘듬

  > Thymeleaf 를 사용하면 Thymeleaf가 독자적으로 (Servlet Container의 개입 없이) View를 완성하여 랜더링된 결과를 확인하기 쉬움 (웹서버를 안띄워도 mockMVC만으로 test가 가능하다.)

 

예제)

controller

@Controller
public class SampleController {

    @GetMapping("/hello")
    public String hello(Model model){
        model.addAttribute("name", "sangguk");      //model > attribute
        return "hello";                                                      //view name
    }
}

template

<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${name}">이름이 안나와요ㅠ</h1>
</body>
</html>

test code

@RunWith(SpringRunner.class)
@WebMvcTest(SampleController.class)
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void hello() throws Exception {
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(view().name("hello"))
                .andExpect(model().attribute("name", is("sangguk")))
                .andExpect(content().string(containsString("sangguk")));
    }
}
728x90

'Spring Boot' 카테고리의 다른 글

문법  (0) 2022.02.28
HtmlUnit  (0) 2022.02.28
Spring 정적 리소스 맵핑  (0) 2022.02.27
ViewResolver  (0) 2022.02.27
HttpMessageConverters  (0) 2022.02.20

댓글