VelocityServlet:
vm模板:
web.xml配置:
运行结果:
Velcity Excemple
11 + 22 = 33
package org.liufei.velocity;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;
@SuppressWarnings("deprecation")
public class AddServletVelocity extends VelocityServlet {
private static final long serialVersionUID = -5343161778899944087L;
@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) throws Exception {
Template template = null ;
try{
int a = 11 ;
int b = 22 ;
int c = a + b ;
ctx.put("a", new Integer(a)) ;
ctx.put("b", new Integer(b)) ;
ctx.put("c", new Integer(c)) ;
template = getTemplate("add.vm") ;
}catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
return template;
}
@Override
protected Properties loadConfiguration(ServletConfig servletConfig) throws IOException, FileNotFoundException {
Properties properties = new Properties() ;
String path = servletConfig.getServletContext().getRealPath("/") ;
if(path == null){
System.out.println("Error !");
path = "/" ;
}
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path) ;
properties.setProperty("runtime.log", path + "velocity.log") ;
properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
return properties ;
}
}
vm模板:
<html>
<head>
<title>Velocity Test</title>
</head>
<body>
<h1>Velcity Excemple</h1>
<p>$a + $b = $c</p>
</body>
</html>
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>org.liufei.velocity.AddServletVelocity</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
</web-app>
运行结果:
Velcity Excemple
11 + 22 = 33