JAVA velocityテンプレートエンジンのインスタンス

1.test.vm
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8″>
</head>
<body>
#set( $this = “Velocity")
$this is great! <br/>
$name <br/>
hi , i am letian
<h1>こんにちは</h1>
</body>
</html>

2.MyVelocity01.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
import java.util.Properties;
public class MyVelocity01 extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
request.setCharacterEncoding(“UTF-8");
response.setContentType(“text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Properties properties=new Properties();
properties.setProperty(“resource.loader", “class");
properties.setProperty(“class.resource.loader.class", “org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//properties.setProperty(“input.encoding", “UTF-8");
//properties.setProperty(“output.encoding", “UTF-8");
properties.setProperty(Velocity.ENCODING_DEFAULT, “UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, “UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, “UTF-8");
VelocityEngine velocityEngine = new VelocityEngine(properties);
VelocityContext context=new VelocityContext();
context.put(“name", “test");
StringWriter sw = new StringWriter();
velocityEngine.mergeTemplate(“templates/test.vm", “utf-8", context, sw);
out.println(sw.toString());
}
}

3.web.xmlを編集
<!–MyVelocity–>
<servlet>
<servlet-name>ve</servlet-name>
<servlet-class>MyVelocity01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ve</servlet-name>
<url-pattern>/ve</url-pattern>
</servlet-mapping>

Source

Posted by arkgame