一、實現原因
1.網站訪問量過大,導致服務器壓力加大以及數據庫數據交換頻繁。生成靜態頁面提供訪問以緩解壓力。
2.靜態頁面是動態頁面的備份,若動態頁面出現異常,靜態頁面可以暫時替代。
二、使用場合
當某個頁面訪問量很大,且數據不經常變動適合轉換為html存儲。如網站首頁,新聞文章頁等
三、實現方法
實現方法有很多,有框架自動生成,有重寫輸出方法,有用緩存機制從而無需生成靜態頁面等,此處介紹兩種方法。
1.
使用servlet發送請求讀取jsp動態數據,將數據寫入html文件並保存。
a.首先需要一個servlet類,service方法中是生成靜態頁面的主要代碼。
1 /** 2 * @file_name 文件名及文件之后的參數 3 * @path 文件所在的路徑.相對於根目錄而言的. 4 * @realName 文件要保存的名字 5 * @realPath 文件要保存的真實路徑, 默認與文件所在的目錄相同。 6 */ 7 public class JspToHtml extends HttpServlet { 8 9 public void service(HttpServletRequest request, HttpServletResponse response) 10 throws ServletException, IOException { 11 12 HttpSession session = request.getSession(); 13 String url = ""; 14 String name = ""; 15 ServletContext sc = getServletContext(); 16 17 String file_name = request.getParameter("file_name");// 你要訪問的jsp文件,如news.jsf。 18 // file_name如:fileDetail.jsf?fileId=56.要是有參數, 只有一個參數。並且以參數名作為文件名。 19 20 String realName = request.getParameter("realName");// 要保存的文件名。如aaa;注意可以沒有這個參數。 21 22 String path = request.getParameter("path");// 你要訪問的jsp文件路徑。如news。注意可以沒有這個參數。 23 24 String realPath = request.getParameter("realPath");// 你要保存的文件路徑,如htmlNews.注意可以沒有這個參數。 25 // 下面確定要保存的文件名字。 26 if (realName == null || realName == "") { 27 int a = 0; 28 a = file_name.indexOf("=") + 1; 29 realName = file_name.substring(a); 30 if (realName.indexOf(".") > 0) { 31 realName = file_name.substring(0, file_name.indexOf(".")); 32 } 33 } 34 // 下面構造要訪問的頁面。 35 if (path == null || path.equals("")) { 36 url = "/" + file_name;// 這是你要生成HTML的jsp文件,如 37 } else { 38 url = "/" + path + "/" + file_name;// 這是你要生成HTML的jsp文件,如 39 } 40 // 下面構造要保存的文件名,及路徑。 41 // 1、如果有realPath,則保存在realPath下。 42 // 2、如果有path則保存在path下。 43 // 3、否則,保存在根目錄下。 44 if (realPath == null || realPath.equals("")) { 45 if (path == null || path.equals("")) { 46 // 這是生成的html文件名,如index.htm.說明: 47 // ConfConstants.CONTEXT_PATH為你的上下文路徑。 48 name = session.getServletContext().getRealPath("") + "\\" + realName + ".html"; 49 } else { 50 name = session.getServletContext().getRealPath("") + "\\" + path + "\\" + realName 51 + ".html";// 這是生成的html文件名,如index.html 52 } 53 } else { 54 name = session.getServletContext().getRealPath("") + "\\" + realPath + "\\" + realName 55 + ".html";// 這是生成的html文件名,如index.html 56 } 57 File file = new File(name.substring(0, name.length() - (realName.length() + 5))); 58 if (!file.exists()) { 59 file.mkdir(); 60 } 61 // 訪問請求的頁面,並生成指定的文件。 62 RequestDispatcher rd = sc.getRequestDispatcher(url); 63 64 final ByteArrayOutputStream os = new ByteArrayOutputStream(); 65 66 final ServletOutputStream stream = new ServletOutputStream() { 67 public void write(byte[] data, int offset, int length) { 68 os.write(data, offset, length); 69 } 70 71 public void write(int b) throws IOException { 72 os.write(b); 73 } 74 }; 75 76 //此處需要轉碼,防止中文字符亂碼 77 final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); 78 79 80 HttpServletResponse rep = new HttpServletResponseWrapper(response) { 81 public ServletOutputStream getOutputStream() { 82 return stream; 83 } 84 85 public PrintWriter getWriter() { 86 return pw; 87 } 88 }; 89 rep.setCharacterEncoding("gbk");// response的編碼為gbk防亂碼 90 rd.include(request, rep); 91 pw.flush(); 92 FileOutputStream fos = new FileOutputStream(name); // 把jsp輸出的內容寫到xxx.html 93 94 os.writeTo(fos); 95 fos.close(); 96 } 97 }
b.調用servlet的方法,這個方法即是后台發送請求訪問servlet的方法。
1 // 這個方法適當重載,就可以省去一些參數傳遞。 2 public static void CallOnePage(String basepath, String fileName, String path, String realName, 3 String realPath) { 4 try { 5 String str = basepath + "toHtmlPath?file_name=" + fileName + "&path=" + path 6 + "&realName=" + realName + "&realPath=" + realPath; 7 System.out.println(str); 8 int httpResult; // 請求返回碼 9 10 URL url = new URL(str); // URL發送指定連接請求 11 URLConnection connection = url.openConnection(); 12 connection.connect(); 13 HttpURLConnection httpURLConnection = (HttpURLConnection) connection; 14 httpResult = httpURLConnection.getResponseCode(); 15 16 if (httpResult != HttpURLConnection.HTTP_OK) { // 返回碼為200則連接成功 17 System.out.println("沒有連接成功!"); 18 } else { 19 System.out.println("連接成功了!!!!!"); 20 } 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 }
c.需要在web.xml里面配置servlet
<servlet> <servlet-name>jspToHtml</servlet-name> <servlet-class>com.adam.util.JspToHtml</servlet-class> </servlet> <servlet-mapping> <servlet-name>jspToHtml</servlet-name> <url-pattern>/jspToHtml</url-pattern> </servlet-mapping>
此時便可以通過第b步的方法來生成html頁面了,如
CallOnePage("http://localhost:8080/adam/","test/testHtml.do?method=save&id=1100&subid=1151&tohtml=1", "", "index", "htmls");
生成index.html文件存放在項目目錄的htmls文件夾下。
2.使用httpclient生成靜態html
a.首先導入httpclient的jar文件(commons-httpclient-3.0.1 解壓后取出jar文件導入)
b.實現主生成方法
1 /** 2 * @basePath url host信息 3 * @target 需要轉換的鏈接 4 * @path 文件要保存的真實路徑 5 * @name 文件要保存的名字 6 * @extension 文件要保存的擴展名.html/.htm 7 */ 8 public static boolean staticHtml(String basePath, String target, String path, String name, 9 String extension) { 10 boolean result = true; 11 HttpClient client = new HttpClient(); 12 GetMethod getMethod = new GetMethod(basePath + "/" + target); 13 14 System.err.println(path); 15 try { 16 client.executeMethod(getMethod); 17 18 File filePath = new File(path); 19 if (!filePath.exists()) { 20 filePath.mkdirs(); 21 } 22 23 File file = new File(path + name + extension); 24 25 // FileWriter writer = new FileWriter(file); 26 // writer.write(getMethod.getResponseBodyAsString()); 27 // writer.flush(); 28 29 //FileWriter 無法指定編碼格式,此處替代使用防止存儲的文件亂碼 30 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), 31 "UTF-8")); 32 33 out.write(getMethod.getResponseBodyAsString()); 34 out.flush(); 35 out.close(); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 result = false; 39 } 40 return result; 41 }
此時便可以通過此方法來生成html頁面了,如
staticHtml("http://localhost:8080/btbasic", "main/main.do?method=main", path, "index",".html");
便可以生成index.html放在指定的path下了。
