動態JSP頁產生靜態HTML的方法_JSP編程

來源:互聯網
上載者:User

本文執行個體講述了動態JSP頁產生靜態HTML的方法。分享給大家供大家參考。具體如下:

具體實現:

利用Filter的過濾功能把*.jsp過濾出來,判斷是否存在對應的.html檔案,如果不存在對應的.html檔案,則將其內容讀出寫入指定的.html檔案,再跳轉到對應的.html即可。如果存在對應的.html檔案,則直接跳轉到對應的.html即可。
 
代碼:

JspFilter.java:

import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class JspFilter implements Filter {  public void destroy() {    // TODO 自動產生方法存根  }  public void doFilter(ServletRequest request, ServletResponse response,      FilterChain chain) throws IOException, ServletException {    HttpServletRequest hreq = (HttpServletRequest) request;    HttpServletResponse hresp = (HttpServletResponse) response;    String name = hreq.getRequestURL().substring(          hreq.getRequestURL().lastIndexOf("/") + 1,          hreq.getRequestURL().lastIndexOf("."));    if (hreq.getRequestURL().indexOf(".jsp") != -1 && (null == hreq.getParameter("type") || hreq.getParameter("type").equals(""))) {        hresp.sendRedirect(hreq.getContextPath()+"/conversion?name="+hreq.getRequestURL());        return ;    }    chain.doFilter(request, response);  }  public void init(FilterConfig arg0) throws ServletException {    // TODO 自動產生方法存根  }}

ConversionServlet.java:

import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.HttpURLConnection;import java.net.URL;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ConversionServlet extends HttpServlet {  public ConversionServlet () {    super();  }  public void destroy() {    super.destroy(); // Just puts "destroy" string in log    // Put your code here  }  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    response.setContentType("text/html");    PrintWriter out = response.getWriter();    //----擷取請求的URL    String reqTarget = request.getParameter("name");    //----指定對應JSP的HTML名稱    String name = reqTarget.substring(reqTarget.lastIndexOf("/") + 1,reqTarget.lastIndexOf("."));    //---判斷是否存在對應的HTML檔案    File file = new File(request.getRealPath("/") + name + ".html");    if (!file.exists()) {  //--------如果不存在對應的HTML檔案      try {        file.createNewFile();  //--------建立HTML檔案        //-------將JSP的內容寫入對應的HTML檔案內        InputStream in;        StringBuffer sb = new StringBuffer("");      //----注意這裡,不能直接存取請求的URL,如果直接存取的話,會陷入死迴圈        URL url = new java.net.URL(reqTarget.toString()+"?type=11");        HttpURLConnection connection = (HttpURLConnection) url            .openConnection();        connection.setRequestProperty("User-Agent", "Mozilla/4.0");        connection.connect();        in = connection.getInputStream();        java.io.BufferedReader breader = new BufferedReader(            new InputStreamReader(in, "GBK"));        String currentLine;        FileOutputStream fos = new FileOutputStream(file);        while ((currentLine = breader.readLine()) != null) {          sb.append(currentLine);          fos.write(currentLine.getBytes());        }        if (null != breader)          breader.close();        if (null != fos)          fos.close();        //---------------轉到與JSP對應的HTML頁        response.sendRedirect(request.getContextPath()+"/"+name + ".html");      } catch (Exception e) {        e.printStackTrace();      }    }else{      //----------如果存在指定的HTML,直接跳轉到指定的HTML頁      response.sendRedirect(request.getContextPath()+"/"+name + ".html");    }  }  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    doGet(request, response);  }  public void init() throws ServletException {    // Put your code here  }}

WEB.XML配置:

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4"  xmlns="http://java.sun.com/xml/ns/j2ee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <filter>  <filter-name>jspfilter</filter-name>  <filter-class>com.beanutil.JspFilter</filter-class> </filter> <filter-mapping>  <filter-name>jspfilter</filter-name>  <url-pattern>*.jsp</url-pattern> </filter-mapping> <servlet>  <servlet-name>conversion</servlet-name>  <servlet-class>com.beanutil.ConversionServlet </servlet-class> </servlet> <servlet-mapping>  <servlet-name>conversion</servlet-name>  <url-pattern>/conversion</url-pattern> </servlet-mapping></web-app>

希望本文所述對大家的JSP程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.