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);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值