jsp生成靜態頁面

首先應創建一個模板文件,文件名和文件後綴可以隨意,但我一般常用的還是 *.template ,因此,這裏就以 template.template 爲例( 將模板文件放入 /WEB-INF/templates/ 文件夾下 ):

template.template:

<html>
<head>
    <meta http-equiv = "Content-Type" content = "text/html; charset=gb2312" >
    <title>#title#</title>
</head>
<body bgcolor = "#CCCCCC" >
    <h3 align = "center" color = "#FFFFFF">
        <font color = "#FFFFFF" >
            #title#
            <br><hr><br>
            author:
        </font>
        <font color = "red" >#author#</font>
        <br>
        <font color = "#FFFFFF" >content:</font>
        <font color = "red" >#content#</font>
        <br><hr><br>
        <font color = "#FFFFFF" >Copy Right 2007 - 2008 &copy; Power by Easyworks.cn</font>
    </h3>
</body>
</html>

由於只是介紹一下原理,所以就只用一個 JSP 頁面來處理:

Test.jsp:

<%@ page language = "java" %>
<%@ page import = "java.util.* , java.io.*" %>
<%@ page contentType = "text/html; charset=gb2312" pageEncoding = "gb2312" %>
<%
    //設置字符編碼
    request.setCharacterEncoding( "gb2312" );
    response.setCharacterEncoding( "gb2312" );

    String title = "This is a title 標題";
    String author = "Easyoworks.cn 作者";
    String content = "This is the Content Area 正文";
    String filePath = "";
    // 獲得模板文件的路徑
    filePath = request.getRealPath( "/" ) + "WEB-INF/templates/template.template";
    / 打印出路徑
    out.println( filePath ); // 註釋
    String templateContent = "";
    // 讀取模板文件
    FileInputStream fis = new FileInputStream( filePath );
    int length = fis.available();
    byte[] bytes = new byte[ length ];
    fis.read( bytes );
    fis.close();
    templateContent = new String( bytes );
    // 打印出模板內容
    out.println( "以下是模板內容:<br>" + templateContent + "<br>以下是置換以後的 html 內容<br>" ); // 註釋
    templateContent = templateContent.replaceAll( "#title#" , title );
    templateContent = templateContent.replaceAll( "#author#" , author );
    templateContent = templateContent.replaceAll( "#content#" , content );
    // 根據時間得出文件名
    Calendar cld = Calendar.getInstance();
    String fileName = String.valueOf( cld.getTimeInMillis() ) + ".html";

    // 生成的 html 文件保存路徑
    fileName = request.getRealPath( "/" ) + fileName;
    out.println( templateContent ); // 註釋
    // 建立文件輸出流
    FileOutputStream fos = new FileOutputStream( fileName );
    byte[] tag_bytes = templateContent.getBytes();
    fos.write( tag_bytes );
    fos.close();
%>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章