티스토리 뷰

반응형

Spring Boot 레퍼런스 가이드(Spring Boot Reference Guide)에서 템플릿(Template)에 관한 내용을 보면 매우 간단한 가이드를 볼 수 있습니다.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-template-engines

위 링크에서 확인할 수 있듯이 몇 가지 템플릿 엔진을 사용할 수 있도록 제공되고 있으며, 전통적인 방식의 JSP 는 제약이 있으므로 사용을 피하라는 안내가 있습니다.

여기서는 의존성으로 Web 와 Lombok 이 선택된 Spring Boot 프로젝트를 이용하여 Thymeleaf 템플릿을 이용하는 방법을 간단히 설명하겠습니다. Thymeleaf 는 html 확장자를 이용하고 태그(Tag)을 이용하기 때문에 템플릿 파일을 웹브라우져에서 열었을 때에도 내용이 잘 보여서 웹디자이너나 웹퍼블리셔와 협업하기에 좋은 템플릿 엔진입니다.


1. 의존성 추가

먼저 추가할 의존성 정보를 알아야 합니다. Spring Boot 는 Maven 중앙 저장소를 이용하여 프로젝트를 구성하기 때문에 Maven 중앙 저장소에서 Thymeleaf 을 검색해봐야 합니다.

http://mvnrepository.org

위 웹사이트의 검색창에서 Thymeleaf 혹은 Spring Boot Thymeleaf 등의 키워드로 검색을 하면 Spring Boot Thymeleaf Starter 가 검색됩니다.



Spring Boot Thymeleaf Starter 을 선택하여 페이지를 이동하면 사용 가능한 버전 목록이 나타납니다.



Spring Boot 프로젝트를 생성할 때 선택했던 Spring Boot 의 버전과 동일한 버전이 있는지 확인한 뒤(없다면 해당 기능을 더 이상 제공하지 않는 경우일 수 있음) 버전을 선택하여 다음 페이지로 이동합니다.



페이지 중간에 드디어 Maven 에 붙여넣기를 할 수 있는 코드가 보입니다. 위의 책갈피에는 Maven 뿐만 아니라 Gradle 도 존재하므로 Gradle 을 빌드툴로 선택했다면 Gradle 양식으로 볼 수 있습니다.

이 페이지에서 제공하는 의존성 정보는 <version> 을 포함하고 있습니다. 하지만, Spring Boot 프로젝트에서는 <parent> 정보를 통해 <version> 을 일괄적으로 관리하고 있습니다. 그렇기 때문에 제공되는 정보 중 <version> 정보는 제외하고 pom.xml 에 추가하면 됩니다.

그러면 아래와 같이 pom.xml 의 내용이 변경될 것입니다.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

이것으로 기본 설정은 끝이 났습니다(?!).


2. Thymeleaf 로 Hello World 출력하기

Thymeleaf 가 정상적인지 확인하기 위해 src/main/java/com/example/demo/controller/ 디렉토리를 생성한 뒤 HelloController.java 파일을 아래와 같이 만들어 보겠습니다.

package com.example.demo.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class HelloController {

	@RequestMapping("/hello")
	public String hello(HttpServletResponse response) throws IOException {
		return "hello/index"
	}

}

/hello 을 처리하는 hello() 메서드의 return 이 String 형태의 hello/index 임을 주목해 주십시오. return 값을 이용해 view 에서 이용할 파일의 디렉토리와 경로를 찾아갑니다. 위와 같은 경우 src/resources/templages/hello/index.html 의 파일을 이용한다는 의미가 됩니다.

index.html 파일은 아래와 같이 만들어 보겠습니다.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>Hello</title>
</head>
<body>
Hello World : <span th:text="Thymeleaf">HTML</span>
</body>
</html>

위의 코드에서 <html> 내에 Thymeleaf 이용을 위한 XML NameSpace 정의를 추가하였고, <span> 에 Thymeleaf 코드를 추가하였습니다.

index.html 을 웹브라우져를 이용해 열면 아래와 같이 출력됩니다.



하지만, Maven 으로 Packaging 한 뒤 Spring Boot 을 실행한 후, /hello 페이지로 이동하면 아래와 같이 Thymeleaf 에 정의된 내용으로 표시되는 것을 확인할 수 있습니다.


3. 기본 설정 변경하기

spring-boot-starter-thymeleaf 을 추가하여 Thymeleaf 을 빠르게 사용할 수 있게 되었습니다. 어떤 원리에 의해서 이렇게 되는지는 Spring 에서 Auto Configuration 을 진행하는 것을 이해해야 하지만, 환경 설정을 통해서 어떤 설정을 할 수 있고 어떻게 변경할 수 있는지를 알면 Spring Boot 에서 선택할 수 있는 다른 라이브러리들도 이해하기 쉬울 것입니다.

application.properties 살펴보기 에서 application.properties 파일에 들어갈 수 있는 설정 정보를 설명한 Spring Boot 레퍼런스 가이드의 부록을 소개했었습니다. 이 페이지에서 thymeleaf 가 들어간 설정 정보를 확인해보겠습니다.

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0 # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved.

여러가지 설정 정보가 존재하는데, spring.thymeleaf.prefix 와 spring.thymeleaf.suffix 의 기본값이 classpath:/templates/.html 인게 먼저 눈에 들어옵니다. 앞서서 "hello/index" 라고 return 을 했을 때 templates/ 디렉토리의 hello/index.html 을 읽는 이유가 바로 여기에 있습니다. 그 외에도 여러 설정 항목들이 존재하고 있으며, 해당 부록의 윗 부분에 있는 링크(ThymeleafAutoConfiguration 에 링크가 실제로 걸려 있음)를 이용해 소스로 이동해보면 내부 구동 원리도 알 수 있습니다.


4. 기존의 설정 방식을 사용하기

Spring Boot 는 Spring Framework 을 기반으로 하기 때문에 기존의 XML 형태의 설정이나 Java Config 형태의 설정도 여전히 사용 가능합니다.

예를 들어 아래와 같이 @Configuration 애노테이션이 선언된 클래스에 Java Config 을 사용하여 개발자가 원하는 설정을 등록할 수 있습니다.

https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#the-springstandard-dialect

@Bean
public SpringResourceTemplateResolver templateResolver(){
    // SpringResourceTemplateResolver automatically integrates with Spring's own
    // resource resolution infrastructure, which is highly recommended.
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // HTML is the default value, added here for the sake of clarity.
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // Template cache is true by default. Set to false if you want
    // templates to be automatically updated when modified.
    templateResolver.setCacheable(true);
    return templateResolver;
}


반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 31
글 보관함