First, two necessary jar packages are required:
Velocity. Jar velocity-tool-view.jar
Web. xml
<!-- load velocity property --> <servlet> <servlet-name>velocity</servlet-name> <servlet-class>org.apache.velocity.tools.view.servlet.VelocityLayoutServlet</servlet-class> <init-param> <param-name>org.apache.velocity.properties</param-name> <param-value>/WEB-INF/velocity.properties</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>velocity</servlet-name> <url-pattern>*.vm</url-pattern> </servlet-mapping>
velocity.properties
input.encoding=utf-8output.encoding=utf-8WebRoot.resource.loader.class = org.apache.velocity.tools.view.servlet.WebappLoaderwebapp.resource.loader.path=/WEB-INF/vm/
Background call:
String realpath = request. getrealpath ("/"); // template path string urlvm = "/WEB-INF/Vm/test. VM "; // The generated HTML path. In the webroot HTML folder, string urlhtml = realpath +"/html/test.htm "; // set the template element velocitycontext context = new velocitycontext (); context. put ("title", "Hello word"); createhtml. createhtml (realpath, urlvm, urlhtml, context );
CreateHtml.java
Package COM. velocity; import Java. io. printwriter; import Java. util. properties; import Org. apache. velocity. template; import Org. apache. velocity. velocitycontext; import Org. apache. velocity. app. velocity; public class createhtml {public static void createhtml (string realpath, string urlvm, string urlhtml, velocitycontext context) {// load path properties prop = new properties (); prop. setproperty (velocity. file_resource_loader_path, realpath); try {velocity. init (PROP); // initialize VM template = new template (); template = velocity. gettemplate (urlvm, "UTF-8"); // generate the HTML page printwriter writer = new printwriter (urlhtml); template. merge (context, writer); // remember to disable stream writer. close ();} catch (exception e) {// todo auto-generated Catch Block E. printstacktrace ();}}}
In this way, a static page is generated under the server, and the page is directly accessed, for example, http: // localhost: 8080/html/test.htm
Velocity generates static page code