package slt; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ToHtml extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables public void init() throws ServletException { } //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); service(request,response); }
//Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void destroy() { } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = ""; String name = ""; String pName = ""; ServletContext sc = getServletContext(); String file_name = request.getParameter("file_name"); //你要訪問的jsp檔案,如index.jsp //則你訪問這個servlet時加參數.如http://localhost/toHtml?file_name=index url = "/" + file_name + ".jsp"; //這是要產生HTML的jsp檔案,如//http://localhost/index.jsp的執行結果. name = file_name + ".htm"; //這是產生的html檔案名稱,如index.htm. pName = "../WebModule2/" + file_name + ".htm"; //產生html的完整路徑 RequestDispatcher rd = sc.getRequestDispatcher(url);
final ByteArrayOutputStream os = new ByteArrayOutputStream(); final ServletOutputStream stream = new ServletOutputStream() { public void write(byte[] data, int offset, int length) { os.write(data, offset, length); } public void write(int b) throws IOException { os.write(b); } }; final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os)); HttpServletResponse rep = new HttpServletResponseWrapper(response) { public ServletOutputStream getOutputStream() { return stream; } public PrintWriter getWriter() { return pw; } }; rd.include(request, rep); pw.flush(); FileOutputStream fos = new FileOutputStream(pName); //把jsp輸出的內容寫到指定路徑的htm檔案中 os.writeTo(fos); fos.close(); response.sendRedirect(name); //書寫完畢後轉向htm頁面 } } |