动态生成静态页面技术

最近在项目中要用动态生成技术,以前也没弄过,搜索了一下网络发现了一种方法通俗易懂,于是拿过来总结一下跟大家分享,废话不多说,先来看看代码:

[color=darkred][b]template.htm[/b][/color]

<html>
<head>
<title>###title###</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<LINK href="../css.css" rel=stylesheet type=text/css>
</head>

<body>
<img src="###img###">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="2">
<tr>
<td align="center">###title###</td>
</tr>
<tr>
<td align="center">作者:###author###  </td>
</tr>
<tr>
<td>###content###
</td>

</tr>

</table>
</body>
</html>


[color=darkred][b]BuildHtm.java[/b][/color]

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import org.apache.log4j.Logger;

public class BuildHtm {
private Logger log = Logger.getLogger(this.getClass()); // 日志

/**
* 读取模板内容
* @param filePath 文件路径
* @throws IOException
* */
public String getTemplateContent(String filePath){
FileInputStream fileinputstream;
String templateContent = null;

try {
fileinputstream = new FileInputStream(filePath); //读取模块文件
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
templateContent = new String(bytes);
} catch (IOException e) {
log.debug(e.getMessage());
e.printStackTrace();
}

return templateContent;
}

/**
* 重新生产静态页面
* @param fileName 文件名及路径
* @param templateContent 模板内容
* @throws IOException
* */
public void createFile(String fileName,String templateContent){
FileOutputStream fileoutputstream;

try {
fileoutputstream = new FileOutputStream(fileName); //建立文件输出流
byte tag_bytes[] = templateContent.getBytes();
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
} catch (IOException e) {
log.debug(e.getMessage());
e.printStackTrace();
}

}

/**
* 获取新的Html页面代码
* @throws IOException
* */
public void BuildHtml() throws IOException{
String title="动态生成静态html文件";
String content="小样,还搞不定你?";
String editer="hpsoft";
String filePath = "template.htm";

String templateContent = this.getTemplateContent(filePath);
templateContent=templateContent.replaceAll("###title###",title);
templateContent=templateContent.replaceAll("###content###",content);
templateContent=templateContent.replaceAll("###author###",editer);//替换掉模块中相应的地方
templateContent=templateContent.replaceAll("###img###","1.jpg");//替换掉模块中相应的地方

// 根据时间得文件名
Calendar calendar = Calendar.getInstance();
String fileName = String.valueOf(calendar.getTimeInMillis()) +".html";

createFile(fileName, templateContent);
}

public static void main(String args[]) throws IOException{
(new BuildHtm()).BuildHtml();
}

}
这个方法个人感觉挺好,不知道大家有没有更好的生成技术,不惜赐教!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值