JSP 生成静态HTML页面

时间:2022-02-14 08:13:21

在网站项目中,为了访问速度加快,为了方便百度爬虫抓取网页的内容,需要把jsp的动态页面转为html静态页面。通常有2种常用的方式:

1.伪静态,使用URL Rewriter

2.纯静态,本文中代码实现的就是纯静态,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;

/**
* @Description: jsp生成html页面--使用
* @author Alpha
* @date 2015年9月17日 下午1:24:27
* @version V1.0
*/
public class ToHtml extends HttpServlet {

private static final long serialVersionUID = -7294946376649752356L;

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

ServletContext sc = getServletContext();//为你的应用的上下文路径。

String fileName = request.getParameter("fileName");// 你要访问的jsp
// 则你访问这个servlet时加参数.如http://localhost/test/toHtml?fileName=index
String url = "/" + fileName + ".jsp";// 你要生成的页面的文件名。扩展名为jsp
String name = sc.getRealPath("/") + fileName + ".html";// 这是生成的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();

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

PrintWriter out = response.getWriter();
out.print("SUCCESS");

}
}
web.xml 配置:

<!-- 生成静态页面 -->
<servlet>
<servlet-name>jspToHtmlServlet</servlet-name>
<servlet-class>com.alpha.servlet.ToHtml</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jspToHtmlServlet</servlet-name>
<url-pattern>*.2html</url-pattern>
</servlet-mapping>


生成方法:

http://localhost:8080/test/idnex.2html?fileName=index 生成首页