티스토리 뷰

개요

  • FreeMarker는 오랜 역사를 자랑하는 Java 템플릿 엔진이다. ThymeleafJtwig와 같은 보다 간결하고 진보된 경쟁자가 존재하지만 FreeMarker 만의 오랜 역사와 경험으로 현실에서 프로젝트를 수행 중에 부딪히는 많은 문제를 해결할 수 있어 1순위로 추천한다.
  • FreeMarkerSpring Boot를 기본 지원하여 매우 편리하게 사용할 수 있다. 본 글에서는 Spring Boot 기반 프로젝트에서 일반 로직에서의 템플릿으로 사용하는 방법, 컨트롤러의 뷰로서 사용하는 방법 2가지를 소개하고자 한다.

라이브러리 종속성 추가

  • 프로젝트 루트의 /build.gradle 파일에 아래 내용을 추가한다.
dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-freemarker'
}

템플릿 작성

  • 프로젝트 루트의 /src/main/resources 경로에 templates 디렉토리를 생성하고 template.ftlh라는 파일을 아래와 같이 작성한다.
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="utf-8">
    <title>${title}</title>
</head>
<body>
<h1>${body}</h1>
</body>
</html>
  • FreeMarker는 확장자에 따라 자동으로 이스케이프 처리 여부를 결정한다. .ftlh 확장자는 HTML 이스케이프 자동 처리를, .ftlx 확장자는 XML 이스케이프 자동 처리를 수행한다.
  • 결과를 확인하기 전에 템플릿의 문법 오류를 체크하거나 임의의 데이터 모델을 테스트하고자 한다면 FreeMarker Online Tester를 추천한다.

템플릿 처리 로직 작성: Vanilla Java

  • 이제 템플릿 처리 로직을 작성할 차례이다. 일반 Java에서의 템플릿 처리 로직은 아래와 같이 작성한다.
// Configuration 인스턴스 작성, 싱글턴 객체로 사용할 것
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
configuration.setDefaultEncoding("UTF-8");

// 템플릿에 주입할 데이터를 담는 데이터 모델 작성
Map<String, Object> dataModel = new HashMap();
dataModel.put("title", "Hello");
dataModel.put("body", "World!");

// 템플릿에 데이터 주입
try {
    Template template = configuration.getTemplate("template.ftlh");
    StringWriter templateStringWriter = new StringWriter();
    template.process(dataModel, templateStringWriter);
    String result = templateStringWriter.toString();
} catch (IOException | TemplateException ex) {
    throw new Runtimeexception(ex);
}
  • freemarker.template.Configuration 인스턴스는 Freemarker의 사용을 위한 시작점이 되는 인스턴스이다. 전반적인 환경 설정과 캐시 처리를 담당하는데 무거운 인스턴스이므로 반드시 싱글턴 객체로 취급하여 재사용해야 한다.
  • 다음으로 템플릿에 주입할 데이터를 담을 데이터 모델을 작성한다. Map<String, Object>, POJO 인스턴스 모두 사용이 가능하다.
  • 마지막으로 템플릿에 데이터를 주입하면 완성된 결과를 획득할 수 있다.
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="utf-8">
    <title>Hello</title>
</head>
<body>
<h1>World!</h1>
</body>
</html>

템플릿 처리 로직 작성: Spring Boot, Web MVC

  • 이제 Spring Boot에서의 템플릿 처리 로직을 작성할 차례이다. 아래 내용만 /src/main/resources/application.yml 파일에 추가하면 FreeMarker를 이용할 모든 준비가 끝난다.
spring:
    freemarker:
        template-loader-path: classpath:/templates
        suffix: .ftlh

참고 글

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함