The project structure is as shown in the screenshot:
1, first, the introduction of velocity programming required jar package, build all kinds of files. Under the required JAR package:
2. Configure the Web. xml file
<!--Configuring the velocity's servlet--
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
</servlet >
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern> *.vm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>hello</ servlet-name>
<servlet-class>velocityHandler.HelloHandler</servlet-class>
</ servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
< Url-pattern>/index</url-pattern> <!--for browser access-
</servlet-mapping>
Hellohandler.java specific code is as follows:
public class Hellohandler extends velocityviewservlet{private static final long serialversionuid = 1L;
Private Velocityengine Velo; @Override public void Init () throws servletexception{//velocity Engine Object velo = new Velocit
Yengine ();
Set the load path for the VM template Properties prop = new properties ();
String path = This.getservletcontext (). Getrealpath ("/");
Prop.setproperty (Velocity.file_resource_loader_path, PATH + "templates/");
Set the encoding Prop.setproperty (Velocity.encoding_default, "UTF-8");
Prop.setproperty (velocity.input_encoding, "UTF-8");
Prop.setproperty (velocity.output_encoding, "UTF-8");
try {//Initialize settings, use the GetTemplate ("*.VM") output below to make sure to invoke Velo object to do, namely Velo.gettemplate ("*.VM") velo.init (prop);
} catch (Exception E1) {e1.printstacktrace (); }} @SuppressWarnings ("Unchecked") @Override protected Template handlerequest (httpservletreQuest Request, HttpServletResponse response, Context ctx) {try {request.setcharacterencoding ("UTF-8");
} catch (Unsupportedencodingexception e) {e.printstacktrace ();
} response.setcharacterencoding ("UTF-8");
String p1 = "Lily";
String P2 = "Molly";
String p3 = "Zhang San mad";
@SuppressWarnings ("rawtypes") vector personlist = new vector ();
Personlist.addelement (p1);
Personlist.addelement (p2);
Personlist.addelement (p3); Ctx.put ("Personlist", personlist);
The template data list is placed in the contextual context template template = Velo.gettemplate ("INDEX.VM");
return template; }
}INDEX.VM file
3, enter the address Http://localhost/velocity/index in the browser, you can see the following effect
Note: VM files can not be accessed directly, that is, enter the address directly in the browser HTTP://LOCALHOST/VELOCITY/TEMPLATES/INDEX.VM will not see the effect, the VM files need to go through a mechanism to be parsed, such as struts2,spring and so on.