靜態(tài)頁(yè)面生成程序段假設(shè)想對(duì)以下test.jsp?a=123&b=456 JSP頁(yè)面生成靜態(tài)html頁(yè)面,可以利用下面的代碼段: 1 以上代碼就實(shí)現(xiàn)了具體轉(zhuǎn)換功能,使用時(shí)須注意編碼問(wèn)題,你可以建立一套自己的命名規(guī)則替產(chǎn)生的靜態(tài)頁(yè)面命名,便于管理。
import java.io.*;2 import java.net.*;3 import java.util.*;4 ![]() 5 ![]() public class TestGenerateHtml {6 ![]() 7 ![]() public static void main(String[] args) {8 9 String jspPage = "http://www./test.jsp?a=123&b=456";//jsp文件地址10 String htmlPage = "C:\\html\\test~a=123-b=456.html";//html文件名11 12 BufferedReader in = getIn(jspPage);13 BufferedWriter out = getOut(htmlPage, true);14 generateHtml(in, out);//生成靜態(tài)頁(yè)面15 close(in, out);16 }17 18 ![]() public final static void generateHtml(BufferedReader in, BufferedWriter out) {19 ![]() 20 if (out == null)21 return;//不生成靜態(tài)頁(yè)面22 ![]() try {23 int c;24 ![]() while ((c = in.read()) != -1) {25 out.write((char)c);26 }27 ![]() } catch (IOException e) {28 e.printStackTrace();29 }30 ![]() 31 }32 33 ![]() public final static BufferedReader getIn(String jspPage) {34 ![]() 35 BufferedReader in = null;36 ![]() 37 ![]() try {38 URL url = new URL(jspPage);39 URLConnection urlConn = url.openConnection();//建立http連接40 in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"gb2312"));//設(shè)置Encoding,必須設(shè)置,否則顯示中文會(huì)有問(wèn)題41 ![]() } catch (IOException e) {42 e.printStackTrace();43 }44 ![]() 45 return in;46 }47 ![]() 48 ![]() public final static BufferedWriter getOut(String htmlPage, boolean flag) {49 ![]() 50 BufferedWriter out = null;51 ![]() 52 ![]() try {53 File htmlFile = new File(htmlPage);54 ![]() if (flag) {55 htmlFile.createNewFile();56 ![]() } else {//如果flag為false則不覆蓋文件57 ![]() if (htmlFile.exists()) {//如果文件已經(jīng)存在則返回null58 return null;59 ![]() } else {//建立新文件60 htmlFile.createNewFile();61 }62 }63 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"gb2312"));//設(shè)置Encoding64 ![]() } catch (IOException e) {65 e.printStackTrace();66 }67 ![]() 68 return out;69 ![]() 70 }//flag為真則覆蓋原文件71 72 ![]() public final static void close(BufferedReader in, BufferedWriter out) {73 ![]() 74 ![]() try {75 in.close();76 if (out != null)77 out.close();78 ![]() } catch (IOException e) {79 e.printStackTrace();80 }81 ![]() 82 }83 84 }85 ![]() |
|
|
來(lái)自: Joshua > 《雜項(xiàng)》