Java Web 筆記(4)

来源:https://www.cnblogs.com/xjtu-lyh/archive/2020/02/20/12337734.html
-Advertisement-
Play Games

11、Filter (重點) Filter:過濾器 ,用來過濾網站的數據; 處理中文亂碼 登錄驗證…. Filter開發步驟: 1. 導包 2. 編寫過濾器 1. 導包不要錯 實現Filter介面,重寫對應的方法即可 3. 在web.xml中配置 Filter 12、監聽器 實現一個監聽器的介面;( ...


11、Filter (重點)

Filter:過濾器 ,用來過濾網站的數據;

  • 處理中文亂碼
  • 登錄驗證….

Filter開發步驟:

  1. 導包

  2. 編寫過濾器

    1. 導包不要錯

  實現Filter介面,重寫對應的方法即可

  ```java
  public class CharacterEncodingFilter implements Filter {
  
      //初始化:web伺服器啟動,就以及初始化了,隨時等待過濾對象出現!
      public void init(FilterConfig filterConfig) throws ServletException {
          System.out.println("CharacterEncodingFilter初始化");
      }
  
      //Chain : 鏈
      /*
      1. 過濾中的所有代碼,在過濾特定請求的時候都會執行
      2. 必須要讓過濾器繼續同行
          chain.doFilter(request,response);
       */
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          response.setContentType("text/html;charset=UTF-8");
  
          System.out.println("CharacterEncodingFilter執行前....");
          chain.doFilter(request,response); //讓我們的請求繼續走,如果不寫,程式到這裡就被攔截停止!
          System.out.println("CharacterEncodingFilter執行後....");
      }
  
      //銷毀:web伺服器關閉的時候,過濾會銷毀
      public void destroy() {
          System.out.println("CharacterEncodingFilter銷毀");
      }
  }
  
  ```
  1. 在web.xml中配置 Filter

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <!--只要是 /servlet的任何請求,會經過這個過濾器-->
        <url-pattern>/servlet/*</url-pattern>
        <!--<url-pattern>/*</url-pattern>-->
    </filter-mapping>

12、監聽器

實現一個監聽器的介面;(有N種)

  1. 編寫一個監聽器

    實現監聽器的介面…

    //統計網站線上人數 : 統計session
    public class OnlineCountListener implements HttpSessionListener {
    
        //創建session監聽: 看你的一舉一動
        //一旦創建Session就會觸發一次這個事件!
        public void sessionCreated(HttpSessionEvent se) {
            ServletContext ctx = se.getSession().getServletContext();
    
            System.out.println(se.getSession().getId());
    
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(1);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count+1);
            }
    
            ctx.setAttribute("OnlineCount",onlineCount);
    
        }
    
        //銷毀session監聽
        //一旦銷毀Session就會觸發一次這個事件!
        public void sessionDestroyed(HttpSessionEvent se) {
            ServletContext ctx = se.getSession().getServletContext();
    
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(0);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count-1);
            }
    
            ctx.setAttribute("OnlineCount",onlineCount);
    
        }
    
    
        /*
        Session銷毀:
        1. 手動銷毀  getSession().invalidate();
        2. 自動銷毀
         */
    }
    
  2. web.xml中註冊監聽器

    <!--註冊監聽器-->
    <listener>
        <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
    </listener>
  3. 看情況是否使用!

13、過濾器、監聽器常見應用

監聽器:GUI編程中經常使用;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("中秋節快樂");  //新建一個窗體
        Panel panel = new Panel(null); //面板
        frame.setLayout(null); //設置窗體的佈局

        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255)); //設置背景顏色

        panel.setBounds(50,50,300,300);
        panel.setBackground(new Color(0,255,0)); //設置背景顏色

        frame.add(panel);

        frame.setVisible(true);

        //監聽事件,監聽關閉事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
            }
        });


    }
}

用戶登錄之後才能進入主頁!用戶註銷後就不能進入主頁了!

  1. 用戶登錄之後,向Sesison中放入用戶的數據

  2. 進入主頁的時候要判斷用戶是否已經登錄;要求:在過濾器中實現!

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    
    if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
        response.sendRedirect("/error.jsp");
    }
    
    chain.doFilter(request,response);

14、JDBC

什麼是JDBC : Java連接資料庫!

需要jar包的支持:

  • java.sql
  • javax.sql
  • mysql-conneter-java… 連接驅動(必須要導入)

實驗環境搭建

CREATE TABLE users(
    id INT PRIMARY KEY,
    `name` VARCHAR(40),
    `password` VARCHAR(40),
    email VARCHAR(60),
    birthday DATE
);

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'張三','123456','[email protected]','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','[email protected]','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','[email protected]','2000-01-01');


SELECT  * FROM users;

導入資料庫依賴

<!--mysql的驅動-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

IDEA中連接資料庫:

JDBC 固定步驟:

  1. 載入驅動
  2. 連接資料庫,代表資料庫
  3. 向資料庫發送SQL的對象Statement : CRUD
  4. 編寫SQL (根據業務,不同的SQL)
  5. 執行SQL
  6. 關閉連接
public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解決中文亂碼
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.載入驅動
        Class.forName("com.mysql.jdbc.Driver");
        //2.連接資料庫,代表資料庫
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.向資料庫發送SQL的對象Statement,PreparedStatement : CRUD
        Statement statement = connection.createStatement();

        //4.編寫SQL
        String sql = "select * from users";

        //5.執行查詢SQL,返回一個 ResultSet  : 結果集
        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()){
            System.out.println("id="+rs.getObject("id"));
            System.out.println("name="+rs.getObject("name"));
            System.out.println("password="+rs.getObject("password"));
            System.out.println("email="+rs.getObject("email"));
            System.out.println("birthday="+rs.getObject("birthday"));
        }

        //6.關閉連接,釋放資源(一定要做) 先開後關
        rs.close();
        statement.close();
        connection.close();
    }
}

預編譯SQL

public class TestJDBC2 {
    public static void main(String[] args) throws Exception {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解決中文亂碼
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.載入驅動
        Class.forName("com.mysql.jdbc.Driver");
        //2.連接資料庫,代表資料庫
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.編寫SQL
        String sql = "insert into  users(id, name, password, email, birthday) values (?,?,?,?,?);";

        //4.預編譯
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,2);//給第一個占位符? 的值賦值為1;
        preparedStatement.setString(2,"狂神說Java");//給第二個占位符? 的值賦值為狂神說Java;
        preparedStatement.setString(3,"123456");//給第三個占位符? 的值賦值為123456;
        preparedStatement.setString(4,"[email protected]");//給第四個占位符? 的值賦值為1;
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//給第五個占位符? 的值賦值為new Date(new java.util.Date().getTime());

        //5.執行SQL
        int i = preparedStatement.executeUpdate();

        if (i>0){
            System.out.println("插入成功@");
        }

        //6.關閉連接,釋放資源(一定要做) 先開後關
        preparedStatement.close();
        connection.close();
    }
}

事務

要麼都成功,要麼都失敗!

ACID原則:保證數據的安全。

開啟事務
事務提交  commit()
事務回滾  rollback()
關閉事務

轉賬:
A:1000
B:1000
    
A(900)   --100-->   B(1100) 

Junit單元測試

依賴

<!--單元測試-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

簡單使用

@Test註解只有在方法上有效,只要加了這個註解的方法,就可以直接運行!

@Test
public void test(){
    System.out.println("Hello");
}

失敗的時候是紅色:

搭建一個環境

CREATE TABLE account(
   id INT PRIMARY KEY AUTO_INCREMENT,
   `name` VARCHAR(40),
   money FLOAT
);

INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
    @Test
    public void test() {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解決中文亂碼
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        Connection connection = null;

        //1.載入驅動
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2.連接資料庫,代表資料庫
             connection = DriverManager.getConnection(url, username, password);

            //3.通知資料庫開啟事務,false 開啟
            connection.setAutoCommit(false);

            String sql = "update account set money = money-100 where name = 'A'";
            connection.prepareStatement(sql).executeUpdate();

            //製造錯誤
            //int i = 1/0;

            String sql2 = "update account set money = money+100 where name = 'B'";
            connection.prepareStatement(sql2).executeUpdate();

            connection.commit();//以上兩條SQL都執行成功了,就提交事務!
            System.out.println("success");
        } catch (Exception e) {
            try {
                //如果出現異常,就通知資料庫回滾事務
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 面向對象三大特性 封裝: Encapsulation是指一種將抽象性函式介面的實現細節部份包裝、隱藏起來的方法。封裝可以被認為是一個保護屏障,防止該類的代碼和數據被外部類定義的代碼隨意訪問。要訪問該類的代碼和數據,必須通過嚴格的介面控制。封裝最主要的功能在於我們能修改自己的實現代碼,而不用修改那些調 ...
  • 一、List集合 1.List集合存儲元素的特點: (1)有序(List集合中存儲有下標)​:存進去是這樣的順序,取出來還是按照這個順序取出​。 (2)可重覆 2.深入ListJ集合 ArrayList集合底層是數組,數組​是有下標的;所以ArrayList集合有很多自己的特性​;ArrayList ...
  • 開發環境: Windows操作系統開發工具: MyEclipse+Jdk+Tomcat+MySQL資料庫運行效果圖 源碼及原文鏈接:https://javadao.xyz/forum.php?mod=viewthread&tid=45 ...
  • 開發環境: Windows操作系統開發工具: Myeclipse+Jdk+Tomcat+MySQL資料庫運行效果圖 源碼及原文鏈接:https://javadao.xyz/forum.php?mod=viewthread&tid=44 ...
  • 原創聲明 本文作者:黃小斜 轉載請務必在文章開頭註明出處和作者。 本文思維導圖 什麼是演算法 上回我們有一篇文章,講述了作為一個新人程式員,如何學習數據結構這門課程,其實呢,數據結構和演算法是息息相關的,為什麼這麼說呢,因為數據結構本身只是一個載體,而在數據結構之上產生作用和輸出價值的東西其實是演算法。 ...
  • 關註公眾號:CoderBuff,回覆“redis”獲取《Redis5.x入門教程》完整版PDF。 《Redis5.x入門教程》目錄 "第一章 · 準備工作" "第二章 · 數據類型" 第三章 · ​命令 第四章 ​· 配置 第五章 · Java客戶端(上) 第六章 · 事務 第七章 · 分散式鎖 第 ...
  • Java基礎 多線程 多個線程一起做同一件事情,縮短時間,提升效率 提高資源利用率 加快程式響應,提升用戶體驗 創建線程 1. 繼承Thread類 步驟 繼承Thread類,重寫run方法 調用的時候,直接new一個對象,然後調start()方法啟動線程 特點 由於是繼承方式,所以不建議使用,因為J ...
  • 1.Object類 equals方法 2.Date類 構造方法 成員方法 DateFormat類 Calendar類 3.System類 StringBuilder原理 構造方法 toString方法 4.包裝類 裝箱&拆箱 自動裝箱&自動拆箱 基本類型和字元串類型的 轉換 5.Collection ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...