JSP生成静态html网页

梦想的初衷 提交于 2020-02-16 10:04:08
 1 /**
 2  * jsp生成静态html网页
 3  */
 4 public class ToHtml extends HttpServlet {
 5     public void service(HttpServletRequest request, HttpServletResponse response)
 6             throws ServletException, IOException {
 7         String url = "";
 8         String name = "";
 9         ServletContext sc = getServletContext();
10         String file_name = request.getParameter("file_name");// 你要访问的jsp文件名,如index,不包括扩展名
11         // 则你访问这个servlet时加参数.如[url]http://localhost/test/toHtml?file_name=index[/url]
12         url = "/" + file_name + ".jsf";// 你要生成的页面的文件名。我的扩展名为jsf .
13         name = ConfConstants.CONTEXT_PATH + "\\" + file_name + ".htm";// 这是生成的html文件名,如index.htm.文件名字与源文件名相同。扩展名为htm
14         // ConfConstants.CONTEXT_PATH为你的应用的上下文路径。
15         RequestDispatcher rd = sc.getRequestDispatcher(url);
16         final ByteArrayOutputStream ōs = new ByteArrayOutputStream();
17         final ServletOutputStream stream = new ServletOutputStream() {
18             public void write(byte[] data, int offset, int length) {
19                 os.write(data, offset, length);
20             }
21  
22             public void write(int b) throws IOException {
23                 os.write(b);
24             }
25         };
26         final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
27         HttpServletResponse rep = new HttpServletResponseWrapper(response) {
28             public ServletOutputStream getOutputStream() {
29                 return stream;
30             }
31  
32             public PrintWriter getWriter() {
33                 return pw;
34             }
35         };
36         rd.include(request, rep);
37         pw.flush();
38         FileOutputStream fos = new FileOutputStream(name); // 把jsp输出的内容写到xxx.htm
39         os.writeTo(fos);
40         fos.close();
41         PrintWriter ōut = response.getWriter();
42         out.print("<p align=center><font size=3 color=red>页面已经成功生成!single<br>[url]http://www.xxxx.org/space/?[/url] 233</font></p>");
43     }
44 }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!