欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp页面的静态化

程序员文章站 2022-05-14 22:21:23
...
前些天接手了公司一个网站的维护和优化,考虑到有的动态页面中有太多的数据库操作,所以要将其进行静态化,这也是网站优化升级的一个必经的步骤。
由于是菜鸟刚刚上阵,起初觉得无从下手,于是在ITeye发了一篇求助,通过一些老鸟的帮助再加上我自己的思考,从而确定了解决思路,并且最终成功搞定。下面说一下方案和步骤:

1:封装一个httpclient,并每隔一段时间向服务器发一次请求(当然请求的是需要静态化的动态页面)
2:以流的形式获取响应报文,并将其写到本地文件且命名为"***.html"
3:配置过滤器,将对该动态页面(***.jsp)的请求转发到转化后的静态页面(***.html)

方案确定了,然后是查对应的技术有哪些,这里面主要有两点,一个是httpclient,一个是定时器。
通过各种搜索,我确定了用Apache的httpclient,然后定时器用quartz。然后去官网查看两者的用法,一步步搞定,下面我贴出一部分代码

Httpclient:
import java.io.File;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class MyHttpClient {

private static String urlString = "http://www.ncpqh.com/";
private static String fileUrlString = "D:\\forTest\\test.html";
public void fetchAndSave(){
byte[] content = get(urlString);
saveFile(content, fileUrlString);
}

private byte[] get(String url){

HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
int statusCode = client.executeMethod(getMethod);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + getMethod.getStatusLine());
}
InputStream inputStream = getMethod.getResponseBodyAsStream();
byte[] bytes = new byte[1024 * 2000];
int index = 0;
int count = inputStream.read(bytes, index, 1024 * 2000);
while (count != -1) {
index += count;
count = inputStream.read(bytes, index, 1);
}
return bytes;
} catch (HttpException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
getMethod.releaseConnection();

}
}

private void saveFile(byte[] content,String fileUrl){
File htmlFile = new File(fileUrl);
if (content == null || content.equals("")) {
System.out.println("There is no content");
}else {
try {
if (htmlFile.exists()) {
htmlFile.delete();
htmlFile.createNewFile();
//这里有个缺陷,如果恰巧删除的时候有人访问的话,对用户来说会很不友好
}
FileOutputStream fileOutputStream = new FileOutputStream(htmlFile);
fileOutputStream.write(content);
fileOutputStream.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}
}


定时器的部分比较简单quartz官网有很详细的demo,我就不贴代码了

下面是过滤器的部分,碰巧的是我需要静态化的页面只有首页,所以只需要在web.xml里配置一下欢迎页面就可以了,所以就不用过滤器了。但是如果不是首页的是需要配置过滤器的。

好了,到这里静态化的工作就完成了,我这次的收获是这样的:对于毫无头绪的问题,要理性的去分析,一步一步来,不能急于求成。