从JSP,ASP等动态页面生成静态页面的实现方式
在网站应用中,为了提高页面的访问速度,经常需要将动态页面静态化以提高页面的访问速度,因为动态页面一般要从数据库检索信息,频繁访问动态页面会大大提高数据库的负载,并且访问速度也比静态页面慢.本文通过在程序里建立一个http请求,将返回的输出流存储为html文件的方式来生成静态页面.在CMS类的应用中,信息发布完可直接调用这段代码,给定一个动态连接地址如http://localhost:8080/cms/info.jsp?infoid=001,生成一个静态页面,代码如下:
package org.apache.easframework.common;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* 将信息发布为静态页面
* @author bzwang
*
*/
public class DynInfo2Html
{
/**
* 将信息转化为静态html
* @param sSourceUrl 动态信息访问URL
* @param sDestDir 存储为静态文件的目录
* @param sHtmlFile 生成的静态文件名,可以按信息的唯一ID+.html命名
* @throws IOException
*/
public static void convert2Html(String sSourceUrl,String sDestDir,String sHtmlFile) throws IOException
{
int HttpResult;
URL url=new URL(sSourceUrl);
URLConnection urlconn=url.openConnection();
urlconn.connect();
HttpURLConnection httpconn=(HttpURLConnection)urlconn;
HttpResult=httpconn.getResponseCode();
if(HttpResult!=HttpURLConnection.HTTP_OK)
{
}
else
{
InputStreamReader isr =
new InputStreamReader(httpconn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
if(!sDestDir.endsWith(“/”))sDestDir+=”/”;
FileOutputStream fout = new FileOutputStream(sDestDir+sHtmlFile);
while ((inputLine = in.readLine()) != null)
{
fout.write(inputLine.getBytes());
}
in.close();
fout.close();
}
}
public static void main(String[] args) throws IOException
{
convert2Html(“http://localhost:9080/system/show.jsp?infoid=b3cd5cf4082a4bbebe70e332cb43fcb2″,”D:/projects/myproject/Src/b2c_front/Jsp/module/bzhzx/html”,”aaaa.html“);
}
}