/*
* Copyright 2000-2001,2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Servlet直接继承VelocityServlet。需要引入velocity-dep-1.4.jar,velocity-1.4.jar两个包。
package com.javayou;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
/**
* Sample of how to use the VelocityServlet.
* This example shows how to add objects to the context and
* pass them to the template.
*
* @author willians He
* @author <a href="mailto:hzxmsn@163.com">willians He.</a>
* @version $Id: SampleServlet.java,v 1.5.8.1 2006/07/15 10:01:29 geirm Exp $
*/
public class SampleServlet extends VelocityServlet
{
/**
* Called by the VelocityServlet
* init(). We want to set a set of properties
* so that templates will be found in the webapp
* root. This makes this easier to work with as
* an example, so a new user doesn't have to worry
* about config issues when first figuring things
* out
*/
protected Properties loadConfiguration(ServletConfig config )
throws IOException, FileNotFoundException
{
Properties p = new Properties();
/*
* first, we set the template path for the
* FileResourceLoader to the root of the
* webapp. This probably won't work under
* in a WAR under WebLogic, but should
* under tomcat :)
*/
String path = config.getServletContext().getRealPath("/");
if (path == null)
{
System.out.println(" SampleServlet.loadConfiguration() : unable to "
+ "get the current webapp root. Using '/'. Please fix.");
path = "/";
}
p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH, path );
/**
* and the same for the log file
*/
p.setProperty( "runtime.log", path + "velocity.log" );
return p;
}
/**
* <p>
* main routine to handle a request. Called by
* VelocityServlet, your responsibility as programmer
* is to simply return a valid Template
* </p>
*
* @param ctx a Velocity Context object to be filled with
* data. Will be used for rendering this
* template
* @return Template to be used for request
*/
public Template handleRequest( HttpServletRequest request,
HttpServletResponse response, Context ctx )
{
/*
* set up some data to put into the context
*/
String p1 = "Bob-->congratulation to Bob";
String p2 = "Harold-->congratulation to Harold";
String p3 = "Bob--->this is Wrong enter Bob";
String p4 = "Harold-->this is Wrong enter Harold";
String jpgurl2="/test/picture/lxy01.jpg";
String jpgurl1="/test/picture/ch020.jpg";
// 为后面的展示,提前输入List数值
List temp = new ArrayList();
temp.add(new Students("123", "Guangzhou"));
temp.add(new Students("321", "Guangzhou"));
temp.add(new Students("456", "Shanghai"));
temp.add(new Students("654", "Shanghai"));
ctx.put("list", temp);
Vector personList = new Vector();
Vector personList2 = new Vector();
String name=null;
String pass=null;
if(!request.getParameterMap().isEmpty())
{
name = request.getParameter("Account");
pass = request.getParameter("Password");
}else {
name="myname";
pass="123456";
}
if(name.equals("myname")&&pass.equals("123456")) {
personList.addElement( p1 );
personList.addElement( p2 );
personList2.addElement( jpgurl1 );
}
else{
personList.addElement( p3 );
personList.addElement( p4 );
personList2.addElement( jpgurl2 );
}
/*
* Add the list to the context.
* This is how it's passed to the template.
*/
ctx.put("theList", personList );
ctx.put("theImageList", personList2 );
/*
* get the template. There are three possible
* exceptions. Good to know what happened.
*/
Template outty = null;
try
{
//outty = getTemplate("sample.html");
outty=getTemplate("templat/picMoudle/pic1.html");
}
catch( ParseErrorException pee )
{
System.out.println("SampleServlet : parse error for template " + pee);
}
catch( ResourceNotFoundException rnfe )
{
System.out.println("SampleServlet : template not found " + rnfe);
}
catch( Exception e )
{
System.out.println("Error " + e);
}
return outty;
}
}
Students.java
/*
* 创建日期 2006-7-18
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
package com.javayou;
/**
* @author Willian He
*
*/
public class Students {
public String no = "";
public String address = "";
public Students(String _no, String _address) {
no = _no;
address = _address;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
}
模板
pic1.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample Picture page</title></head>
<body bgcolor="#ffffff">
<center>
<h2>Hello ,How are you!</h2>
<i>Here's the list of picture</i>
#set ($foo="The Velocity")
<table width="750" height="200" border="1" cellpadding="1" cellspacing="1">
<tr>
<td bgcolor="#eeeeee" align="center">
Show the picture <br>
##foreach ($s1 in $list)
#foreach ($s in $list)
#if($s.address=="Shanghai")
this is<$velocityCount> Address: $s.address $s.no<br>
#else
that is<$velocityCount> Address: $s.no,$s.address <br>
#end
#end
##end
</td>
</tr>
#foreach ($name in $theList)
<tr align="center">
<td bgcolor="#eeeeee">$name</td>
</tr>
#end
#foreach ($name in $theImageList)
<tr>
<td align="center"><img src="$name" title="give me" /></td>
</tr>
<tr>
<td align="center"><font color="#ff0255">$name</font></td>
</tr>
#end
<tr>
<td bgcolor="#green" align="center">$foo</td>
</tr>
</table>
#macro(tablerows $color $somelist)
#foreach($something in $somelist)
<tr>
<td bgcolor=$color>$something</td>
</tr>
#end
#end
#set($greatlakes=["Superior","Michigan","Huron","Erie","Ontario"])
#set($color=("bllack"))
<table>
#tablerows($color $greatlakes)
</table>
<a href="http://localhost:8080/test/MyJsp.jsp">回上一页</a>
</center>
</html>