在网站项目中,为了访问速度加快,为了方便百度爬虫抓取网页的内容,需要把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;
-
- 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");
-
- String url = "/" + fileName + ".jsp";
- String name = sc.getRealPath("/") + fileName + ".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);
- 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 生成首页