Velocity与Struts 1.* -- 静态页生成

本文介绍如何在Struts1.*版本中利用Velocity模板生成静态页面的完整流程,包括获取VelocityContext、加载模板、填充数据、生成字符串、创建文件等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Struts中有两种使用Velocity的方法,一种是利用Velocity的vm模板进行页面展示,一种则是利用Velocity来生成静态页面。以下介绍在Struts 1.*版本中使用Velocity模板生成静态页面的过程。

思路是访问一个Action,在Action中进行静态页面的生成,最终该Action跳转到生成好的静态页面中。

步骤为:
1. 获取VelocityContext,该对象中包含了需要展示的数据
2. 获取指定路径下的vm模板内容
3. 根据Velocity模板,生成字符串
4. 根据指定路径及文件名创建文件
5. 将转换好的模板文件写入指定文件中

源码如下:
Velocity模板
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>StrutsSample_1</title>
</head>
<body>
<h3>StrutsSample</h3>
<table width="400" border="1">
#foreach($name in $list)
<tr> <td>$name</td> </tr>
#end
</table>
</body>
</html>


public class CreateHtmlPage extends DispatchAction {
public ActionForward createStaticPage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
ActionForward forward = new ActionForward();
ActionMessages errors = new ActionMessages();
String webServer_dir = "D:/Tomcat6/webapps/Mixele_Velocity";

String filepath = webServer_dir + "/success.htm"; //需要生成的静态页
String vmpath = webServer_dir + "/templates/namelist.vm"; //Velocity模板

VelocityContext context = getContext();
String templatebody = getTemplateBody(vmpath);
String str = createHtmlStrByVelocity(context, templatebody);
File htmlfile = createFile(filepath);
writerTxtFile(htmlfile, str);

if (!errors.isEmpty()) {
saveErrors(request, errors);
forward = new ActionForward(mapping.getInput());
} else {
forward = new ActionForward("/success.htm");
}
return forward;
}

/** 获取VelocityContext对象,并向其中注入模板需要展现的数据 */
public VelocityContext getContext() {
/* 这里需要注意,因为在web.xml中配置了VelocityViewServlet
* 所以这里Velocity会在系统启动时初始化
* 如果没有配置,需要先在这里进行Velocity的初始化工作 */
VelocityContext context = new VelocityContext();
List<String> list = new ArrayList<String>();
String name = null;
for(int i=0;i<20;i++){
name = "Hoffman YoYo "+i+" Name";
list.add(name);
}
context.put("list", list);
return context;
}

/** 通过指定路径获取vm模板并提取模板内容 */
public String getTemplateBody(String vmpath) {
File file = new File(vmpath);
BufferedReader reader = null;
StringBuffer strbf = new StringBuffer("");
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
strbf.append(tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return strbf.toString();
}

/** 根据Velocity模板,生成字符串 */
public String createHtmlStrByVelocity(VelocityContext context, String vmbody) {
StringWriter writer = new StringWriter();
try {
Velocity.evaluate(context, writer, "myString", vmbody);
} catch (ParseErrorException e) {
e.printStackTrace();
} catch (MethodInvocationException e) {
e.printStackTrace();
} catch (ResourceNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return writer.toString();
}

/** 在指定路径中创建由Velocity解析出的html文件
* 当文件存在时,删除该文件,重新创建 */
public File createFile(String filepath) {
File file = new File(filepath);
if(file.exists() && file.isFile()) {
boolean delFileSuccess = file.delete(); //文件存在删除之
if(!delFileSuccess) {
System.out.println("删除文件" + filepath + "失败!");
}
try {
boolean cresteFileSuccess = file.createNewFile();
if (!cresteFileSuccess) {
System.out.println("创建文件" + filepath + "失败!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}

/** 写文本文件 */
public void writerTxtFile(File filepath, String str) {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(filepath), 1024));
} catch (IOException e) {
e.printStackTrace();
}
out.println(str);
out.flush();
out.close();
}
}

通过以上的代码,即可将赋予VelocityContext中的数据与VM模板组合,生成静态页面。
以上代码很多地方都是硬编码,其实在实际工程中,静态化的步骤不会发生太大变化,只是模板与生成页面的路径会有更复杂的获取过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值