標籤:turn dispatch 動態 stream include ppi 抓取 方便 tle
【轉載】JSP產生靜態Html頁面
在網站項目中,為了訪問速度加快,為了方便百度爬蟲抓取網頁的內容,需要把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 產生首頁
JSP產生靜態Html頁面