JSP+Servlet實現對數據庫增刪改查之進階mvc架構

1.Bean層(Model層)?

  1. 角色:就像餐廳里的“菜品”。
  2. ?功能:是純數據對象(如Person類),封裝屬性和 getter/setter(例如用戶名、密碼)。
  3. ?示例Person類
package com.bean;public class Person {private int id;private String name;private String pwd;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}
}

2.Dao層(Data Access Object)?

  • 角色:后廚的“廚師”,專注做菜(操作數據)。
  • ?功能:直接和數據庫對話,執行增刪改查(CRUD)。
  • ?示例UserDAO?類中的?saveUser(User user)?方法,負責把用戶數據存入數據庫。

接口

package com.dao;import com.bean.Person;import java.sql.SQLException;
import java.util.List;public interface PersonDao {public List<Person> queryAll() throws SQLException;public  Boolean selectOne(Person person) throws SQLException;public int save(Person person) throws SQLException;
}

實現接口

package com.dao.impl;import com.bean.Person;
import com.dao.PersonDao;
import com.db.DB;import java.sql.*;
import java.util.ArrayList;
import java.util.List;public class PersonDaoImpl implements PersonDao {// ------------------------- 方法1:查詢所有用戶 -------------------------@Overridepublic List<Person> queryAll() throws SQLException {Connection connection=new DB().getConnection(); //獲取數據庫連接Statement statement= connection.createStatement(); //創建SQL執行器ResultSet resultSet= statement.executeQuery("select * from person"); //執行查詢SQL語句List list=new ArrayList(); //準備空集合裝數據while (resultSet.next()){  //遍歷查詢結果(一行一行讀)Person p=new Person(); //新建數據盒子p.setId(resultSet.getInt(1));  //取第一列(id)放入盒子p.setName(resultSet.getString(2));  //取第二列(name)放入p.setPwd(resultSet.getString(3));  //取第三列(pwd)放入list.add(p); //把盒子加入集合}resultSet.close();statement.close();connection.close();return list;}// ------------------------- 方法2:檢查用戶名是否存在 -------------------------@Overridepublic Boolean selectOne(Person person) throws SQLException {//Connection connection=new DB().getConnection(); getConnection()為靜態方法就可以之間如下:Connection connection= DB.getConnection(); //獲取一個數據庫連接PreparedStatement statement= connection.prepareStatement("select * from person where name=?");statement.setString(1,person.getName()); //設置參數(替換第一個問號)ResultSet resultSet= statement.executeQuery(); //執行查詢if (resultSet.next()){return false;}else {return true;}}// ------------------------- 方法3:保存用戶 -------------------------@Overridepublic int save(Person person) throws SQLException {Connection connection= DB.getConnection();//  預編譯SQL(提高性能,防止注入)PreparedStatement statement= connection.prepareStatement("insert into person(name,pwd) values(?,?)");statement.setString(1,person.getName()); //設置第一個參數(name)statement.setString(2,person.getPwd()); //設置第二個參數(pwd)int i= statement.executeUpdate(); //執行插入操作statement.close();connection.close();return i; //返回影響的行數(1=成功,0=失敗)}
}

3.DB(驅動連接數據庫)

  • ?角色:餐廳的“倉庫”,存儲所有食材。
  • ?功能:持久化保存數據(如 MySQL、PostgreSQL)
package com.db;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public  class  DB {public static Connection getConnection(){Connection connection=null;try {Class.forName("com.mysql.cj.jdbc.Driver");connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/users?serverTimezone=GMT%2B8","root","123456");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return connection;}}

4.Service層

  • 角色:餐廳的“經理”,協調復雜流程。
  • ?功能:處理業務邏輯(例如注冊時檢查用戶名是否重復 + 加密密碼)。
  • ?示例UserService?的?registerUser()?方法會調用 DAO 的多個操作,并處理事務。

接口

package com.service;import com.bean.Person;import java.sql.SQLException;
import java.util.List;public interface PersonSercie {public List<Person> AllPerson() throws SQLException;public boolean register(Person person) throws SQLException;
}

實現接口

package com.service.impl;import com.bean.Person;
import com.dao.PersonDao;
import com.dao.impl.PersonDaoImpl;
import com.service.PersonSercie;import java.sql.SQLException;
import java.util.List;public class PersonServiceImpl implements PersonSercie {@Overridepublic List<Person> AllPerson() throws SQLException {PersonDao dao=new PersonDaoImpl(); // 1. 創建DAO對象,準備訪問數據庫return dao.queryAll();  // 2. 調用DAO查詢所有用戶}@Overridepublic boolean register(Person person) throws SQLException {PersonDao dao=new PersonDaoImpl();//檢查用戶名是否已存在if(dao.selectOne(person)){  //調用DAO查詢是否存在同名用戶dao.save(person); //無重復 → 保存用戶return true; //返回注冊成功}else {return false; //返回注冊失敗}}
}

5.Servlet(Controller層)?

  • 角色:餐廳的“服務員”,接待客人并傳遞需求。
  • ?功能:接收 HTTP 請求(如?POST /login),調用 Service 處理,返回響應(跳轉頁面或 JSON)。
  • ?示例LoginServlet?獲取表單參數,交給?UserService?驗證登錄。

刪除

package com.servlet;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;@WebServlet(name = "DeleteServlet",urlPatterns = "/del")
public class DeleteServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String id=request.getParameter("id");try {Class.forName("com.mysql.cj.jdbc.Driver");Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/users?serverTimezone=GMT%2B8","root","123456");//Statement statement= connection.createStatement();PreparedStatement statement= connection.prepareStatement("delete  from person where id=?");statement.setInt(1,Integer.parseInt(id));int i=statement.executeUpdate();if(i>0){response.sendRedirect("listall");}else {response.getWriter().println("Error");}statement.close();connection.close();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}
}

查看

package com.servlet;import com.bean.Person;
import com.service.PersonSercie;
import com.service.impl.PersonServiceImpl;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.List;@WebServlet(name = "ListAllServlet",urlPatterns = "/listall")
public class ListAllServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PersonSercie personSercie=new PersonServiceImpl();try {List<Person> list=personSercie.AllPerson();request.setAttribute("persons",list);request.getRequestDispatcher("listall.jsp").forward(request,response);} catch (SQLException e) {e.printStackTrace();}}
}

增加

package com.servlet;import com.bean.Person;
import com.service.PersonSercie;
import com.service.impl.PersonServiceImpl;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;@WebServlet(name = "RegServlet",urlPatterns = "/reg")
public class RegServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name=request.getParameter("uname");String pwd=request.getParameter("upwd");Person person=new Person();person.setName(name);person.setPwd(pwd);//調用模型中注冊業務邏輯實現PersonSercie personSercie = new PersonServiceImpl(); // 創建服務層對象(業務邏輯處理者)try {if(personSercie.register(person)){  // 調用服務層的注冊方法response.sendRedirect("login.jsp");   // 注冊成功:跳轉到登錄頁}else {response.sendRedirect("reg.jsp");// 注冊失敗:返回注冊頁};} catch (SQLException e) {e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}

改1

package com.servlet;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;@WebServlet(name = "UpdateDoServlet",urlPatterns = "/updateDo")
public class UpdateDoServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String id=request.getParameter("id");String name=request.getParameter("username");String pwd=request.getParameter("userpwd");try {Class.forName("com.mysql.cj.jdbc.Driver");Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/users?serverTimezone=GMT%2B8","root","123456");//Statement statement= connection.createStatement();PreparedStatement statement= connection.prepareStatement("update person set name=?,pwd=? where  id=?");statement.setString(1,name);statement.setString(2,pwd);statement.setInt(3,Integer.parseInt(id));int i=statement.executeUpdate();if(i>0){response.sendRedirect("listall");}else {response.getWriter().println("Error");}statement.close();connection.close();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}

改2

package com.servlet;import com.bean.Person;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;@WebServlet(name = "UpdateServlet",urlPatterns = "/update")
public class UpdateServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String id=request.getParameter("id");try {Class.forName("com.mysql.cj.jdbc.Driver");Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/users?serverTimezone=GMT%2B8","root","123456");PreparedStatement statement= connection.prepareStatement("select *  from person where id=?");statement.setInt(1,Integer.parseInt(id));ResultSet resultSet=statement.executeQuery();Person p=new Person();if (resultSet.next()){p.setId(resultSet.getInt(1));p.setName(resultSet.getString(2));p.setPwd(resultSet.getString(3));}request.setAttribute("user",p);resultSet.close();statement.close();connection.close();request.getRequestDispatcher("update.jsp").forward(request,response);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}
}

總結

大概流程:就像網購流程:JSP→ 你下單(Servlet收件)→ 調度中心檢查(Service處理)→ 倉庫存取(DAO操作→倉庫DB)→ 最終收到包裹(響應結果)

  1. ?用戶填寫表單
    👉 在?reg.jsp?頁面輸入用戶名和密碼,點擊提交。

  2. ?Servlet接收請求
    👉?RegServlet?像快遞員一樣收到包裹(HTTP請求),拆開包裹取出數據(request.getParameter)。

  3. ?封裝成Bean
    👉 把數據裝進?Person?盒子(person.setName(name))。

  4. ?Service處理業務
    👉 調度員(PersonServiceImpl)開始工作:

    • 問倉庫管理員(DAO):“這個用戶名有人用嗎?”(selectOne
    • 如果沒人用,告訴管理員:“存進倉庫!”(save
  5. ?DAO操作數據庫
    👉 管理員打開倉庫(DB連接),執行 SQL 存入數據。

  6. ?返回結果給用戶
    👉 Servlet 根據結果,跳轉到登錄頁(成功)或返回注冊頁(失敗)。

至于Servlet中doGet和doPost方法該使用哪個

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/73649.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/73649.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/73649.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

多任務學習與持續學習微調:深入探索大型語言模型的性能與適應性

引言 大型語言模型&#xff08;LLMs&#xff09;的出現極大地推動了自然語言處理領域的發展。為了使其在各種特定任務和動態環境中表現出色&#xff0c;微調技術至關重要。本節將深入探討多任務學習&#xff08;Multi-task Learning, MTL&#xff09;和持續學習&#xff08;Co…

Ubuntu24.04 啟動后突然進入tty,無法進入圖形界面

問題描述 昨晚在編譯 Android AOSP 14 后&#xff0c;進入了登錄頁面&#xff0c;但出現了無法輸入密碼的情況&#xff0c;且無法正常關機&#xff0c;只能強制重啟。重啟后&#xff0c;系統只能進入 TTY 頁面&#xff0c;無法進入圖形界面。 問題排查 經過初步排查&#x…

圖論——廣度優先搜索實現

99. 島嶼數量 題目描述 給定一個由 1(陸地)和 0(水)組成的矩陣,你需要計算島嶼的數量。島嶼由水平方向或垂直方向上相鄰的陸地連接而成,并且四周都是水域。你可以假設矩陣外均被水包圍。 輸入描述 第一行包含兩個整數 N, M,表示矩陣的行數和列數。 后續 N 行,每行…

【sql靶場】第13、14、17關-post提交報錯注入保姆級教程

目錄 【sql靶場】第13、14、17關-post提交報錯注入保姆級教程 1.知識回顧 1.報錯注入深解 2.報錯注入格式 3.使用的函數 4.URL 5.核心組成部分 6.數據編碼規范 7.請求方法 2.第十三關 1.測試閉合 2.列數測試 3.測試回顯 4.爆出數據庫名 5.爆出表名 6.爆出字段 …

[項目]基于FreeRTOS的STM32四軸飛行器: 六.2.4g通信

基于FreeRTOS的STM32四軸飛行器: 六.2.4g通信 一.Si24Ri原理圖二.Si24R1芯片手冊解讀三.驅動函數講解五.移植2.4g通訊&#xff08;飛控部分&#xff09;六.移植2.4g通訊&#xff08;遙控部分&#xff09;七.通訊模塊的完成&#xff08;遙控部分&#xff09; 一.Si24Ri原理圖 S…

PyQt6內嵌http.server Web 和Flask Web服務器方法詳解

PyQt6 可以內嵌一個簡單的 Web 服務器。雖然 PyQt6 本身不提供直接的 Web 服務器功能&#xff0c;但可以結合 Python 的標準庫&#xff08;如 http.server&#xff09;或其他 Web 框架&#xff08;如 Flask、FastAPI 等&#xff09;來實現。 示例&#xff1a;使用 http.server…

【源碼分析】Nacos實例注冊流程分析-事件驅動框架

【踩坑記錄】 本人下載的Nacos 服務端版本是2.3.2&#xff0c;在開始進行源碼編譯便遇到問題&#xff0c;下面是各個問題記錄 源碼大量爆紅 在最開始用Idea加載Maven項目的時候&#xff0c;發現項目中大量的代碼爆紅&#xff0c;提示其類或者包不存在&#xff0c;后來結果查…

Unity物理射線濾除某層

關鍵點&#xff1a;使用LayerMask&#xff0c;針對Physics里檢測collider的射線&#xff08;raycast、OverlapSphere...&#xff09;都適用 1.使用layerMask過濾層 int ignoreLayer LayerMask.NameToLayer("IgnoreRaycast");// 獲取要忽略的層 int layerMask ~(1…

【白話神經網絡(二)】矩陣、CNN、RNN

全連接層 回顧前面學過的知識&#xff1a; 一個最簡單的神經網絡&#xff0c;就是ywxb 套上一個激活函數。 如果有多個輸入&#xff0c;那就是多個w和x 如果有多個輸出&#xff0c;那就再來一行公式&#xff0c;多一組w和b 要是神經元多了的話&#xff0c;公式密密麻麻的&…

Unity教程(二十二)技能系統 分身技能

Unity開發2D類銀河惡魔城游戲學習筆記 Unity教程&#xff08;零&#xff09;Unity和VS的使用相關內容 Unity教程&#xff08;一&#xff09;開始學習狀態機 Unity教程&#xff08;二&#xff09;角色移動的實現 Unity教程&#xff08;三&#xff09;角色跳躍的實現 Unity教程&…

深入解析Java面向對象三大特征之多態、final、抽象類與接口

面向對象編程&#xff08;OOP&#xff09;的三大核心特征為封裝、繼承、多態&#xff0c;其中多態是最具靈活性和擴展性的特性。本文將從多態的本質出發&#xff0c;結合final關鍵字、抽象類與接口的設計&#xff0c;深入探討這些概念的應用場景及其在代碼中的實現細節&#xf…

編碼器和解碼器概念及算法示例【清晰易懂】

編碼器&#xff08;Encoder&#xff09;和解碼器&#xff08;Decoder&#xff09;是處理信息的一對“搭檔”&#xff0c;它們的作用就像是“翻譯員”和“逆翻譯員”。 1. 編碼器&#xff08;Encoder&#xff09;是什么&#xff1f; &#x1f449; 把原始信息變成另一種形式&a…

爬蟲逆向:逆向中用到匯編語言詳細總結

更多內容請見: 爬蟲和逆向教程-專欄介紹和目錄 文章目錄 一、匯編語言基礎二、常見匯編指令2.1 數據傳輸指令2.2 算術指令2.3 邏輯指令2.4 控制流指令2.5 其他指令三、寄存器概述四、調用約定五、棧操作與函數調用六、逆向工程中的匯編分析七、常用逆向工具八、實際案例分析九…

CTF WEB題

[文件包含,少許難度] 地址:攻防世界 代碼審計WRONG WAY! <?php include("flag.php"); #包含了一個“flag.php”文件 highlight_file(__FILE__); #來顯示當前文件的源代碼 if(isset($_GET["file1"]) && isset($_GET["file2"])) #isse…

c++圖論(一)之圖論的起源和圖的概念

C 圖論之圖論的起源和圖的概念 圖論&#xff08;Graph Theory&#xff09;是數學和計算機科學中的一個重要分支&#xff0c;其起源可以追溯到 18 世紀 的經典問題。以下是圖論的歷史背景、核心起源問題及其與基本概念和用途&#xff1a; 借用一下CSDN的圖片哈 一、圖論的起源&…

Ollama + CherryStudio:構建本地私有知識庫

前面我們介紹了Ollama的安裝和使用&#xff0c;并通過Open-WebUI進行調用&#xff0c;相信大家對Ollama也有了一定的了解&#xff1b;這篇博文就結合Ollama工具和CherryStudio工具構建一個本地知識庫&#xff08;RAG&#xff09;&#xff1b;在進行接下來的操作之前&#xff0c…

【實戰ES】實戰 Elasticsearch:快速上手與深度實踐-8.2.1AWS OpenSearch無服務器方案

&#x1f449; 點擊關注不迷路 &#x1f449; 點擊關注不迷路 &#x1f449; 點擊關注不迷路 文章大綱 8.2.1AWS OpenSearch 無服務器方案深度解析與實踐指南1. Serverless架構的核心價值與行業趨勢1.1 傳統Elasticsearch集群的運維挑戰1.2 Serverless技術演進路線技術特性對比…

清晰易懂的Java8安裝教程

小白也能看懂的 Java 8 安裝教程&#xff08;JDK 和 JRE 分目錄安裝&#xff09; 本教程將手把手教你如何在 Windows 系統上安裝 Java 8&#xff08;JDK 1.8&#xff09;&#xff0c;并將 JDK 和 JRE 安裝到不同的目錄中&#xff0c;同時提供國內 Java 8 下載源和方法。即使你…

圖搜索的兩種寫法,廣度優先和深度優先

最近AI的爆發大家都瘋了&#xff0c;也確實夠瘋&#xff0c;前幾年誰能天天和AI聊天呢&#xff0c;特別它越來越智能&#xff0c;越來越理解你&#xff0c;你越來越離不開它&#xff0c;我很好奇將來它會不會有情緒&#xff0c;太可怕了&#xff0c;一旦有了這個就有了感情&…

嵌入式八股RTOS與Linux---前言篇

前言 Linux與RTOS是校招八股的時候很喜歡考察的知識,在這里并沒有把兩個操作系統完全的獨立開去講,放在一起對比或許可能加深印象。我們講Linux的內核有五部分組成:進程調度、內存管理、文件系統、網絡接口、進程間通信,所以我也將從這五方面出發 中斷管理去對比和RTOS的不同。…