pom.xml へ Velocity 設定追加
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml へリソースディレクトリ定義追加
<resources mapping="/html/**" location="/html/" />
src/main/webapp/WEB-INF/spring/root-context.xml へ velocityEngine 定義追加
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/velocity" />
<property name="velocityPropertiesMap">
<map>
<entry key="input.encoding" value="UTF-8" />
<entry key="output.encoding" value="UTF-8" />
</map>
</property>
</bean>
Velocityテンプレートファイル
/WEB-INF/velocity/sample.vm
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルタイトル</title>
</head>
<body>
<ul id="data">
#foreach ($data in $datalist.entrySet())
<li>
$data.key
$data.value
</li>
#end
</ul>
</body>
</html>
コントローラ
jp.s6131.sample.controller.HomeController.java
http://localhost:8080/sample アクセス後、
@Autowired
VelocityEngine velocityEngine;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(HttpServletRequest req, Locale locale, Model model) {
・・・
Map<String, Object> param = new HashMap<String, Object>();
Map<String, String> data = new HashMap<String, String>();
for (int i = 0; i < 10; i++) {
data.put(String.format("%05d", i), String.format("名称%02d", i));
}
param.put("datalist", data);
try {
String outputFile = req.getSession().getServletContext().getRealPath("/html/sample.html");
logger.debug("output html = " + outputFile);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outputFile), "utf-8");
VelocityEngineUtils.mergeTemplate(velocityEngine, "sample.vm", param, osw);
osw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
http://localhost:8080/sample/html/sample.html にアクセスし、作成済 HTML を確認。

人気ブログランキングへ