velocity入门(二)

代码下载地址:http://download.csdn.net/detail/jxlgzwh/6025487

项目结构:


velocity入门(二)_第1张图片

add.vm 源码:

<html>
<head> <title>Velocity Example</title></head>
<body>
<h1>Velocity Example</h1>
<p>$a+$b=$c</p>
</body>
</html>
AddServlet.java 源码:
package mypack;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.velocity.*;
import org.apache.velocity.context.*;
import org.apache.velocity.servlet.*;
import org.apache.velocity.app.*;
import org.apache.velocity.exception.*;

public class AddServlet extends VelocityServlet {

	protected Properties loadConfiguration(ServletConfig config)
			throws IOException, FileNotFoundException {

		Properties p = new Properties();
		String path = config.getServletContext().getRealPath("/");
		if (path == null) {
			System.out.println("VelocityAdd.loadConfiguration():"
					+ "unable to get the current webapp root. Using '/'. ");
			path = "/";
		}
		p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
		p.setProperty("runtime.log", path + "velocity.log");
		System.out.println("path=" + path);
		return p;
	}

	public Template handleRequest(HttpServletRequest request,
			HttpServletResponse response, Context context) {
		Template outty = null;
		try {
			int a = 11;
			int b = 22;
			int c = a + b;
			context.put("a", new Integer(a));
			context.put("b", new Integer(b));
			context.put("c", new Integer(c));

			outty = getTemplate("add.vm");
		} catch (ParseErrorException ex1) {
			System.out.println("VelocityAdd: parse error for template " + ex1);
		} catch (ResourceNotFoundException ex2) {
			System.out.println("VelocityAdd: template not found " + ex2);
		} catch (Exception ex3) {
			System.out.println("VelocityAdd: error " + ex3);
		}
		return outty;
	}

}
web.xml配置如下:
<servlet>
    <servlet-name>add</servlet-name>
    <servlet-class>mypack.AddServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>add</servlet-name>
    <url-pattern>/add</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>properties</servlet-name>
    <servlet-class>mypack.PropertiesServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>properties</servlet-name>
    <url-pattern>/properties</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>properties_1</servlet-name>
    <servlet-class>mypack.PropertiesServlet_1</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>properties_1</servlet-name>
    <url-pattern>/properties_1</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>loop</servlet-name>
    <servlet-class>mypack.LoopServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>loop</servlet-name>
    <url-pattern>/loop</url-pattern>
  </servlet-mapping>
浏览器输入:http://localhost:8080/helloapp/add

显示结果为:

velocity入门(二)_第2张图片


你可能感兴趣的:(velocity入门(二))