本文參考了一些網站上關於 JSP 操作 XML 的文件,並混入個人實作心得。案例是一個企業內部訂餐系統的後台管理端部分程式碼,功能聚焦在「餐館基本資料管理」。
這個例子最初只是作者與前公司同事開玩笑的產物之一,也藉此紀念那些一起共事的朋友。
程式運行在 TOMCAT 4.01 平台上的 B/S 架構環境。TOMCAT 的安裝設定這裡不談,只說明相關檔案與目錄結構。
/tomcat/webapps/canyin/ — 主目錄
/tomcat/webapps/canyin/Jsp/ — JSP 檔案
/tomcat/webapps/canyin/Jsp/admin/ — 後台管理 JSP
/tomcat/webapps/canyin/WEB-INF/classes/canyin/ — JavaBean
/tomcat/webapps/canyin/data/ — XML 資料檔
/tomcat/webapps/ROOT/ — 啟動首頁,只放 index.html
/tomcat/webapps/canyin/data/users.xml — 使用者資訊
/tomcat/webapps/canyin/data/restaurants.xml — 餐館基本資料
/tomcat/webapps/ROOT/index.html — 首頁,輸入帳號密碼
/tomcat/webapps/canyin/Jsp/loginjudge.jsp — 身分判定頁,依帳號密碼決定跳轉後台或前台
/tomcat/webapps/canyin/Jsp/admin/admin_rest.jsp — 餐館資料管理頁
/tomcat/webapps/canyin/WEB-INF/classes/canyin/checkSessionBean.class — 檢查 session 是否為管理員
/tomcat/webapps/canyin/WEB-INF/classes/canyin/connXmlBean.class — 連線/讀取 XML
/tomcat/webapps/canyin/WEB-INF/classes/canyin/writeXmlBean.class — 寫入 XML
users.xml 記錄帳號、密碼與角色:
<?xml version="1.0" encoding="UTF-8" ?>
<users>
<user name="joard" passWord="joard" roles="admin" />
<user name="joard01" passWord="joard01" roles="user" />
<user name="joard02" passWord="joard02" roles="user" />
</users>
restaurants.xml 記錄餐館資訊:
<?xml version="1.0" encoding="UTF-8" ?>
<restaurants num="10">
<restaurant id="1">
<name>上海亭快餐店</name>
<phone>021-76546726</phone>
<address>百老匯廣場 B 座</address>
</restaurant>
<restaurant id="8">
<name>香格里拉大飯店</name>
<phone>021-2312134</phone>
<address>南京路 1023 號</address>
</restaurant>
</restaurants>
這裡有個實務技巧:<restaurants> 上的 num 屬性記錄「曾經寫入過幾筆資料」。每新增一筆就加一,即使後續刪除也不回退,作用等同資料庫裡慣用的自動遞增 ID,用來給新 <restaurant> 的 id 屬性一個唯一值。
純 HTML,重點是表單把帳號密碼 POST 到 loginjudge.jsp,並在提交前做基本驗證:
<form name=dataform method=post action='canyin/Jsp/loginjudge.jsp'>
<tr>
<td width="100"><b>登錄名:</b></td>
<td><input maxlength=16 name="username" class=stedit></td>
</tr>
<tr>
<td width="100"><b>密碼:</b></td>
<td><input class=stedit maxlength=16 name="userpass" type=password></td>
</tr>
</form>
搭配的 JavaScript 驗證函式:
function checkform()
{
var Checkblank = /^(\s*|(\ )|(\.))*$/;
if (Checkblank.test(dataform.username.value))
{
alert("登錄名不能為空 !");
return false;
}
if (Checkblank.test(dataform.userpass.value))
{
alert("密碼不能為空!");
return false;
}
window.dataform.submit();
}
checkSessionBean:檢驗傳入的 session 名稱與預期值是否相符。
package canyin;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
public class checkSessionBean {
private boolean bolCheckPass = false;
public boolean checkSessionBean(HttpServletRequest request, String strSessionName, String strCheckValue) {
if (strSessionName == null || strCheckValue == null) {
return bolCheckPass;
} else {
HttpSession session = request.getSession(false);
if (session != null && session.getValue(strSessionName) != null) {
bolCheckPass = session.getValue(strSessionName).equals(strCheckValue);
}
return bolCheckPass;
}
}
}
connXmlBean:以 DOM 方式打開指定的 XML 檔。
package canyin;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class connXmlBean {
private DocumentBuilderFactory factory = null;
private DocumentBuilder builder = null;
private Document doc = null;
public String connXml(String xmlFileName) {
String strExc = "";
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
doc = builder.parse(xmlFileName);
doc.normalize();
} catch (Exception e) {
strExc = e.toString();
}
return strExc;
}
public Document getXMLDoc() {
return doc;
}
}
writeXmlBean:把 DOM 內容寫回指定 XML 檔。
package canyin;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import org.w3c.dom.*;
public class writeXmlBean {
public String writeXml(Document doc, String xmlFileName) {
String strExc = "";
try {
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer = tfactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(xmlFileName));
transformer.transform(source, result);
} catch (Exception e) {
strExc = e.toString();
}
return strExc;
}
}
讀取 users.xml,逐一比對帳號密碼,並依 roles 屬性決定去處:
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" import="javax.xml.parsers.*" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="canyin.*" %>
<jsp:useBean id="xmlBean" class="canyin.connXmlBean" scope="page" />
<%
session.setMaxInactiveInterval(1800);
Document doc;
NodeList users;
String strUsername = (String) request.getParameter("username");
String strPassWord = (String) request.getParameter("userpass");
// 先確認不是空值
if (strUsername == null || strPassWord == null) {
out.println("<script>alert('用戶名或密碼有空值!'); ");
out.println("window.location.href='/index.html';</script>");
return;
}
xmlBean.connXml("webapps/canyin/data/users.xml");
doc = xmlBean.getXMLDoc();
users = doc.getElementsByTagName("user");
for (int i = 0; i < users.getLength(); i++) {
Element user = (Element) users.item(i);
String strName = user.getAttributeNode("name").getNodeValue();
String strPass = user.getAttributeNode("passWord").getNodeValue();
String strRole = user.getAttributeNode("roles").getNodeValue();
if (strName.equals(strUsername) && strPass.equals(strPassWord)) {
if (strRole.equals("admin")) {
session.setAttribute("sesUserRole", "admin");
response.sendRedirect("admin/admin_rest.jsp");
} else {
session.setAttribute("sesUserRole", "user");
response.sendRedirect("index.jsp");
}
return;
}
}
out.println("<script>alert('用戶名或密碼錯誤!'); history.go(-1);</script>");
%>
這支程式同時負責「驗權」與「CRUD」。開頭先擋掉非管理員:
<%
if (!checkSessionBean.checkSessionBean(request, "sesUserRole", "admin")) {
out.print(showDialog("您沒有管理的權限!", "/index.html"));
return;
}
String strAct = (String) request.getParameter("act");
xmlBean.connXml("webapps/canyin/data/restaurants.xml");
doc = xmlBean.getXMLDoc();
restaurants = doc.getElementsByTagName("restaurant");
%>
新增(act=addnewDo)的重點流程:
新增節點的核心程式碼:
Element restNum = (Element) doc.getElementsByTagName("restaurants").item(0);
int intNum = Integer.parseInt(restNum.getAttributeNode("num").getNodeValue()) + 1;
restNum.getAttributeNode("num").setNodeValue(String.valueOf(intNum));
Element newRestaurant = doc.createElement("restaurant");
Attr newArrId = doc.createAttribute("id");
newArrId.setValue(String.valueOf(intNum));
newRestaurant.setAttributeNode(newArrId);
Element newName = doc.createElement("name");
newName.appendChild(doc.createTextNode(strName));
newRestaurant.appendChild(newName);
Element newPhone = doc.createElement("phone");
newPhone.appendChild(doc.createTextNode(strPhone));
newRestaurant.appendChild(newPhone);
Element newAddress = doc.createElement("address");
newAddress.appendChild(doc.createTextNode(strAddress));
newRestaurant.appendChild(newAddress);
doc.getDocumentElement().appendChild(newRestaurant);
writeXmlBean.writeXml(doc, "webapps/canyin/data/restaurants.xml");
修改(act=modiDo):先依 recordId 找出目標節點在 NodeList 中的索引,並用 recordExist 旗標確認記錄存在;同時檢查名稱、電話是否與「其他」記錄重複(比較時要排除自己),最後用 setNodeValue() 就地更新三個子節點的文字內容。
刪除(act=del):同樣先定位索引,再取得該節點並從父節點移除:
Node delNode = (Node) restaurants.item(intI);
doc.getElementsByTagName("restaurants").item(0).removeChild(delNode);
writeXmlBean.writeXml(doc, "webapps/canyin/data/restaurants.xml");
頁面狀態由 act 參數決定:沒有 act 時為 show(純列表);act=modi 時把該列換成輸入框;act=addnew 時在表格尾端多一列空白輸入框。若 restaurants 完全沒有資料,會自動切到 addnew 狀態。修改列的表單會帶一個 hidden 的 recordId,方便送出時定位;刪除按鈕則用 confirm() 二次確認後導向 act=del。
幾點實作中踩到的坑,值得記下: