基於 JSP/Servlet + MySQL + Commons-DbUtils 的輕量級新聞發布系統,採用 MVC 分層,含登入驗證、新聞增刪改查、主題管理、會話追蹤完整實現。
CREATE TABLE `user` ( `uname` VARCHAR(50) PRIMARY KEY, `upwd` VARCHAR(100) NOT NULL ); CREATE TABLE `topic` ( `tid` INT PRIMARY KEY AUTO_INCREMENT, `tname` VARCHAR(100) NOT NULL ); CREATE TABLE `news` ( `nid` INT PRIMARY KEY AUTO_INCREMENT, `ntitle` VARCHAR(200) NOT NULL, `ncontent` TEXT, `npubtime` DATETIME DEFAULT CURRENT_TIMESTAMP, `tid` INT, `uname` VARCHAR(50), FOREIGN KEY (tid) REFERENCES topic(tid), FOREIGN KEY (uname) REFERENCES user(uname) );
public class BaseDao {
private static final String URL = "jdbc:mysql://localhost:3306/newsdb?useSSL=false";
private static final String USER = "root";
private static final String PASS = "123456";
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASS);
}
}
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String uname = req.getParameter("uname");
String upwd = req.getParameter("upwd");
String sql = "SELECT COUNT(1) FROM user WHERE uname=? AND upwd=?";
QueryRunner qr = new QueryRunner();
try (Connection conn = new BaseDao().getConnection()) {
Long count = qr.query(conn, sql, new ScalarHandler(), uname, upwd);
if (count > 0) {
HttpSession session = req.getSession();
session.setAttribute("uname", uname);
Cookie cookie = new Cookie("uname", uname);
cookie.setMaxAge(60*60*24);
resp.addCookie(cookie);
resp.sendRedirect(req.getContextPath() + "/admin.jsp");
} else {
resp.sendRedirect(req.getContextPath() + "/index.jsp");
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
// 新增 String sql = "INSERT INTO news(ntitle, ncontent, tid, uname) VALUES(?,?,?,?)"; qr.update(conn, sql, title, content, tid, uname); // 列表(分頁) sql = "SELECT n.*, t.tname FROM news n LEFT JOIN topic t ON n.tid=t.tid ORDER BY n.npubtime DESC LIMIT ?,?"; Listlist = qr.query(conn, sql, new BeanListHandler (News.class), offset, pageSize); // 編輯回顯 sql = "SELECT * FROM news WHERE nid=?"; News news = qr.query(conn, sql, new BeanHandler (News.class), nid); // 更新 sql = "UPDATE news SET ntitle=?, ncontent=?, tid=? WHERE nid=?"; qr.update(conn, sql, title, content, tid, nid); // 刪除 sql = "DELETE FROM news WHERE nid=?"; qr.update(conn, sql, nid);
同新聞模組,針對 topic 表做增刪改查,下拉選單動態載入:
// JSP 中
index.jsp 登入頁admin.jsp 後台首頁(顯示歡迎用戶、功能導航)news_add.jsp / news_edit.jsp 新增/編輯新聞news_list.jsp 新聞列表(分頁、編輯/刪除按鈕)topic_add.jsp / topic_list.jsp 主題管理fn:escapeXml)