主頁 > 後端開發 > 重溫Java Web的技術細節

重溫Java Web的技術細節

2020-09-14 09:56:24 後端開發

[toc]

一、背景

  • Java Servlet可以說是一項非常久遠的技術了,甚至可以說是Java Web應用的起源,也就是說真正了解了這項技術的原理與實作細節,我們就掌握了Java Web的基礎,也對以后能上手基于Java Servlet的框架起到事半功倍的作用,
  • 本文旨在重溫與Java Servlet密切相關的一些技術細節,

二、請求與回應

  • Servlet的核心任務是處理請求Request,并給出回應Response,這也是Servlet存在的真正意義, 在這里插入圖片描述

2.1、Http請求

  • 在Java Web應用開發中,99.999%用到的都是Http請求
/** 
* Servlet處理HTTP GET/POST請求
*/
public class HttpServletDemo extends HttpServlet {
	
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
	   ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp {
		...
    }
 }
  • HTTP存在GET/POST請求,Servlet是如何分辨的呢?

    • GET請求,請求的資料會附在URL之后(就是把資料放置在HTTP協議頭中),以?分割URL和傳輸資料,多個引數用&連接
    • POST請求:把提交的資料放置在是HTTP包的Body中,
## GET和POST請求的區別

# GET請求
GET /books/?name=computer&num=1 HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
# 注意最后一行是空行

# POST請求
POST /books/add HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
Connection: Keep-Alive
# 以下是POST請求Body
name=computer&num=1
  • HttpServlet類中的Service方法根據Http請求的型別GET/POST分別呼叫doGet或doPost
/**
* HttpServlet類Service方法
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
      	
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }
    }
  • 對于Http Request請求,我們還需要理解冪等的概念:對同一個系統,使用同樣的條件,一次請求和重復的多次請求對系統資源的影響是一致的,
  • 根據以上定義,我們認為GET請求一般情況下是冪等的(GET請求不會引起服務資源的變更),而POST請求是非冪等的(POST請求會提交資料并造成資料更改,造成不可逆,比如多次POST提交訂單資料),
  • Servlet可以通過API獲取到Http請求的相關資料
API 備注
request.getParameter("引數名") 根據引數名獲取引數值(注意,只能獲取一個值的引數)
request.getParameterValue("引數名“) 根據引數名獲取引數值(可以獲取多個值的引數)
request.getMethod 獲取Http請求方式
request.getHeader("User-Agent") 獲取用臺瀏覽器資訊
request.getCookies 獲取與請求相關的Cookies
request.getSession 獲取與用戶相關的會話
... ...

2.2、Http回應

  • 回應是為了向用戶發送資料,Servlet需要處理的是封裝成Http回應訊息的HttpServletResponse物件,
  • Http回應一般回傳給瀏覽器HTML頁面,再由瀏覽器決議HTML呈現給用戶, 在這里插入圖片描述
  • 但Http回應發送HTML頁面并不是全部,比如用戶需要通過網站下載某個檔案,那Http回應需要回傳位元組流,
protected void doGet(HttpServletRequest req, HttpServletResponse resp){
		// 這是一個位元組流
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-disposition", "attachment;filename=" + filename);

        InputStream fis = this.getClass().getResourceAsStream("download.xlsx");
        OutputStream os = resp.getOutputStream();
        byte[] bis = new byte[1024];
        while (-1 != fis.read(bis)) {
            os.write(bis);
        }
}
  • Servlet設定Http回應頭控制瀏覽器的行為
//設定refresh回應頭控制瀏覽器每隔1秒鐘重繪一次
response.setHeader("refresh", "1");

//可分別通過三種方式禁止快取當前檔案內容
response.setDateHeader("expries", -1);

response.setHeader("Cache-Control", "no-cache");

response.setHeader("Pragma", "no-cache")

// 重定向:收到客戶端請求后,通知客戶端去訪問另外一個web資源
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
     // 通過sendRedirect方法實作請求重定向
     resp.sendRedirect(req.getContextPath() + "/welcome.jsp");
}
// 請求分派
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
  req.getRequestDispatcher("/result.jsp").forward(req,resp);
}
  • Servlet與HTTP 狀態碼
代碼 訊息 描述
200 OK 請求成功,
401 Unauthorized 所請求的頁面需要授權
404 Not Found 服務器無法找到所請求的頁面,
500 Internal Server Error 未完成的請求,服務器遇到了一個意外的情況
... ... ...
// 回傳HTTP 500狀態碼
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
  resp.sendError(500);
}

在這里插入圖片描述


三、ServletConfig

  • 在每個Servlet運行時,有可能需要一些初始化引數,比如,檔案使用的編碼,共享的資源資訊等,
  • 這些初始化引數可以在 web.xml 檔案中使用一個或多個 <init-param> 元素進行描述配置,當 容器 初始化一個 Servlet 時,會將該 Servlet 的配置資訊封裝,并通過 init(ServletConfig)方法將 ServletConfig 物件的參考傳遞給 Servlet, 在這里插入圖片描述

3.1 測驗ServletConfig引數

  • 在web.xml中進行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
	<servlet>
         <servlet-name>http-demo</servlet-name>
         <servlet-class>demo.servlet.HttpServletDemo</servlet-class>
		  <!-- 設定該servlet的管理員郵箱地址 -->
          <init-param>
              <param-name>adminEmail</param-name>
              <param-value>[email protected]</param-value>
          </init-param>
     </servlet>
</web-app>
		
  • 在servlet代碼中進行如下呼叫:
public class HttpServletDemo extends HttpServlet {

    // 重寫Get請求方法,回傳一個表單頁面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("GBK");
        PrintWriter out =resp.getWriter();
        out.println("<html><body>");
        out.println("管理員郵箱:");
        out.println(getServletConfig().getInitParameter("adminEmail"));
        out.println("<br>");
        out.println("</body></html>");
    }
}

在這里插入圖片描述


四、ServletContext

-web應用同樣也需要一些初始化的引數,但 相對于每一個Servlet有一個ServletConfig來說,一個Web應用(確切的說是每個JVM)僅有一個ServletContext來存放這些引數,這個ServletContext對Web應用中的每個Servlet都可用, 在這里插入圖片描述

4.1 測驗ServletContext引數

  • 在web.xml中進行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
         
		<!-- 設定web應用的統一標題欄 -->
        <context-param>
            <param-name>title</param-name>
            <param-value>My-App網站</param-value>
        </context-param>

        <servlet>
            <servlet-name>http-demo</servlet-name>
            <servlet-class>demo.servlet.HttpServletDemo</servlet-class>

            <init-param>
                <param-name>adminEmail</param-name>
                <param-value>[email protected]</param-value>
            </init-param>
        </servlet>

        <servlet-mapping>
            <servlet-name>http-demo</servlet-name>
            <url-pattern>/http-demo</url-pattern>
        </servlet-mapping>
</web-app>
  • 在servlet代碼中進行如下呼叫:
public class HttpServletDemo extends HttpServlet {

    // 重寫Get請求方法,回傳一個表單頁面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        resp.setContentType("text/html");
        resp.setCharacterEncoding("GBK");
        PrintWriter out =resp.getWriter();
        out.println("<html><body>");
        out.println("<title>"+getServletContext().getInitParameter("title")+"</title>");
        out.println("管理員郵箱:");
        out.println(getServletConfig().getInitParameter("adminEmail"));
        out.println("<br>");
        out.println("</body></html>");
    }
 }

在這里插入圖片描述

  • 注意點:
// 在web應用中,以下兩句代碼等價
getServletContext().getInitParameter("title");
getServletConfig().getServletContext().getInitParameter("title");

4.2、ServletContext屬性

  • 通過編程的方式,可以給ServletContext系結屬性,使得web應用中的Servlet物件可以使用該全域屬性,
// 重寫Post請求方法,提交表單上的資料,并回傳結果頁面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer age = Integer.parseInt(req.getParameter("age"));
        if (name != null && age != null) {
            User user = new User(name, age);
            req.setAttribute("name", name);
            req.setAttribute("age", age);
            // 設定提交成功次數屬性,并同步加鎖,防止多執行緒并發例外
            synchronized (getServletContext()) {
                if (user.checkName()) {
                    Long postCount = getServletContext().getAttribute("postCount") == null ? 1L
                            : Long.parseLong(getServletContext().getAttribute("postCount").toString()) + 1L;
                    getServletContext().setAttribute("postCount", postCount);

                    req.setAttribute("result", "登記成功" + "! 總共已有" + postCount + "人數登記!!");
                } else {
                    req.setAttribute("result", "登記失敗:名稱中包含非法字符");
                }
            }
            RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
            view.forward(req, resp);

        }

    }

在這里插入圖片描述 在這里插入圖片描述

  • 屬性與引數的區別
屬性  引數
設定方法 setAttribute(String name,Object value) 只能在web.xml中設定
回傳型別 Object String
獲取方法 getAttribute(String name). getInitParameter(String s)

五、屬性的作用域

  • 除了ServletContext可以設定屬性外,HttpSession會話、HttpServletRequest請求都可以設定和使用屬性,但這三者的作用域是不同的,可參見下表:
屬性作用域 備注
ServletContext web應用存活期間都可以設定并使用屬性;應用關閉背景關系撤消后相應屬性也會消失 各個Servlet都可以使用,但執行緒不安全,一般適在于常量屬性等,比如資料庫連接
HttpSession HttpSession應用存活期間都可以設定并使用屬性;會話超時或被人為撤消后相應屬性也會消失 與會話相關的都可以使用,比如電商網站的購物車屬性
HttpServletRequest 每次請求生成時可設定或使用屬性,直到這個請求在service方法中消失 請求中屬性是執行緒安全的,類似于區域變數

六、HttpSession

  • Session就是為了讓服務器有能力分辨出不同的用戶,
  1. 客戶端在第一次請求時沒有攜帶任何sessionId,服務端Servlet容器就會給客戶端創建一個HttpSession物件 存盤在服務器端,然后給這個物件創建一個sessionID 作為唯一標識,同時 這個sessionID還會放在一個cookie里,通過response回傳客戶端,
  2. 客戶端第二次發出請求,cookie中會攜帶sessionId,servlet容器拿著這個sessionID在服務器端查找對應的HttpSession物件,找到后就直接拿出來使用,
  3. Servlet會為不同的客戶端創建不同的sessionId及session物件,代表不同的狀態,

在這里插入圖片描述

6.1 HttpSession的關鍵方法

  • 關鍵方法
方法 描述
getSession() 獲取Session 物件
setAttribute() 在Session 物件中設定屬性
getAttribute() 在Session 物件中獲取屬性
removeAttribute() 在Session 物件中洗掉屬性
invalidate() 使Session 物件失效
setMaxInactiveInterval() 設定Session 物件最大間隔時間(在這段時間內,客戶端未對這個會話有新的請求操作,該會話就會撤消)

6.2 簡易的購物車使用HttpSession

  • 網站后臺通過會話保存用戶的購物車狀態,用戶在退出網站后在會話的有效時間段內重新進入網站,購物車狀態不消失,

  • web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <context-param>
        <param-name>title</param-name>
        <param-value>購物網站</param-value>
    </context-param>

    <!-- 網站session失效時間為30分鐘 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <!-- 登錄servlet -->
    <servlet>
        <servlet-name>http-demo</servlet-name>
        <servlet-class>demo.servlet.HttpServletDemo</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>http-demo</servlet-name>
        <url-pattern>/http-demo</url-pattern>
    </servlet-mapping>

    <!-- 購物車servlet -->
    <servlet>
        <servlet-name>cart</servlet-name>
        <servlet-class>demo.servlet.CartServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>cart</servlet-name>
        <url-pattern>/cart</url-pattern>
    </servlet-mapping>

</web-app>
  • 購物網站登錄頁面Servlet:
/**
 * 購物網站登錄頁面
 *
 * @author zhuhuix
 * @date 2020-08-28
 */
public class HttpServletDemo extends HttpServlet {
    //static int i=0 ;

    // 重寫Get請求方法,回傳登錄表單頁面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setAttribute("title", getServletContext().getInitParameter("title"));
        req.getRequestDispatcher("/form.jsp").forward(req, resp);

    }

    // 重寫Post請求方法,進行登錄,登錄成功后跳車購物車頁面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer password = Integer.parseInt(req.getParameter("password"));
        if (name != null && password != null) {
            req.getSession().setAttribute("name",name);
            RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
            view.forward(req, resp);
        }
    }
}
  • 購物網站登錄頁面視圖:
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}用戶登錄

<body>

用戶登錄

在這里插入圖片描述

  • 購物車頁面視圖:
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}購物車

<body>

${name}的購物車

貨物 數量
手機
電腦
書本

在這里插入圖片描述

  • 購物車的Servlet:
/**
 * 購物車Servlet
 *
 * @author zhuhuix
 * @date 2020-08-29
 */
public class CartServlet extends javax.servlet.http.HttpServlet {


    // 重寫Post請求方法,提交購物車的資料,并回傳結果頁面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查找頁面上的購物數量,并放入session中

        req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
        req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
        req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));

        RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
        view.forward(req, resp);
    }
}
  • 購物結果視圖頁面:
<!--結果頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}購物結果

<body>

${name}的購物結果

已購貨物 已購數量
手機 ${phoneNumber}
電腦 ${pcNumber}
書本 ${bookNumber}

在這里插入圖片描述

  • HttpSession狀態測驗
  1. 用戶登錄網站后在購物車頁面提交購物結果: 在這里插入圖片描述
  2. 用戶退出網站,重新登錄 后進入購物車頁面,網站后臺將HttpSession中的資料重新調取到頁面進行顯示: 在這里插入圖片描述 在這里插入圖片描述
  • 在web.xml中將會話失效時間改為一分鐘,并重啟網站,進行購物車提交
  <!-- 網站session失效時間為1分鐘 -->
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>

在這里插入圖片描述

  • 退出網站,超過一分鐘后重新登錄,并查看購物車情況 在這里插入圖片描述
  • 購物車已空空如也 在這里插入圖片描述

七、監聽器

  • 監聽器Listener又稱為監聽者,Listener的設計為開發Servlet應用程式提供了一種快捷的手段,能夠方便地從另一個縱向維度控制程式和資料,正所謂旁觀者清在這里插入圖片描述
  • 監聽器采用了觀察者設計模式,監聽范圍包括ServletContext、HttpSession、HttpRequest, 在這里插入圖片描述

7.1 監聽器測驗--在線會話數統計

  • 在web.xml中進行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

        <context-param>
            <param-name>title</param-name>
            <param-value>My-App網站</param-value>
        </context-param>

        <!-- 監聽者 負責監聽HttpSession創建與銷毀-->
        <listener>
            <listener-class>demo.servlet.HttpSessionListenerDemo</listener-class>
        </listener>

        <!-- 登錄servlet -->
        <servlet>
            <servlet-name>http-demo</servlet-name>
            <servlet-class>demo.servlet.HttpServletDemo</servlet-class>

            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>http-demo</servlet-name>
            <url-pattern>/http-demo</url-pattern>
        </servlet-mapping>
    
</web-app>
  • 創建監聽器類:
/**
 * HttpSession監聽器測驗:統計當前服務器在線人數
 */
public class HttpSessionListenerDemo implements javax.servlet.http.HttpSessionListener {
    @Override
    public void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent) {
        SessionStatics.increase();
    }

    @Override
    public void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent) {
        SessionStatics.decrease();
    }
}

/**
 * 計數類
 */
public  class SessionStatics {
    private  static volatile Long count=0L;

    public static void increase(){
        synchronized (SessionStatics.class) {
            count++;
        }
    }

    public static void decrease(){
        synchronized (SessionStatics.class) {
            count--;
        }
    }

    public static Long getCount(){
        return count;
    }
}
  • 創建用戶登錄的servlet代碼:
/**
 * HttpServlet模擬一個登錄頁面
 *
 * @author zhuhuix
 * @date 2020-08-28
 */
public class HttpServletDemo extends HttpServlet {

    // 重寫Get請求方法,回傳一個表單頁面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setAttribute("title", getServletContext().getInitParameter("title"));
        req.getRequestDispatcher("/form.jsp").forward(req, resp);

    }

    // 重寫Post請求方法,提交表單上的資料,并回傳結果頁面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer password = Integer.parseInt(req.getParameter("password"));
        if (name != null && password != null) {
            // checkUserAndPassword
            req.setAttribute("name", name);

            req.setAttribute("result","登錄成功,當前在線人數:"+SessionStatics.getCount());

            RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
            view.forward(req, resp);
        }
    }
}
  • 設計用戶登錄與登錄結果的視圖頁面:
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}用戶登錄

<body>

用戶登錄

<!--結果頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}登錄結果

<body>

登錄結果

  • 結果演示: 在這里插入圖片描述 在這里插入圖片描述 在這里插入圖片描述 在這里插入圖片描述

7.2 特殊的監聽器

  • HttpSessionBindingListener監聽器可以JavaBean物件感知自己被系結到Session中和從Session中洗掉;且該監聽器不需要在web.xml宣告,
public class User implements javax.servlet.http.HttpSessionBindingListener {
    private String name;

    public User(String name){
        this.name=name;
    }

    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println(name+"加入session");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println(name+"移出session");
    }
}

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
  		...
        // 測驗HttpSessionBindingListener
        req.getSession().setAttribute("user",new User(name));
}

在這里插入圖片描述


八、過濾器

  • 過濾器Filter允許你攔截請求和回應,通過撰寫和配置一個過濾器,可以完成一些全域性的操作:比如安全驗證、統一編 碼處理、敏感字過濾等,
  • Servlet API中提供了一個Filter介面,開發web應用時,如果撰寫的Java類實作了這個介面,則把這個java類稱之為過濾器Filter,
  • 通過Filter技術,開發人員可以實作用戶在訪問某個目標資源之前,對訪問的請求和回應進行攔截,簡單說,就是可以實作web容器對某資源的訪問前截獲進行相關的處理,還可以在某資源向web容器回傳回應前進行截獲進行處理,

在這里插入圖片描述

8.1 過濾器的使用方法

  • 定義一個類,實作介面Filter,并 重寫Filter介面類的方法;
/**
 * 過濾器例子
 */
public class FilterDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 過濾
        System.out.println("攔截過濾...");
        // 放行請求
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
  • 配置過濾器攔截路徑,
<!-- web.xml -->
    <!-- 過濾器配置 -->
    <filter>
        <filter-name>filterDemo</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <!-- 攔截路徑 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

8.2 過濾器的執行流程

  • 當Web容器接受到一個對資源路徑的請求時,會判斷是否有過濾器與這個資源路徑相關聯,如果有,就把請求交給過濾器進行處理,
  • 在過濾器程式中,可以改變請求的內容,或者重新設定請求的頭資訊等操作,然后對請求放行發送給對應目標資源;當目標資源完成回應后,容器再次會將回應轉發給過濾器,這時候可以對回應的內容進行處理,然后再將回應發送到客戶端., 在這里插入圖片描述
	@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 前置過濾
        System.out.println("攔截過濾{pre}");
        // 放行請求
        filterChain.doFilter(servletRequest,servletResponse);
        // 后置過濾
        System.out.println("攔截過濾{post}");
    }

在這里插入圖片描述

8.3 過濾器的生命周期

  1. 初始化init:服務器啟動時,進行創建Filter物件,然后呼叫init方法;該程序只執行一次,一般用于加載資源,
  2. 攔截過濾doFilter:每一次請求被都會被執行,
  3. 銷毀destroy:服務器正常關閉時,Filter物件會被銷毀,該程序只執行一次,一般用于釋放資源,

8.4 過濾器的攔截配置

  • 攔截路徑配置:
  1. 攔截具體資源:比如/index.jsp,只有訪問index.jsp資源時,過濾器才會執行,
  2. 攔截網站目錄:/demo ,訪問網站的demo目錄下的資源時,過濾器才會執行,
  3. 后綴名攔截:比如 *.jsp,訪問所有后綴名為jsp資源時,過濾器會執行,
  4. 攔截所有資源:比如/*,訪問網站下所有資源時,過濾器都會執行,
	<!-- 攔截具體資源 -->
 	<filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/form.jsp</url-pattern>
    </filter-mapping>
	<!-- 攔截網站目錄 -->
    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/demo</url-pattern>
    </filter-mapping>
	<!-- 后綴名攔截 -->
    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
	<!-- 攔截所有資源 -->
    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • 攔截方式配置:
  1. REQUEST : 瀏覽器直接請求時,過濾器才會執行,
  2. FORWARD: 只有轉發訪問時,過濾器才會執行,
  3. INCLUDE:包含訪問資源時,過濾器才會執行,
  4. ERROR:錯誤跳轉資源時,過濾器才會執行,
  5. ASYNC:異步訪問資源時,過濾器才會執行,
 <!-- 過濾器配置 -->
    <filter>
        <filter-name>filterDemo</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/http-demo</url-pattern>
        <!-- 瀏覽器直接請求時,過濾器會執行 -->
        <dispatcher>REQUEST</dispatcher>
        <!-- 轉發請求時,過濾器會執行 -->
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

8.5 過濾器鏈

  • 過濾器可以鏈到一起,一個接一個地運行, 在這里插入圖片描述
  • 在web.xml中,哪個過濾器的filter-mapping先配置,則哪個過濾器先執行
<!-- 過濾器配置  -->
    <filter>
        <filter-name>filterDemo1</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>
    <!-- 哪個過濾器的filter-mapping先配置,則哪個過濾器先執行-->
    <filter-mapping>
        <filter-name>filterDemo1</filter-name>
        <url-pattern>/http-demo</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>filterDemo2</filter-name>
        <filter-class>demo.filter.FilterDemo2</filter-class>
    </filter>
    <!-- 哪個過濾器的filter-mapping后配置,則哪個過濾器后執行-->
    <filter-mapping>
        <filter-name>filterDemo2</filter-name>
        <url-pattern>/http-demo</url-pattern>
    </filter-mapping>

在這里插入圖片描述

8.5 過濾器的案例--登錄驗證

  • 專案結構 在這里插入圖片描述
  • web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <context-param>
        <param-name>title</param-name>
        <param-value>購物網站</param-value>
    </context-param>

    <!-- 過濾器配置  -->
    <filter>
        <filter-name>loginFilter</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- 登錄驗證servlet -->
    <servlet>
        <servlet-name>loginServlet</servlet-name>
        <servlet-class>demo.servlet.LoginServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <!-- 購物車servlet -->
    <servlet>
        <servlet-name>cart</servlet-name>
        <servlet-class>demo.servlet.CartServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>cart</servlet-name>
        <url-pattern>/cart</url-pattern>
    </servlet-mapping>

</web-app>
  • 登錄程式
/**
 * 購物網站登錄頁面
 *
 * @author zhuhuix
 * @date 2020-08-30
 */
public class LoginServlet extends HttpServlet {

    // 重寫Get請求方法,回傳一個登錄頁面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setAttribute("title", getServletContext().getInitParameter("title"));
        req.getRequestDispatcher("/form.jsp").forward(req, resp);

    }

    // 重寫Post請求方法,提交用戶名與密碼
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer password = Integer.parseInt(req.getParameter("password"));
        if (name != null && password != null) {
            // 用戶登錄驗證通過后,設定用戶名稱屬性
            req.getSession().setAttribute("name",name);
            RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
            view.forward(req, resp);
        }

    }
}
  • 登錄頁面
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}用戶登錄

<body>

用戶登錄

在這里插入圖片描述

  • 購物車程式
/**
 * 購物車Servlet
 *
 * @author zhuhuix
 * @date 2020-08-29
 */
public class CartServlet extends javax.servlet.http.HttpServlet {


    // 重寫Post請求方法,提交購物車的資料,并回傳結果頁面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查找頁面上的購物數量,并放入session中

        req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
        req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
        req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));

        RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
        view.forward(req, resp);
    }
}
  • 購物車頁面
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href=https://www.cnblogs.com/zhuhuix/p/"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    ${title}購物車

<body>

${name}的購物車

貨物 數量
手機
電腦
書本

在這里插入圖片描述

  • 程式測驗
  1. 訪問購物車頁面:由于用戶未登錄,則會跳轉到登錄頁面 在這里插入圖片描述

  2. 用戶輸入用戶名和密碼后進行登錄,登錄成功后會跳轉到購物車頁面, 在這里插入圖片描述 在這里插入圖片描述

  3. 用戶進行購物,并提交購物結果 在這里插入圖片描述 在這里插入圖片描述

  4. 退出頁面,在瀏覽器中再次訪問購物車頁面,可以看到過濾器判斷到用戶會話存在,已處于登錄狀態,直接跳轉到購物車頁面

在這里插入圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/33591.html

標籤:Java

上一篇:歸納從檔案中讀取資料的六種方法-JAVA IO基礎總結第2篇

下一篇:Struts+Servlet+JDBC網上手機銷售系統

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more