以下示範如何透過 JSP 讀取範本檔、替換其中的佔位符,再輸出成靜態 HTML 檔案,並自動跳轉到產生的頁面。
<%@ page contentType="text/html;charset=utf-8"%>
<%@page import="cn.nbaia.newPage.newsPage.*,cn.nbaia.newPage.newsImg.*,java.util.*,cn.nbaia.newPage.columnPage.*,cn.nbaia.company.*,cn.nbaia.link.*"%>
<%@page import="java.io.*"%>
<%
//此處若寫成 "WEB-INF/templates/template.htm" 程式會報錯
String filePath = request.getRealPath("/") + "test/template.htm";
out.print(filePath);
String templateContent = "";
FileInputStream fileinputstream = new FileInputStream(filePath);//讀取範本檔
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
templateContent = new String(bytes);
int newsid = 2484;//request.getParameter("id");
newsCtl nCtl = new newsCtl();
news news = new news();
news = nCtl.selectOneById(newsid);
String title = news.getTitle();
String content = news.getContent();
if (title == null) title = "";
if (content == null) content = "";
templateContent = templateContent.replaceAll("#title#", title);
templateContent = templateContent.replaceAll("#content#", content);
//根據 id 產生檔名
String fileame = String.valueOf(newsid) + ".html";
String file = "filename/" + String.valueOf(newsid) + ".html";
fileame = request.getRealPath("/") + "/filename/" + fileame;//產生的 html 檔保存路徑
out.print(templateContent);
FileOutputStream fileoutputstream = new FileOutputStream(fileame);//建立檔案輸出串流
byte tag_bytes[] = templateContent.getBytes("utf-8");
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
response.sendRedirect("../" + file);
%>
<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>jsp</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body><!--top start--><SPAN id=showTop></SPAN><IE:DOWNLOAD
id=oDownload style="BEHAVIOR: url(#default#download)" />
<SCRIPT>
function topOnDownloadDone(downDate){
showTop.innerHTML = downDate
}
oDownload.startDownload('inc/top.jsp', topOnDownloadDone)
</SCRIPT>
<!--top end-->
<TABLE width="778" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><td valign="top" bgcolor="#FFFFFF"><div align="center" class="d9p">#title#</div></td></tr>
<tr><td valign="top" bgcolor="#FFFFFF"><div align="center" class="d9p">#content#</div></td></tr>
</TABLE>
<!--bottom start--><SPAN id=showBottom></SPAN>
<SCRIPT>
function bottomOnDownloadDone(downDate)
{
showBottom.innerHTML = downDate
}
oDownload.startDownload('inc/bottom.jsp', bottomOnDownloadDone)
</SCRIPT><!--bottom end--></body></html>
來源:CSDN