第一种方法相对很简单就是利用java去访问以jsp教程结束的动态页面,然后获取其由服务器传下的html页面进行保存,这样适合于少数的页面更新,不适合大批量的如新闻系统更新了,我们就可以利用第二种方法了。
package com.tgdh.project.util;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.url;public class createhtml {
public static void main(string[] args) throws ioexception {
createhtml(
"http://192.168.1.200:8080/navigation/shoppingui.action?id=26",
"d:abc.html");
}public static void createhtml(string url, string filename)
throws ioexception {
url urlc = new url(url);httpurlconnection connection = (httpurlconnection) urlc
.openconnection();
inputstream ips教程 = connection.getinputstream();
fileoutputstream fos = new fileoutputstream(filename);
challage(ips, fos);
ips.close();
fos.close();
}private static void challage(inputstream ips, outputstream ops)
throws ioexception {
byte[] contents = new byte[1024];
int len = 0;
while ((len = ips.read(contents)) != -1) {
ops.write(contents, 0, len);
}
}}
下面再看一个简单应用方法
第一步,加入servlet.代码如下。
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,不包括扩展名
// 则你访问这个servlet时加参数.如http://localhost/test/tohtml?file_name=index
url = "/" + file_name + ".jsf";// 你要生成的页面的文件名。我的扩展名为jsf .
name = confconstants.context_path+""+ file_name + ".htm";// 这是生成的html文件名,如index.htm.文件名字与源文件名相同。扩展名为htm
//confconstants.context_path为你的应用的上下文路径。
requestdispatcher rd = sc.getrequestdispatcher(url);
final bytearrayoutputstream = 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 ōut = response.getwriter();
out
.print("<p align=center><font size=3 color=red>页面已经成功生成!single<br>http://www.agilejava.org/space/? 233</font></p>");
}
}
第二步、配置你的web.xml
<servlet>
<servlet-name>tohtml</servlet-name>
<servlet-class>mj.util.html.tohtml</servlet-class>//你的servlet的类。
</servlet>
<servlet-mapping>
<servlet-name>tohtml</servlet-name>
<url-pattern>/tohtml</url-pattern>
</servlet-mapping>第三步、运行servlet。如:http://localhost:8080/test/tohtml?file_name=index
ok,这就在你的test项目的根目录下,生成了一个index.htm的静态文件。