您的位置:首页 > 其它

页面静态化技术的实现

2016-08-22 10:07 204 查看

页面静态化技术的实现

以前自己开发的作业提交系统,存在同学们首页打开缓慢的情况。

今天思考了下,一直知道原因,最主要的原因就是每次打开首页,都需要去数据库查询数据,这会给用户很不好的体验。



jsp动态解析,增加了数据加载时间

页面静态化处理

解决方案:在数据没有(增删改)的情况下,页面是内容是没有变化的。

故我想去把此网页的内容抓取到,在有增删改的情况下触发方法更新一下重新生成静态HTML文件。

//此方法获取你想要静态化jsp页面的页面文本内容

public static String getContent(){

//创建客户端对象

DefaultHttpClient client=new DefaultHttpClient();

//请求方式及初始化请求地址

HttpPost post=new HttpPost("http://127.0.0.1/task/index.jsp");

HttpResponse response=null;

try {

//执行请求并得到反应对象

response=client.execute(post);

//返回结果进行转字符串(得到了动态网页的文本内容)

result=EntityUtils.toString(response.getEntity(),"UTF-8");

} catch (ClientProtocolException e) {

//客户端协议异常

e.printStackTrace();

} catch (IOException e) {

//IO异常

e.printStackTrace();

}

return result;

}


故我想到了在触发内容修改是才写入html文件,写入方法为:

public  void indexStatic() throws IOException{

//获取到jsp网页文本内容

String html = HttpUtil.getContent();

//得到项目文件路径

String path =System.getProperty("user.dir");

//从bin文件夹回退

path=path.substring(0, path.length()-3);

//创建文件准备

File file = new File(path+"/webapps/task/index.html");

if (!file.exists()) {

try {

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

System.out.println("文件创建失败");

}

}

OutputStreamWriter fos=null;

try {

//创建输出流,准备输出文件,UTF-8编码保证中文不乱吗

fos = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");

fos.write(html);

} catch (FileNotFoundException e) {

e.printStackTrace();

}finally{

//关闭流对象

fos.close();

}

}


自动默认打开index.html,减轻数据库压力的同时,提升访问速度

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  静态化