一、Listener監聽器
1、簡介
Listener是Servlet規范中的一員
在Servlet中,所有的監聽器接口都是以Listener結尾
監聽器實際上是Servlet規范留給JavaWeb程序員的一些特殊時機
當在某些時機需要執行一段Java代碼時,可以用對應的監聽器
2、常用的監聽器接口
(1)jakarta.servlet 包下:
ServletContextListener、ServletContextAttributeListener
ServletRequestListener、ServletRequestAttributeListener
(2)jakarta.servlet.http 包下:
HttpSessionListener
HttpSessionAttributeListener、HttpSessionBindingListener
HttpSessionIdListener、HttpSessionActivationListener
3、實現一個監聽器的步驟
(1)以ServletContextListener為例
編寫一個類實現ServletContextListener接口
這個監聽器監聽的是ServletContext對象的創建和銷毀
監聽器中的方法不需要程序員調用,在特定事件發生時由服務器調用
@WebListener
public class MyServletContextListener implements ServletContextListener {@overridepublic void contextInitialized(ServletContextEvent sce) {// 這個方法在ServletContext對象被創建時調用 }@overridepublic void contextDestroyed(ServletContextEvent sce) {// 這個方法在ServletContext對象被銷毀時調用 }
}
(2)在web.xml文件中配置這個監聽器
也可以使用 @WebListener?注解
<listener><listener-class>自己實現的監聽器類的全類名</listener-class>
</listener>
4、其他監聽器
(1)XxxxAttributeListener
監聽的是某個域中的attribute被增加、修改、刪除
只要域中的數據發生變化,就執行相應的方法
(2)XxxxBindingListener
例如,一個JavaBean實體類實現了HttpSessionBindingListener接口
那么當這個實體類的對象被放入session的attribute中觸發bind事件,移除觸發unbind事件
這個實體類不需要使用 @WebListener注解
(3)HttpSessionIdListener
監聽Session對象的Id,當Id改變時調用類中的唯一的方法
(4)HttpSessionActivationListener
監聽Session對象的鈍化和活化
鈍化:session對象從內存中存儲到硬盤文件
活化:session對象從硬盤文件中恢復到內存
二、MVC架構模式
1、簡介以及示意圖
2、JDBC工具類的封裝
public class DBUtil {private static ResourceBundle bundle = ResourceBundle.getBundle("resources/jdbc");private static String driver = bundle.getString("driver");private static String url = bundle.getString("url");private static String user = bundle.getString("user");private static String password = bundle.getString("password");// 工具類的所有方法都是靜態的// 將構造方法私有化,防止創建對象private DBUtil() {}static {try {Class.forName(driver); } catch (ClassNotFoundException e) {e.printStackTrace(); }}private static ThreadLocal<Connection> local = new ThreadLocal<>();// 沒有使用數據庫連接池,直接創建連接對象public static Connection getConnection() throws SQLException {Connection conn = local.get();if (conn == null) {conn = DriverManager.getConnection(url, user, password); local.set(conn);}return conn;}public static void close(Connection conn, Statement stmt, ResultSet rs) {if (conn != null) {try {conn.close(); local.remove(); } catch (SQLException e) {throw new RuntimeException(e); }}if (stmt != null) {try {stmt.close(); } catch (SQLException e) {throw new RuntimeException(e); }}if (rs != null) {try {rs.close(); } catch (SQLException e) {throw new RuntimeException(e); }} }}
3、MVC架構模式與三層架構的關系
三層架構:表現層、業務邏輯層、持久化層
表現層對應V和C
M包括了業務邏輯層和持久化層