本系統基於 Tomcat 5.5.7 + J2SE 5.0 + PostgreSQL 8.0 構建,採用經典的 JSP + JavaBean 模式,展示動態網站開發的基本流程。
index.jsp:管理員登入介面check.jsp:身份驗證處理main.jsp:新聞發布編輯頁pub.jsp:執行發布邏輯display.jsp:新聞列表顯示DB.java:資料庫連線封裝(單例模式管理 Connection/Statement)MD5.java:MD5 雜湊演算法,用於生成唯一靜態頁檔名PubBean.java:新聞發布核心邏輯(標題入庫 + 內容生成靜態 HTM)CheckBean.java:管理員帳密驗證為降低資料庫負載、提升前台訪問速度,系統不將新聞全文存入資料庫,而是:
news 表(欄位:title, page).htm 靜態檔案newsice{MD5(title)}.htm 格式,利用標題唯一性保證檔名不衝突CREATE TABLE administrator (
admin char(16),
"password" char(32)
) WITHOUT OIDS;
CREATE TABLE news (
title char(255),
page char(255)
) WITHOUT OIDS;
public class DB {
private Connection conn;
private Statement stmt;
public DB() {
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/news?user=admin&password=");
stmt = conn.createStatement();
} catch (Exception e) { System.out.println(e); }
}
public void update(String sql) { ... }
public ResultSet query(String sql) { ... }
}
public void pubIt() {
try {
title = new String(title.getBytes("8859_1"), "gb2312");
context = new String(context.getBytes("8859_1"), "gb2312");
String titleMD5 = md5.getkeyBeanofStr(title);
db.update("insert into news values('" + title + "','" + titleMD5 + "')");
String file = "newsice" + titleMD5 + ".htm";
PrintWriter pw = new PrintWriter(new FileOutputStream(file));
pw.println("<title>" + title + "</title>");
pw.println(context);
pw.close();
} catch (Exception e) { System.out.println(e); }
}
public String checkIt() {
try {
ResultSet rs = db.query("select * from administrator where admin='" + admin + "'");
while (rs.next()) {
String pws = rs.getString("password").trim();
if (pws.equals(password)) return "密碼正確!";
else return "密碼錯誤!";
}
return "用戶不存在!";
} catch (Exception e) { System.out.println(e); return "系統錯誤"; }
}
<form name="login" action="check.jsp" method="post">
用戶:<input type="text" name="admin"><br>
密碼:<input type="password" name="password"><br>
<input type="submit" value="登陸">
</form>
<jsp:useBean id="checkBean" class="login.CheckBean"/>
<jsp:setProperty name="checkBean" property="admin" value="<%= admin.trim() %>" />
<jsp:setProperty name="checkBean" property="password" value="<%= password.trim() %>" />
<%
String result = checkBean.checkIt();
if (result.equals("密碼正確!")) {
session.setAttribute("admin", admin);
response.sendRedirect("main.jsp");
} else {
response.sendRedirect("index.jsp?error=" + URLEncoder.encode(result, "gb2312"));
}
%>
此範例展示了早期 JSP 開發的典型模式:JSP 負責展示、JavaBean 封裝業務邏輯、靜態化生成提升性能。雖然技術棧已較老舊(Scriptlet、JDBC 直連、無連線池),但其架構思想對理解現代 MVC 框架極具參考價值。