六、MVC模式
? Model(模型)
職責:處理數據和業務邏輯。
-
負責數據的存儲、讀取和操作。
-
包含業務規則和邏輯。
? View(視圖)
職責:展示界面和接收用戶輸入。
-
把數據以可視化的形式呈現給用戶。
-
不處理業務邏輯,只負責顯示。
? Controller(控制器)
職責:協調模型與視圖,處理請求。
-
接收用戶請求(如點擊按鈕、提交表單)。
-
調用模型處理業務邏輯。
-
控制流程并決定使用哪個視圖展示結果。
七、頁面提交方式
跳轉方式 | 觸發方式 | 是否能傳值 | 傳遞值的方式 | 聲明跳轉的方法/示例 |
---|---|---|---|---|
超鏈接 | 點擊 | 是 | URL參數(查詢字符串) | <a href="targetPage.jsp?param1=value1?m2=value2">Link</a> |
表單 | 提交(自動或編程式) | 是 | 表單字段(GET方法:URL參數;POST方法:請求體) | <form action="targetServlet" method="GET/POST">...</form> |
Forward動作 | 自動(服務器端) | 是 | 請求屬性(僅在同一個請求內有效) | request.getRequestDispatcher("target.jsp").forward(request, response); |
SendRedirect | 自動(客戶端重定向) | 是 | URL參數 或 Session/sessionStorage等 | response.sendRedirect("targetPage.jsp") |
RequestDispatcher | 自動(服務器端) | 是 | 請求屬性(forward() )或直接包含內容(include() ) | getServletContext().getRequestDispatcher("/target").include(request, response); |
八、JSP的標簽
1. <%@ page %>
:定義頁面相關的屬性
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"import="java.util.*, com.example.*" %>
2. <%@ include %>
:靜態包含其他文件的內容
<%@ include file="path/to/file.jsp" %>
3. <jsp:include>
:動態地包含另一個資源
<jsp:include page="path/to/file.jsp"><jsp:param name="paramName" value="paramValue"/> </jsp:include>
4. <jsp:forward>
:轉發請求到另一個資源
<jsp:forward page="path/to/resource.jsp"><jsp:param name="paramName" value="paramValue"/> </jsp:forward>
5. <jsp:param>
:傳遞參數給<jsp:include>
或<jsp:forward>
<jsp:param name="paramName" value="paramValue"/>
6. <jsp:useBean>
:查找或實例化一個JavaBean
7. <jsp:setProperty>
:設置JavaBean的屬性值
8. <jsp:getProperty>
:獲取JavaBean的屬性值
<body><jsp:useBean id="user" class="com.example.User" scope="request"/><jsp:setProperty name="user" property="name" value="John Doe"/><jsp:setProperty name="user" property="age" value="30"/> ?<h1>User Information</h1><p>Name: <jsp:getProperty name="user" property="name"/></p><p>Age: <jsp:getProperty name="user" property="age"/></p> </body>
九、過濾器(Filter)
作用:用于對客戶端請求和服務器響應進行預處理或后處理(比如可以省掉每個Servlet的字符編碼設置)
XML配置:同Servlet
<filter>
<filter-name>myFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
使用通配符*,匹配所有的請求
</filter-mapping>
需要重寫三個最重要的 方法
十、監聽器(Listener)
作用:ServletContextListener監聽容器啟動和銷毀,還可以監聽會話或者請求只要實現不同接口
-
ServletContextListener:監聽Web應用的啟動(
contextInitialized
)和關閉(contextDestroyed
)事件。 -
HttpSessionListener:監聽HttpSession的創建(
sessionCreated
)和銷毀(sessionDestroyed
)事件。 -
ServletRequestListener:監聽ServletRequest的創建(
requestInitialized
)和銷毀(requestDestroyed
)事件。 -
HttpSessionAttributeListener:監聽HttpSession中屬性的添加、移除或替換事件。
-
ServletContextAttributeListener:監聽ServletContext中屬性的添加、移除或替換事件。
實現相關接口:重寫一些用到的方法
xml配置
<listener>
<listener-class>com.example.MyContextListener</listener-class>
</listener>