본문 바로가기
Programming/Java

Velocity 를 이용한 템플릿 작성

by d-e-v-j 2024. 8. 19.
반응형

사내 이메일이라던지 Noti 메일에 대한 템플릿을 작성하여

그 요소값만 넣어주고 메일을 발송하는 시스템을 많이 개발해왔었다.

개발을 하면서 그냥 DB에 템플릿을 넣어주는구나만 알고 있었는데

이걸 Velocity code 라고 부르는걸 이제서야 깨닫고 좀 더 알아보려 한다.

 


1.Velocity 란?

Apache Velocity 는 텍스트 기반의 템플릿 엔진으로, 웹 페이지 템플릿, 이메일 템플릿, 코드 생성 등 다양한 용도로 활용할 수 있다. Velocity는 주로 Java 애플리케이션과 통합되어 동적인 콘텐츠를 쉽게 생성할 수 있다.

 

Velocity의 특징

  • 간결한 문법 : '$', '#' 기호를 사용하여 변수를 참조하고, 조건문, 반복문 등의 구조를 표현할 수 있다.
  • Java와의 통합용이성 : Java 객체의 속성이나 메서드를 템플릿 내에서 쉽게 호출
  • 유연한 텍스트 생성 : 다양한 텍스트 기반의 콘텐츠를 쉽게 생성할 수 있다.

 

2.Velocity 사용법

지시어(Directives)

다양한 지시어로 템플릿을 제어할 수 있다. 주요 지시어로는 #if, #foreach, #include, #macro 등이 있다.

조건문

#if($user.isPremium)
    Thank you for being a premium member!
#else
    Upgrade to premium for more benefits.
#end

 

반복문

#foreach($item in $items)
    - $item
#end

 

포함

#include("header.vm")

 

매크로

#macro(greeting $name)
    Hello, $name!
#end

#greeting("John")

 

 

3.Velocity를 사용한 이메일 템플릿

템플릿 파일 작성

Hello $user.name,

We are excited to inform you that your order #$order.id has been shipped!

#foreach($item in $order.items)
    - $item.name: $item.price
#end

Total: $order.total

Thank you for shopping with us!

Best regards,
The Team

 

 

Java 에서 velocity 통합

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.util.Properties;

public class EmailTemplateExample {
    public static void main(String[] args) {
        // Velocity 엔진 설정
        Properties props = new Properties();
        props.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        VelocityEngine ve = new VelocityEngine(props);

        // 컨텍스트 설정
        VelocityContext context = new VelocityContext();
        context.put("user", new User("John Doe"));
        context.put("order", new Order("123456", items));

        // 템플릿 가져오기
        StringWriter writer = new StringWriter();
        ve.mergeTemplate("emailTemplate.vm", "UTF-8", context, writer);

        // 결과 출력
        System.out.println(writer.toString());
    }
}

Velocity 의 간단한 문법과 방법으로 다양한 기능을 사용하고, 복잡한 구문도 쉽체 처리가 가능하다.

이러한 내용들이 Util 파일에 숨어 있는 경우도 있고, 다른 형식(Java mail sender 등)으로 mail을 사용하기도 한다.

그래도 알아두면 좋고 더 간단하게 구문을 만드는 방법도 있으니 필요하면 찾아보면 좋겠다.


 

 

 

 

728x90
반응형
LIST

'Programming > Java' 카테고리의 다른 글

JAVA 중복 처리 방지 방법  (1) 2024.08.23
Java 메일 Library 들  (0) 2024.08.21
JAVA 비동기처리 CompletableFuture  (0) 2024.08.05
원시 타입(Primitive type)과 래퍼 클래스(Wrapper class)  (29) 2024.07.31
TCP 소켓 통신  (0) 2024.07.30