主要的想法是jsp会在服务器构建之后再显示, 感觉jsp的相应比html应该是慢一些. 一些不会经常变动的jsp页面都换成html的话应该会加快访问速度.
如果动态信息比较多的页面没有好的想法, 还是动态的, 除非定时刷新或者手动更新?
总之在jsptohtml的过程中遇到了一些问题, 也有一些不明白的地方这里做个记录;
第一个, html和jsp的区别到底是什么?
第二个, jsp工作原理到底是什么?
第三个, 什么时候需要jsp转为html?
可以参看资料1中对于浏览器解析html的原理, html可以理解为一种文本格式,而浏览器可以解析这种格式文本然后按照特定的样式展示在浏览器界面, 为了好看加入了css和js等;
其实说到底就是:信息在浏览器中展示.
那么jsp又是什么鬼? 不难理解,其实抓住一点:所有在浏览器中解析的页面最后都是以html形式展示的!就是说其实你如果访问页面:http://127.0.0.1/index.jsp, 其实服务器返回给浏览器的不是什么jsp, 而是一个html内容.
那么jsp的原理其实就是: 当用户第一次访问index.jsp页面时, 请求到了服务器的时候, 服务器使用jsp容器将jsp构建为java文件,并编译为class, 加载到内存中, 然后解析请求组装数据位html, 将html返回给浏览器.
简单来说其实就是请求到后台之后, 服务器返回给了浏览器一个html;原来你丫就是一个html内容啊. 披着jsp的外衣.
好了,明白了浏览器加载页面的原理,那么怎么用就简单了.
第三个就是什么时候用到html, 建议的是一些变动不是很频繁地, 或者很有规律的页面;涉及到实时数据的不建议;
代码部分:
注意,在要转成html的jsp页面里面不要出现//的注释, 要使用<!---->格式的,或者/**/的标准格式;
public class JspToHtml {
private static long star = 0;
private static long end = 0;
private static long ttime = 0;
/**
* 获取页面转换后的内容
* @param httpUrl 访问地址url
* @param bianma 格式编码
* @return
*/
public static String getHtmlCode(String httpUrl, String bianma) {
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, bianma));
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;
}
/**
* 将转化后的内容保存
* @param filePath 保存地址+文件名
* @param info 页面内容
*/
public static synchronized void writeHtml(String filePath, String info) {
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
System.out.println(filePath);
out.write(info);
out.flush();
} catch (Exception ex) {
ex.getMessage();
}
}
//main调用
public static void main(String[] args) {
String url = "http://127.0.0.1:8080/corp.action?corp.id=34827";
writeHtml("/Users/tulong/java/tmp/corp34827.html",getHtmlCode(url,"utf-8"));
long tmp = Long.parseLong("0");
java.util.Date before = new java.util.Date();
long currtime = before.getTime();
System.out.println(currtime - tmp);
}
}
网上很多jsp转html得代码, 可以自行搜索;
如何使用:
在后台处理请求时, 其实只要加上判定是否存在此页面对应的html, 如果有就使用response转发[或者用result指定html,但是如果相似页面多就不科学了....], 没有就跳转到jsp页面, 并主动调用生成,下次访问就是html了.
参考资料:
html解析原理http://www.cnblogs.com/NetSos/archive/2010/11/29/1891194.html
jsp工作原理http://blog.163.com/tianbian_4159/blog/static/88874105200862685053327/
最后测试了一下,同样地内容,html比jsp快一倍至少: