*、在进行网站静态化开发时,对于系统中引入的页面也想实现以引入html方式,这样当被引入的页面发生改变时,不需要对所有引用页面进行静态化,而只需要进行被引入页面的静态化即可。
案例:jquery动态加载html页面之load http://www.360doc.com/content/15/0610/14/18139076_477138156.shtml
*、网站静态化核心之一:发起请求获取网页源码
/** * 模拟浏览器请求,给定的url返回网页源码 * @param urlPath 网页地址 * @param requestMethod GET或POST,默认是GET * @param codeType GBK或UTF-8,默认是GBK */ public static String getHtmlCode(String urlPath , String requestMethod , String codeType) { String aimHtml = null; try { URL url=new URL(urlPath); HttpURLConnection httpConn=(HttpURLConnection)url.openConnection(); //设置参数 httpConn.setDoOutput(true); //需要输出 httpConn.setDoInput(true); //需要输入 httpConn.setUseCaches(false); //不允许缓存 httpConn.setRequestMethod(StringUtils.isBlank(requestMethod) ? "GET" : requestMethod); //设置GET方式连接 //httpConn.setConnectTimeout(1000 * 10); //链接超时10秒 //httpConn.setReadTimeout(1000 * 6); //读取超时6秒 //设置请求属性 httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch"); httpConn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");//唯一一处:关键点关键点关键点 httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("Charset", StringUtils.isBlank(codeType) ? "GBK" : codeType); httpConn.setRequestProperty("Cache-Control", "max-age=0"); httpConn.setRequestProperty("Upgrade-Insecure-Requests", "1"); httpConn.setRequestProperty("User-Agent", "Mozilla/5.0"); httpConn.connect(); //获得响应状态 int resultCode=httpConn.getResponseCode(); if(HttpURLConnection.HTTP_OK==resultCode){ StringBuffer sb=new StringBuffer(); String readLine=new String(); BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),StringUtils.isBlank(codeType) ? "GBK" : codeType)); while((readLine=responseReader.readLine())!=null){ sb.append(readLine).append("\n"); } responseReader.close(); aimHtml = sb.toString(); } }catch(Exception e) { aimHtml = null; logger.error(urlPath+"网址访问失败!",e); } return aimHtml; }
*、静态化网站核心之二是将源码写入文件且不出现乱码
/** * 将解析结果写入指定的静态HTML文件中 * * @param pageContent * 文本内容 * @param fileUrl * 目标全路径 * @throws Exception */ private static void writeHtml(String pageContent, String fileUrl) throws Exception { try { OutputStreamWriter fw = new OutputStreamWriter( new FileOutputStream(fileUrl), "UTF-8"); fw.write(pageContent); if (fw != null) { fw.close(); } } catch (Exception e) { logger.error(fileUrl + "文件写入失败!", e); throw e; } }
*、静态时数据结构+urlwriter会提高效率,具体根据情境分析,(*^__^*) 嘻嘻……