1.概念
页面静态化,其实就是将动态生成的jsp页面,变成静态的HTML页面,让用户直接访问。
2.优点
(1)加快页面打开浏览速度,静态页面无需连接数据库,打开速度较动态页面有明显提高。
(2)降低数据库压力,数据库只有在最初写入HTML文件时被访问一次,之后都直接访问静态页面,大大降低与数据库交互次数。
(3)即使客户端数据库出错,也不影响网站的正常访问。
2.原理
URL发一个请求,得到这个URL的内容,内容是一个HTML,将这个HTML写成文件,将来服务器访问的时候直接访问这个静态页面,而不用访问数据库,这样数据库只有在最初写入HTML文件时访问一次,
下面通过一个简单例子来帮助理解
public class Test {
public static void main(String[] args) throws IOException {
//得到一个URL路径,这个路径访问对应一个网页
URL url=new URL("http://localhost/hqulu/admin/indexadmin");
URLConnection con=url.openConnection();
InputStream in=con.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in, "utf-8"));
//将当前访问的网页信息保存成一个静态HTML文件,写到本地d://index.html
PrintWriter pw=new PrintWriter("d://index.html");
String str;
while((str=br.readLine())!=null) {
pw.write(str);
}
pw.close();
br.close();
System.out.println("index.html静态页面生成");
}
}
代码执行结束,可以看到d盘根目录下,生成一个index.html文件,可以用浏览器直接打开。
3、封装一个静态页面生成类HtmlGenerator
package com.ulu.utils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.apache.log4j.lf5.util.StreamUtils;
/*
* 静态页面引擎技术
* */
public class HtmlGenerator {
private static Logger log=Logger.getLogger(HtmlGenerator.class);
private static CloseableHttpClient httpclient = HttpClients.createDefault();
//根据URL生成静态页面
public static void createHtmlPage(String url,String filename) {
HttpGet httpget=new HttpGet(url);//所以创建一个HttpGet,为服务器要发一个get请求做准备
CloseableHttpResponse response=null;//得到返回的结果
try {
response=httpclient.execute(httpget);//向服务器发一个get请求
HttpEntity entity=response.getEntity();//得到返回的具体内容
if(entity!=null) {
InputStream instream=entity.getContent();
FileOutputStream fo=new FileOutputStream(filename);
try {
StreamUtils.copy(instream, fo);
} finally {
fo.close();
instream.close();
}
}
}catch(Exception e){
log.error("页面生成静态化出错"+e.getMessage());
}finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//测试代码
public static void main(String[] args) {
createHtmlPage("http://localhost/hqulu/admin/indexadmin","f://index.html");
System.out.println("index.html静态页面生成");
}
}