[java] Apache Velocity 자료 바인딩 방법

Apache Velocity는 템플릿 기반의 뷰를 사용하여 동적 콘텐츠를 생성하는 데 사용되는 강력한 템플릿 엔진입니다. Velocity를 사용하여 자원을 바인딩하고 동적으로 뷰를 생성하는 방법에 대해 알아보겠습니다.

Velocity 변수 바인딩

Velocity에서는 $ 기호를 사용하여 변수를 참조합니다. 다음은 기본적인 변수 바인딩 예제입니다.

String name = "John Doe";
VelocityContext context = new VelocityContext();
context.put("username", name);

위 예제에서는 VelocityContext를 사용하여 변수 “username”에 “John Doe”라는 값을 바인딩하고 있습니다.

객체 바인딩

Velocity에서는 Java 객체를 바로 바인딩할 수 있습니다.

User user = new User("John", "Doe");
VelocityContext context = new VelocityContext();
context.put("user", user);

위 예제에서는 User 객체를 “user” 변수에 바인딩하고 있습니다.

메소드 바인딩

객체의 메소드도 Velocity 템플릿에서 호출할 수 있습니다.

public String getCurrentDate() {
    return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}

VelocityContext context = new VelocityContext();
context.put("utils", new DateUtils());

위 예제에서는 getCurrentDate 메소드를 바인딩한 후 Velocity 템플릿에서 utils.getCurrentDate()로 호출할 수 있습니다.

Velocity 자료 바인딩에 대한 간단한 예제를 살펴보았습니다. 이러한 바인딩 기능을 사용하여 동적인 콘텐츠를 생성하고 더욱 유연한 뷰 레이아웃을 구성할 수 있습니다.

참조

Apache Velocity 공식 문서

이제 Apache Velocity의 자료 바인딩에 대해 알아보았습니다. Velocity를 사용하여 다양한 자원을 바인딩하고 동적 컨텐츠를 생성하는 데 활용할 수 있을 것입니다.