JAVA Velocity template engine uses instance _jsp programming

Source: Internet
Author: User

Velocity uses version 1.7. Under Win7, use IntelliJ idea to create a web App project based on Tomcat named Todo_web, set Path to/todo, and import velocity-related jar packs. Import only Velocity-1.7.jar This package may be an error, as prompted to import the velocity from the other packages. The project structure is as follows:



Test Tomcat

Index.jsp contents are as follows:

Copy Code code as follows:

<%--Created by the IntelliJ idea. --%>
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
<title></title>
<body>
<%
Out.print ("Hi,todo");
%>
</body>

Helloworld.java contents are as follows:
Copy Code code as follows:

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
/**
*
* @param request
* @param response
* @throws IOException
* @throws servletexception
*/
@Override
public void doget (HttpServletRequest request, httpservletresponse response)
Throws IOException, Servletexception {
Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
Out.println ("Out.println ("Out.println ("<title>Hi!</title>");
Out.println ("Out.println ("<body>");
Out.println ("Out.println ("</body>");
Out.println ("}
}

Add the following in Web.xml:
Copy Code code as follows:

<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>/hi</url-pattern>
</servlet-mapping>

Run the project, and you can see the effect in Http://localhost:8080/todo and Http://localhost:8080/todo/hi.


Using velocity

Below starts using the Velocity template engine, builds the directory templates under SRC, creates the file Test.vm in the Templates directory, and reads as follows:

Copy Code code as follows:

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<body>
#set ($this = "Velocity")
$this is great! <br/>
$name <br/>
Hi, I am Letian
</body>

Create a new Java file in the SRC directory Myvelocity01.java:
Copy Code code as follows:

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);
Velocityengine.mergetemplate ("Templates/test.vm", "utf-8", context, SW); That's going to happen two times.
Out.println (Sw.tostring ());
}
}

Configure Web.xml:

Copy Code code as follows:

<!--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>

Re-deploy, browser access http://localhost:8080/todo/ve can see the effect.

Simply introduce velocity

Velocity is a java-based template engine with three types of file loading templates: 1, loading 2 from a file path, starting with the Classpath (Myvelocity01.java using this method) 3, and loading from the jar file to start contacting Velocity may encounter problems on the load template.

How to pass a variable to a template file: The template itself can define a variable, for example, a variable $this,java code is defined in TEST.VM, and a variable can be passed to a template, such as a variable in TEST.VM $name is a velocitycontext instance that passes past. Velocity also supports iterative objects, such as: We import java.util.Vector in Myvelocity01.java and code:

Copy Code code as follows:

Context.put ("name", "Test");

To
Copy Code code as follows:

Vector v = new vector ();
V.addelement ("Harry");
V.addelement ("John");
String[] names = {"Harry", "John"};
Context.put ("Names1", V);
Context.put ("Names2", names);

Change the TEST.VM content to:
Copy Code code as follows:

#foreach ($name in $names 1)
$name <br/>
#end
#foreach ($name in $names 2)
$name <br/>
#end

Velocity also supports the map container, which enables the introduction of static templates using #include ("") and the introduction of dynamic Templates #parse ("template name").

Using servlet + velocity is a small and flexible option if you don't want to write a Web site with Java MVC.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.