Java基礎入門day54

day54

servlet升級03

特點

當前設計又有一個問題,我們目前可以做到一個實體類用一個servlet,比如Student類的所有crud方法都可以在StudentServlet中的service方法中進行動態處理。假如又有User類,我們就要在UserServlet中設計service方法,在該service方法中再次進行動態方法的判斷處理

假如項目有幾百個實體類,可能對應幾百個Servlet,可能就要寫幾百個service方法的動態處理

通過分析,我們發現,可以將op的值特意設置為各個實體類的方 法名

使用反射動態獲取每一個servlet,通過發射得到每一個servlet后,動態獲取op的值,再來動態覺得調用各個op值所對應的方法

反射

“照妖鏡”,一個類中有四個訪問級別的成員,private只有自己能訪問,default自己和通過的類可以訪問,protected是自己,同包類和非同包子類可以訪問,public是當前項目所有類都可以訪問

反射可以在類的外部拿到任何訪問修飾基本的數據成員

反射功能強大,但是效率低

service方法的重構

使用反射來實現service方法的簡化

package com.saas.servlet;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
?
public class BaseServlet extends HttpServlet {
?@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");
?String op = req.getParameter("op");
?System.out.println(op);
?Class<? extends BaseServlet> clazz = getClass();
?try {Method method = clazz.getDeclaredMethod(op, HttpServletRequest.class, HttpServletResponse.class);
?//  設置方法可以被訪問method.setAccessible(true);
?//  使用反射調用對應的方法method.invoke(this, req, resp);} catch (NoSuchMethodException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);} catch (InvocationTargetException e) {throw new RuntimeException(e);}}
}

任何繼承自當前BaseServlet的servlet都會執行該BaseServlet的生命周期方法service方法

在service方法中,動態獲取用戶傳遞過來的op值

而該op值一定要設置為每個servlet中的方法名

運用反射得到op對應的方法對象,每個方法的參數列表都是HttpServletRequest和HttpServletResponse

得到每一個業務方法對象后,設置方法可以在外界被訪問

并調用invoke實現對于每個業務方法的調用

好處是當前項目只需要做一個op的判斷,無需再在每個servlet里面有關于op判斷的重復代碼

package com.saas.servlet;
?
import com.saas.entity.User;
import com.saas.service.IUserService;
import com.saas.service.impl.UserServiceImpl;
?
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
?
@WebServlet("/User")
public class UserServlet extends BaseServlet{
?private IUserService userService = new UserServiceImpl();
?public void login(HttpServletRequest req, HttpServletResponse resp){System.out.println("UserServlet login");}public void register(HttpServletRequest req, HttpServletResponse resp){System.out.println("UserServlet register");}public void logout(HttpServletRequest req, HttpServletResponse resp){System.out.println("UserServlet logout");}
?protected void saveUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{System.out.println("UserServlet saveUser");}
?protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{System.out.println("UserServlet updateUser");}
?protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{System.out.println("UserServlet deleteUser");}
?protected void getUserByUid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{System.out.println("UserServlet getUserByUid");
?String suid = req.getParameter("uid");int uid = suid == null ? 0 : Integer.parseInt(suid);
?User u = userService.getUserByUid(uid);
?PrintWriter out = resp.getWriter();
?out.print("<form>");out.print("<input type='hidden' name='uid' value='" + u.getUid() + "' />");out.print("<input type='text' name='username' value='" + u.getUsername() + "' />");out.print("<input type='text' name='password' value='" + u.getPassword() + "' />");out.print("<input type='text' name='email' value='" + u.getEmail() + "' />");out.print("<input type='text' name='phone' value='" + u.getPhone() + "' />");out.print("<input type='text' name='address' value='" + u.getAddress() + "' />");out.print("<input type='submit' value='update' />");out.print("</form>");
?}
?protected void getAllUsers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{System.out.println("UserServlet getAllUsers");
?List<User> users = userService.getAllUsers();
?PrintWriter out = resp.getWriter();
?out.print("<table border=1 align='center' width='80%'>");out.print("<tr>");out.print("<th>uid</th>");out.print("<th>username</th>");out.print("<th>password</th>");out.print("<th>email</th>");out.print("<th>phone</th>");out.print("<th>address</th>");out.print("<th>manage</th>");out.print("</tr>");for (User user : users) {out.print("<tr>");out.print("<td>" + user.getUid() + "</td>");out.print("<td>" + user.getUsername() + "</td>");out.print("<td>" + user.getPassword() + "</td>");out.print("<td>" + user.getEmail() + "</td>");out.print("<td>" + user.getPhone() + "</td>");out.print("<td>" + user.getAddress() + "</td>");out.print("<td><a href='User?op=getUserByUid&uid=" + user.getUid() + "'>update</a></td>");out.print("</tr>");}out.print("</table>");}
}
package com.saas.servlet;
?
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
@WebServlet("/Student")
public class StudentServlet extends BaseServlet {
?private static final long serialVersionUID = 1L;
?public void getAllStudents(HttpServletRequest req, HttpServletResponse resp) {System.out.println("StudentServlet getAllStudents");}
?
?public void getStudentBySid(HttpServletRequest req, HttpServletResponse resp) {System.out.println("StudentServlet getStudentBySid");}
?
?public void getStudentsByPage(HttpServletRequest req, HttpServletResponse resp) {System.out.println("StudentServlet getStudentsByPage");}
?
?public void saveStudent(HttpServletRequest req, HttpServletResponse resp) {System.out.println("StudentServlet saveStudent");}
?
?public void updateStudent(HttpServletRequest req, HttpServletResponse resp) {System.out.println("StudentServlet updateStudent");}
?
?public void deleteStudent(HttpServletRequest req, HttpServletResponse resp) {System.out.println("StudentServlet deleteStudent");}
}

在UserServlet和StudentServlet中都將不會出現op的判斷處理,只需要在BaseServlet中實現一次即可,代碼大大簡化

????????

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

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

相關文章

探索文檔識別技術在加強教育資源共享與合作中的潛力

在數字化浪潮不斷推進的今天&#xff0c;教育資源的共享與合作已經成為提高教學質量和效率的關鍵因素。文檔識別技術作為一項強大的工具&#xff0c;在這一過程中發揮著至關重要的作用。本文旨在探討如何通過文檔識別技術的應用&#xff0c;促進教育資源的有效共享與教師、學校…

MySQL主從復制故障:“ Slave_SQL_Running:No“ 兩種解決辦法

問題 今天搭建MySQL的主從復制&#xff0c;查看從機狀態時show slave status\G&#xff0c;發現這個參數為NO&#xff0c;導致主從復制失敗。 Slave_SQL_Running: No 后面上網查閱了一下資料&#xff0c;大概就是因為在連接支持數據庫后&#xff0c;也就是這個命令后&#xff…

Adobe產品安裝目錄修改

進入安裝包目錄&#xff0c;進入到products文件夾 編輯driver.xml文件 將“InstallDir”修改為你需要安裝的軟件的目錄&#xff0c;我這里是修改到D:\Adobe目錄 <DriverInfo> <ProductInfo> xxxxxxxxxxxxxxxxx </ProductInfo> 拷貝RequestInfo這部分…

c-lodop 打印面單 內容串頁

場景&#xff1a;使用c-lodop程序調取打印機連續打印多張快遞單時&#xff0c;上頁內容&#xff0c;打到了下一頁了 問題原因&#xff1a; 由于是將所有面單內容放到了一個頁面&#xff0c;c-lodop 在打印時&#xff0c;發現一頁放不下&#xff0c;會自動分割成多頁 頁面元素…

【在Postman中,如果后端返回的是String類型的數據但不是JSON格式,報錯】

在Postman中&#xff0c;如果后端返回的是String類型的數據但不是JSON格式 問題描述解決辦法 postman后端返回的String數據,不是json,怎么設置結果的接收&#xff1f; 問題描述 在postman中測試接口&#xff0c;報錯Error&#xff1a;Abort&#xff0c;或者顯示返回數據校驗失…

coveralls使用pytest進行本地測試時報錯SyntaxError: invalid escape sequence \S

## 錯誤復現&#xff1a; git clone gitgithub.com:TheKevJames/coveralls-python.git cd coveralls-python poetry install poetry run pytest## 錯誤內容&#xff1a; ## 完整的打印信息 test session starts platform darwin -- Python 3.8.18, pytest-8.2.1, pluggy-1.5.…

使用 LlamaParse 進行 PDF 解析并創建知識圖譜

此 Python 筆記本提供了有關利用 LlamaParse 從 PDF 文檔中提取信息并隨后將提取的內容存儲到 Neo4j 圖形數據庫中的綜合指南。本教程在設計時考慮到了實用性&#xff0c;適合對文檔處理、信息提取和圖形數據庫技術感興趣的開發人員、數據科學家和技術愛好者。 該筆記本電腦的主…

可視化大屏,不搞點3D效果,感覺有點對不起觀眾呢。

使用3D模型可以為可視化展現增加更多的維度和真實感&#xff0c;提供更直觀、生動的視覺效果。以下是一些3D模型在可視化展現中的作用&#xff1a; 增強沉浸感&#xff1a;通過使用3D模型&#xff0c;可以讓觀眾感受到更真實的場景和物體&#xff0c;增強他們的沉浸感。這有助…

playwright相關的文章

霍格沃茲測試開發Muller老師 - 個人中心 - 騰訊云開發者社區-騰訊云 霍格沃茲測試開發Muller老師 &#xff1a;

【數組】Leetcode 452. 用最少數量的箭引爆氣球【中等】

用最少數量的箭引爆氣球 有一些球形氣球貼在一堵用 XY 平面表示的墻面上。墻面上的氣球記錄在整數數組 points &#xff0c;其中points[i] [xstart, xend] 表示水平直徑在 xstart 和 xend之間的氣球。你不知道氣球的確切 y 坐標。 一支弓箭可以沿著 x 軸從不同點 完全垂直 地…

golang問題

文章目錄 Go里有哪些數據結構是并發安全的&#xff1f;int類型是并發安全的嗎&#xff1f;為什么int不是并發安全的&#xff1f; Go如何實現一個單例模式&#xff1f;sync.Once是如何實現的&#xff0c;如何不使用sync.Once實現單例模式&#xff1f;Go語言里的map是并發安全的嗎…

Freeswitch-Python3開發

文章目錄 一、Freeswitch如何使用mod_python31.1 Freeswitch和python1.2 Freeswitch版本選擇1.3 Freeswitch編譯mod_python31.3.1 debian安裝python31.3.2 Freeswitch編譯mod_python31.3.3 加載 二、如何編寫腳本2.1 函數的基本框架2.2 基本使用2.2.1 觸發條件2.2.2 默認腳本位…

pycharm更改遠程編輯器設置

pycharm的遠程編輯器可以分為兩個部分&#xff1a;SFTP服務器(用于傳輸文件&#xff09;和命令行&#xff08;用于控制linux&#xff09;系統。那么當創建完成后&#xff0c;如何才能更改其設置呢&#xff1f; 一、遠程SFTP服務器設置 找到導航欄依次點擊tools-deployment-co…

運行vue2項目基本過程

目錄 步驟1 步驟2 步驟3 補充&#xff1a; 解決方法&#xff1a; node-scss安裝失敗解決辦法 步驟1 安裝npm 步驟2 切換淘寶鏡像 #最新地址 淘寶 NPM 鏡像站喊你切換新域名啦! npm config set registry https://registry.npmmirror.com 步驟3 安裝vue-cli npm install…

取消頁面按鈕回車事件

html頁面登錄按鈕 <button class"btn btn-success btn-block" id"btnSubmit" data-loading"正在驗證登錄&#xff0c;請稍候...">登 錄</button>js部分 在回車鍵按下時&#xff0c;阻止默認行為 $(document).keyup(function (event…

采用偽代碼及C代碼演示如何解決脫機最小值問題

采用偽代碼及C代碼演示如何解決脫機最小值問題 問題背景算法設計偽代碼實現C代碼實現證明數組正確性使用不相交集合數據結構最壞情況運行時間的緊確界 問題背景 脫機最小值問題涉及到一個動態集合 &#xff08; T &#xff09; &#xff08;T&#xff09; &#xff08;T&…

并網逆變器學習筆記9---VSG控制

參考文獻&#xff1a;《新型電力系統主動構網機理與技術路徑》 “構網技術一般包含下垂控制&#xff0c;功率同步控制&#xff0c;虛擬同步機控制&#xff0c;直接功率控制&#xff0c;虛擬振蕩器控制 等。其中&#xff0c;虛擬同步機技術&#xff0c;即 VSG&#xff0c;因其物…

藍牙(2):BR/EDR的連接過程;查詢(發現)=》尋呼(連接)=》安全建立=》認證=》pair成功;類比WiFi連接過程。

4.2.1 BR/EDR 流程&#xff1a; 查詢&#xff08;發現&#xff09;》尋呼&#xff08;連接&#xff09;》安全建立》認證》pair成功 4.2.1.1 查詢&#xff08;發現&#xff09;流程Inquiry (discovering) 類比WiFi的probe request/response 藍牙設備使用查詢流程來發現附近的…

Github 2024-05-24 Java開源項目日報 Top10

根據Github Trendings的統計,今日(2024-05-24統計)共有10個項目上榜。根據開發語言中項目的數量,匯總情況如下: 開發語言項目數量Java項目10Java設計模式:提高開發效率的正規化實踐 創建周期:3572 天開發語言:Java協議類型:OtherStar數量:86766 個Fork數量:25959 次關…

探數API統計分享-1949年-2021年中國歷年夏糧產量統計報告

????????中國歷年夏糧產量?&#xff0c;為1949年到2021年我國每年的夏糧產量數據。2021年&#xff0c;我國夏糧產量為14596萬噸&#xff0c;比上年增長2.2%。 數據統計單位為&#xff1a;萬噸 。 我國夏糧產量有多少&#xff1f; 2021年&#xff0c;我國夏糧產量為1…