servlet 生成 html 静态

package com.servlet;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/***
 *    生成html
 *    注意: 支持请求  jsp , serlvet(request.getRequestDispatcher(path).forward(request, response))  
 *          如要批量,修改  doGet()内代码.
 *    @author wei
 *
 */
public class ToHtml extends HttpServlet {


 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  
  
  
  
  response.setCharacterEncoding("text/html; charset=utf-8");
  
  String url = "";
  String name = "";
  ServletContext sc = getServletContext();

  // 你要访问的jsp文件,如index.jsp
  // 则你访问这个servlet时加参数.
  //file_name  文件名  file_url 请求url
  // 如http://localhost/toHtml?file_name=index&file_url=index.jsp
  String file_name = request.getParameter("file_name");
  String file_url  = request.getParameter("file_url");
  // 这是你要生成HTML的jsp文件,如
  // http://localhost/index.jsp的执行结果.
  url =  "/" + file_url;
  
  
  
  // 这是生成的html文件名,如index.htm.
  name = sc.getRealPath("")+"/" + file_name + ".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();

  // 把jsp输出的内容写到xxx.htm
  FileOutputStream fos = new FileOutputStream(name);

  os.writeTo(fos);
  fos.close();


 }

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doGet(request, response);
 }
 
 

}

你可能感兴趣的:(servlet)