jsp生成静态页面的方法
程序员文章站
2023-12-10 14:46:16
复制代码 代码如下:import java.io.bytearrayoutputstream; import java.io.fileoutputstr...
复制代码 代码如下:
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;
public class tohtml extends httpservlet
{
public void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception
{
string url="";
string name="";
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="/home/resin/resin-2.1.6/doc/"+file_name+".htm";//这是生成的html文件名,如index.htm.
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(name); //把jsp输出的内容写到xxx.htm
os.writeto(fos);
fos.close();
printwriter out=response.getwriter();
out.print("<p align=center><font size=3 color=red>首页已经成功生成!andrew</font></p>");
}
}