ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot] Spring Boot에서 Thymeleaf 사용하기
    Backend/Spring 2022. 8. 12. 17:23

    Thymeleaf란?

    타임리프란 템플릿 엔진으로 흔히 뷰 템플릿이라고 부른다. Spring MVC 설계 시에 Controller가 전달하는 모델의 데이터를 이용하여 동적으로 화면을 구성할 수 있도록 View를 만들 수 있게 해준다.

    타임리프는 html 태그를 기반으로 하고 여기에 th:속성을 이용하여 동적인 View를 제공한다.

     

    Dependency 추가

    Maven의 경우 pom.xml에 다음을 추가하여 사용할 수 있다.

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

     

    ViewResolver 등록

    ApplcationContext에서 WebMvcConfigurer 인터페이스에 구현된 configureViewResolvers함수로 resolver를 등록한다.

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // jsp 등록
        registry.jsp().viewNames(new String[]{"jsp/*"});
    
        // jsp와 thymeleaf를 사용하기 위한 설정 과정
        var springResourceTemplateResolver = new SpringResourceTemplateResolver();
        springResourceTemplateResolver.setApplicationContext(applicationContext);
        springResourceTemplateResolver.setPrefix("/WEB-INF/"); // view template이 있는 경로
        springResourceTemplateResolver.setSuffix(".html"); // view 확장자
        var springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(springResourceTemplateResolver);
    
        // thymeleafViewResolver 등록
        var thymeleafViewResolver = new ThymeleafViewResolver();
        thymeleafViewResolver.setTemplateEngine(springTemplateEngine);
        thymeleafViewResolver.setOrder(1); // resolver는 chain으로 되어있기때문에 order 지정 
        thymeleafViewResolver.setViewNames(new String[]{"views/*"}); //jsp와 구분할 이름 지정
        registry.viewResolver(thymeleafViewResolver);
    }

     

    Thymeleaf  표현식

    1.  변수식 : ${OGNL}

    • OGNL(Object-Graph Navigation Language) : 객체의 속성에 값을 가져와서 설정하는 표현식
    // customers.html
    <tr th:each="customer: ${customers}">
        <td th:text="${customer.customerId}"></td>
        <td th:text="${customer.name}"></td>
        <td th:text="${customer.email}"></td>
    </tr>

     

    여기서 customers는 controller에서 반환한 모델의 key값으로 고객들의 리스트를 담고있다. each를 사용해 고객리스트에서 고객을 customer 변수에 담아서 사용한다.

    // Customer Controller 클래스
    @RequestMapping(value = "/customers", method = RequestMethod.GET)
    public String findCustomers(Model model) {
        var allCustomers = customerService.getAllCustomers();
        model.addAttribute("customers", allCustomers);
        return "views/customers";
    }

     

    아래의 Customer 클래스에서 정의한 속성 값을따라 가져온 customer 객체에 대해 속성 값으로 접근할 수 있다. 

    // Customer 클래스
    class Customer {
        private UUID customerId;
        private String name;
        private String email;
    }

     

     

    2. 메시지식 : #{코드}

    스프링의 메시지 소스와 연동하여 메시지 코드를 넣으면 해당 메시지가 출력된다. 다국어 처리에 용이하다.

     

     

    3. 링크식 : @{링크}

    html의 a태그와 함께 사용하여 th:href 속성으로 해당 표현식을 사용한다. 

    <a th:href="@{http://localhost:8080/examples/customers}">view</a>

     

    다음처럼 /로 시작하는 링크 패스의 경우 자동으로 애플리케이션 컨텍스트 네임이 앞에 붙게된다.

    <a th:href="@{/customers}">view</a>

     

    링크 패스에 변수식이나 선택 변수 식이 포함되어야 할 경우 다음과 같이 사용한다.

    <a th:href="@{/customers/{customerId}(customerId=*{customerId})}">Details</a>

     

     

    4. 선택 변수식: *{OGNL}

    th:object를 사용하여 객체를 선택했을 경우 이 표현식으로 필드에 접근한다.

    <tr th:each="customer: ${customers}" th:object="${customer}">
        <td th:text="*{customerId}"></td>
        <td th:text="*{name}"></td>
        <td th:text="*{email}"></td>
    </tr>

     

    댓글

Designed by Tistory.