[JAVA] Using templates on the classpath with Apache Velocity

https://stackoverflow.com/questions/2931516/loading-velocity-template-inside-a-jar-file

build.gradle


dependencies {
    implementation 'org.apache.velocity:velocity:1.7'
}

/src/main/resources/templates/hoge.vm


key = $key
import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class Main {

  public static void main(String[] args) {
    Properties p = new Properties();
    p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    Velocity.init(p);

    Context context = new VelocityContext();
    context.put("key", "value0001");

    Template template = new Template();
    template = Velocity.getTemplate("templates/hoge.vm", "UTF-8");

    try (StringWriter body = new StringWriter();) {
      template.merge(context, body);
      body.flush();
      System.out.println(body.toString());;
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Recommended Posts

Using templates on the classpath with Apache Velocity
Programming with ruby (on the way)
FileUpload with Rest on Apache Wicket
Check the operation using jetty with Maven.
Try using the service on Android Oreo
Using JupyterLab + Java with WSL on Windows 10
Notes on using FCM with Ruby on Rails
Try using the Wii remote with Java
A quick note on using jshell with the official Docker image of the JDK
ValidationMessages.properties should not be multiple on the classpath
Using JUnit from the command line on Ubuntu
Come out with a suffix on the method
Publish the app made with ruby on rails
Specify ClassPath when using jupyter + Java with WSL
Tips for using the Spotify app on Ubuntu
Come out with a suffix on the method 2
Matches annotations on the interface with Spring AOP
Until you run the Apache Velocity sample code
Determine the current page with Ruby on Rails
Run the Android emulator on Docker using Android Emulator Container Scripts
Display the list in setDetails on the screen with spring-security
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Challenge the settings for developing with vue.js on Rails 6
[Docker] Build an Apache container on EC2 using dockerfile
Try using the query attribute of Ruby on Rails