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"); // The jsp file you want to access, such as index. jsp // Add parameters when you access this servlet, such as http: // localhost/toHtml? File_name = index Url = "/" + file_name + ". jsp"; // This is the execution result of the jsp file to generate HTML, such as // http: // localhost/index. jsp. Name = file_name + ". htm"; // the generated HTML file name, such as index.htm. PName = "../WebModule2/" + file_name + ". htm"; // Generate the complete html path 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); // write the jsp output content to the htm file in the specified path OS. writeTo (fos ); Fos. close (); Response. sendRedirect (name); // go to the htm page after writing } } |