查看文章
JSP生成静态HTML页面的几种方法2007-07-26 21:17一、从数据库中取相应数据并替换掉模板中的对应标签,下面是一个简单的示例
1.buildhtml.jsp
<%@ page contentType="text/html; charset=gb2312" import="java.util.*,java.io.*"%>
<%
try{
String title="This is Title";
String content="This is Content Area";
String editer="LaoMao";
String filePath = "";
filePath = request.getRealPath("/")+"test/template.htm";
//out.print(filePath+"<br>");
String templateContent="";
FileInputStream fileinputstream = new FileInputStream(filePath);//读取模块文件
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
templateContent = new String(bytes);
//out.print(templateContent);
templateContent=templateContent.replaceAll("###title###",title);
templateContent=templateContent.replaceAll("###content###",content);
templateContent=templateContent.replaceAll("###author###",editer);//替换掉模块中相应的地方
//out.print(templateContent);
// 根据时间得文件名
Calendar calendar = Calendar.getInstance();
String fileame = String.valueOf(calendar.getTimeInMillis()) +".html";
fileame = request.getRealPath("/")+fileame;//生成的html文件保存路径
FileOutputStream fileoutputstream = new FileOutputStream(fileame);//建立文件输出流
byte tag_bytes[] = templateContent.getBytes();
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
}
catch(Exception e){
out.print(e.toString());
}
%>
2. template.htm
<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>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="2">
<tr>
<td align="center">###title###</td>
</tr>
<tr>
<td align="center">author:###author### </td>
</tr>
<tr>
<td>###content###</td>
</tr>
</table>
</body>
</html>
=======================================================
二、从动态页的URL获取相应页面内容并写入到文件
/*
* Created on 2006-3-4
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.easydone.cn.tools.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
/**
* @author Administrator
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class MakeHtml {
private static long star = 0;
private static long end = 0;
private static long ttime = 0;
//返回html代码
public static String getHtmlCode(String httpUrl){
Date before = new Date();
star = before.getTime();
String htmlCode = "";
try {
InputStream in;
URL url = new java.net.URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent","Mozilla/4.0");
connection.connect();
in = connection.getInputStream();
java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in , "GBK"));
String currentLine;
while((currentLine=breader.readLine())!=null){
htmlCode+=currentLine;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
Date after = new Date();
end = after.getTime();
ttime = end-star ;
System.out.println("执行时间:"+ttime +"秒");
}
return htmlCode;
}
//存储文件
public static synchronized void writeHtml(String filePath,String info,String flag) {
PrintWriter pw = null;
try {
File writeFile = new File(filePath);
boolean isExit = writeFile.exists();
if (isExit != true) {
writeFile.createNewFile();
} else {
if (!flag.equals("NO")) {
writeFile.delete();
writeFile.createNewFile();
}
}
pw = new PrintWriter(new FileOutputStream(filePath, true));
pw.println(info);
pw.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}finally{
pw.close();
}
}
public static void main(String[] args) {
String url = "http://www.easydone.cn/index.htm";
writeHtml("c:/demo.htm",getHtmlCode(url),"NO");
}
}
三、利用Filter和定制Response,把服务器返回的JSP响应输出到我们自己的Response中,就可以将响应快速写入Html文件,然后再发送给客户。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Calendar;
public class CacheFilter implements Filter {
ServletContext sc;
FilterConfig fc;
long cacheTimeout = Long.MAX_VALUE;
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request =
(HttpServletRequest) req;
HttpServletResponse response =
(HttpServletResponse) res;
// check if was a resource that shouldn't be cached.
String r = sc.getRealPath("");
String path =
fc.getInitParameter(request.getRequestURI());
if (path!= null && path.equals("nocache")) {
chain.doFilter(request, response);
return;
}
path = r+path;
String id = request.getRequestURI() +
request.getQueryString();
File tempDir = (File)sc.getAttribute(
"javax.servlet.context.tempdir");
// get possible cache
String temp = tempDir.getAbsolutePath();
File file = new File(temp+id);
// get current resource
if (path == null) {
path = sc.getRealPath(request.getRequestURI());
}
File current = new File(path);
try {
long now =
Calendar.getInstance().getTimeInMillis();
//set timestamp check
if (!file.exists() || (file.exists() &&
current.lastModified() > file.lastModified()) ||
cacheTimeout < now - file.lastModified()) {
String name = file.getAbsolutePath();
name =
name.substring(0,name.lastIndexOf("/"));
new File(name).mkdirs();
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
CacheResponseWrapper wrappedResponse =
new CacheResponseWrapper(response, baos);
chain.doFilter(req, wrappedResponse);
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
}
} catch (ServletException e) {
if (!file.exists()) {
throw new ServletException(e);
}
}
catch (IOException e) {
if (!file.exists()) {
throw e;
}
}
FileInputStream fis = new FileInputStream(file);
String mt = sc.getMimeType(request.getRequestURI());
response.setContentType(mt);
ServletOutputStream sos = res.getOutputStream();
for (int i = fis.read(); i!= -1; i = fis.read()) {
sos.write((byte)i);
}
}
public void init(FilterConfig filterConfig) {
this.fc = fi