在部落格的自動建站中,如果使用者需要申請並建立部落格,可以將已經寫好的HTML
進行讀取並替換標籤的元素或是樣式等,並寫成一個 JSP 檔案,供使用者在網頁上瀏覽
首先先必須準備好你的HTML樣板並建立一個專們處理上述問題的類別
在使用者建立之後在後台進行呼叫,以下為 HomePageReplace.java
//import the class that you need...
public class HomePageReplace
{
private HttpSession sess;
private HttpServletRequest request;
public HomePageReplace(){}
//傳入HttpServletRequest及HttpSession 以便取得相關參數或路徑....等
public HomePageReplace(HttpSession sess, HttpServletRequest request){
//this.realPath = realPath;
this.sess = sess;
this.request = request;
}
//......some method
建立物件之後 以下以我專案的例子為例(固路徑或是檔名可能不同)
首先把在根目錄下的 template 資料夾下的 template1.html 進行讀取並寫出的動作
可以透過 request.getRealPath("template/template1.html");
取得該檔案的實際路徑
並在 HomePageReplace 類別中新增讀取該檔案的方法 getContent()
private String getContent() throws IOException
{
//檔案處理盡量使用 byte 形式處理
FileInputStream fis = new FileInputStream(request.getRealPath("template/template1.html"));
byte[] TmpByte = new byte[fis.available()];
String content = "";
int s = 0;
while((s = fis.read(TmpByte)) != -1){
//以下轉碼記得使用 UTF-8
content = content + new String(TmpByte, "UTF-8"); //Use new String(byte[], encode)
}
fis.close();
return content;
}
而我的 template1.html 的邊碼處理大致如下
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="fsc.wby.molde.dbOperator" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style/template.css" />
<title>###TITLE###</title>
</head>
.......
以上的 title 標籤中的 ###TITLE###
主要是要進行使用者部分的替換,譬如部落格建立時 使用者自行輸入網站的名稱
之後在後台進行處理時針對 ###TITLE### 在替換成使用者所輸入的 title
進行這部份處理以及JSP輸出的方法為 replaceContent
public boolean replaceContent() throws IOException
{
FileOutputStream fos = null;
String content = getContent();
String tmpPath = request.getRealPath("/"); //取得 本專案的路徑
String userPath = tmpPath + "/" + (String)sess.getAttribute("domain"); //將本專案路徑加上 使用者輸入的 domain name 當作使用者的根目錄
content = content.replaceAll("###TITLE###", (String)sess.getAttribute("title"));
content = content.replaceAll("###MANAGER###", (String)sess.getAttribute("name"));
content = content.replaceAll("###INTRODUCE###", (String)request.getParameter("aboutSite"));
content = content.replaceAll("###SITENAME###", (String)sess.getAttribute("sitename"));
content = content.replaceAll("###logo###", "images/logo1.jpg");
content = content.replaceAll("###user_photo###", "images/home1.jpg");
content = content.replaceAll("<!--###content###-->", getScriptlet("/template/scriptlet.txt")); //取代網頁中的 scriptlet 程式
File tmpFile = new File(userPath); //建立使用者 的根目錄
if(!tmpFile.exists()){
tmpFile.mkdir();
}
fos = new FileOutputStream(userPath + "/index.jsp"); //首頁為 index.jsp
byte[] writeByte = content.getBytes("UTF-8");
fos.write(writeByte); //輸出
fos.close();
return true;
}
在邊碼處理上面記得在 head 標籤內加上meta<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
如果忘記這行的話,那嚜在以上程式的輸出中,就不能將 content 的指定邊碼指定為UTF-8
以上即可達到以某一個HTML檔案,進行複製、取代、並輸出成 JSP 或 HTML 了
沒有留言:
張貼留言