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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...