- package com.yancms.util;
- import java.io.*;
- import org.apache.commons.httpclient.*;
- import org.apache.commons.httpclient.methods.*;
- import org.apache.commons.httpclient.params.HttpMethodParams;
- /**
- * 靜態頁面引擎技術(突亂了亂碼問題UTF-8)
- * @author 吳彥文
- *
- */
- public class HtmlGenerator extends BaseLog {
- HttpClient httpClient = null; //HttpClient實例
- GetMethod getMethod =null; //GetMethod實例
- BufferedWriter fw = null;
- String page = null;
- String webappname = null;
- BufferedReader br = null;
- InputStream in = null;
- StringBuffer sb = null;
- String line = null;
- //構造方法
- public HtmlGenerator(String webappname){
- this.webappname = webappname;
- }
- /** 根據模版及參數產生靜態頁面 */
- public boolean createHtmlPage(String url,String htmlFileName){
- boolean status = false;
- int statusCode = 0;
- try{
- //創建一個HttpClient實例充當模擬瀏覽器
- httpClient = new HttpClient();
- //設置httpclient讀取內容時使用的字符集
- httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
- //創建GET方法的實例
- getMethod = new GetMethod(url);
- //使用系統提供的默認的恢復策略,在發生異常時候將自動重試3次
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
- //設置Get方法提交參數時使用的字符集,以支持中文參數的正常傳遞
- getMethod.addRequestHeader("Content-Type","text/html;charset=UTF-8");
- //執行Get方法並取得返回狀態碼,200表示正常,其它代碼為異常
- statusCode = httpClient.executeMethod(getMethod);
- if (statusCode!=200) {
- logger.fatal("靜態頁面引擎在解析"+url+"產生靜態頁面"+htmlFileName+"時出錯!");
- }else{
- //讀取解析結果
- sb = new StringBuffer();
- in = getMethod.getResponseBodyAsStream();
- //br = new BufferedReader(new InputStreamReader(in));//此方法默認會亂碼,經過長時期的摸索,下面的方法才可以
- br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
- while((line=br.readLine())!=null){
- sb.append(line+"\n");
- }
- if(br!=null)br.close();
- page = sb.toString();
- //將頁面中的相對路徑替換成絕對路徑,以確保頁面資源正常訪問
- page = formatPage(page);
- //將解析結果寫入指定的靜態HTML文件中,實現靜態HTML生成
- writeHtml(htmlFileName,page);
- status = true;
- }
- }catch(Exception ex){
- logger.fatal("靜態頁面引擎在解析"+url+"產生靜態頁面"+htmlFileName+"時出錯:"+ex.getMessage());
- }finally{
- //釋放http連接
- getMethod.releaseConnection();
- }
- return status;
- }
- //將解析結果寫入指定的靜態HTML文件中
- private synchronized void writeHtml(String htmlFileName,String content) throws Exception{
- fw = new BufferedWriter(new FileWriter(htmlFileName));
- OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(htmlFileName),"UTF-8");
- fw.write(page);
- if(fw!=null)fw.close();
- }
- //將頁面中的相對路徑替換成絕對路徑,以確保頁面資源正常訪問
- private String formatPage(String page){
- page = page.replaceAll("\\.\\./\\.\\./\\.\\./", webappname+"/");
- page = page.replaceAll("\\.\\./\\.\\./", webappname+"/");
- page = page.replaceAll("\\.\\./", webappname+"/");
- return page;
- }
- //測試方法
- public static void main(String[] args){
- HtmlGenerator h = new HtmlGenerator("webappname");
- h.createHtmlPage("http://localhost:8080/yanCms/three/three?parent_id=10&id=103&type=10","c:/a.html");
- System.out.println("靜態頁面已經生成到c:/a.html");
- }
- }