JavaWeb


內容來自B站狂神說Java,為方便查看而上傳,直通車:https://space.bilibili.com/95256449

JavaWeb

Java Web

1、基本概念

1.1、前言

web開發:

  • web,網頁的意思 , www.baidu.com
  • 靜態web
    • html,css
    • 提供給所有人看的數據始終不會發生變化!
  • 動態web
    • 淘寶,幾乎是所有的網站;
    • 提供給所有人看的數據始終會發生變化,每個人在不同的時間,不同的地點看到的信息各不相同!
    • 技術棧:Servlet/JSP,ASP,PHP

在Java中,動態web資源開發的技術統稱為JavaWeb;

1.2、web應用程序

web應用程序:可以提供瀏覽器訪問的程序;

  • a.html、b.html......多個web資源,這些web資源可以被外界訪問,對外界提供服務;
  • 你們能訪問到的任何一個頁面或者資源,都存在於這個世界的某一個角落的計算機上。
  • URL
  • 這個統一的web資源會被放在同一個文件夾下,web應用程序-->Tomcat:服務器
  • 一個web應用由多部分組成 (靜態web,動態web)
    • html,css,js
    • jsp,servlet
    • Java程序
    • jar包
    • 配置文件 (Properties)

web應用程序編寫完畢后,若想提供給外界訪問:需要一個服務器來統一管理;

1.3、靜態web

  • *.htm, *.html,這些都是網頁的后綴,如果服務器上一直存在這些東西,我們就可以直接進行讀取。通絡;

1567822802516

  • 靜態web存在的缺點
    • Web頁面無法動態更新,所有用戶看到都是同一個頁面
      • 輪播圖,點擊特效:偽動態
      • JavaScript [實際開發中,它用的最多]
      • VBScript
    • 它無法和數據庫交互(數據無法持久化,用戶無法交互)

1.4、動態web

頁面會動態展示: “Web的頁面展示的效果因人而異”;

1567823191289

缺點:

  • 加入服務器的動態web資源出現了錯誤,我們需要重新編寫我們的后台程序,重新發布;
    • 停機維護

優點:

  • Web頁面可以動態更新,所有用戶看到都不是同一個頁面
  • 它可以與數據庫交互 (數據持久化:注冊,商品信息,用戶信息........)

1567823350584

新手村:--魔鬼訓練(分析原理,看源碼)--> PK場

2、web服務器

2.1、技術講解

ASP:

  • 微軟:國內最早流行的就是ASP;

  • 在HTML中嵌入了VB的腳本, ASP + COM;

  • 在ASP開發中,基本一個頁面都有幾千行的業務代碼,頁面極其換亂

  • 維護成本高!

  • C#

  • IIS

    <h1>
        <h1><h1>
            <h1>
                <h1>
                    <h1>
            <h1>
                <%
                System.out.println("hello")
                %>
                <h1>
                    <h1>
       <h1><h1>
    <h1>
    

php:

  • PHP開發速度很快,功能很強大,跨平台,代碼很簡單 (70% , WP)
  • 無法承載大訪問量的情況(局限性)

**JSP/Servlet : **

B/S:瀏覽和服務器

C/S: 客戶端和服務器

  • sun公司主推的B/S架構
  • 基於Java語言的 (所有的大公司,或者一些開源的組件,都是用Java寫的)
  • 可以承載三高問題帶來的影響;
  • 語法像ASP , ASP-->JSP , 加強市場強度;

.....

2.2、web服務器

服務器是一種被動的操作,用來處理用戶的一些請求和給用戶一些響應信息;

IIS

微軟的; ASP...,Windows中自帶的

Tomcat

1567824446428

面向百度編程;

Tomcat是Apache 軟件基金會(Apache Software Foundation)的Jakarta 項目中的一個核心項目,最新的Servlet 和JSP 規范總是能在Tomcat 中得到體現,因為Tomcat 技術先進、性能穩定,而且免費,因而深受Java 愛好者的喜愛並得到了部分軟件開發商的認可,成為目前比較流行的Web 應用服務器。

Tomcat 服務器是一個免費的開放源代碼的Web 應用服務器,屬於輕量級應用服務器,在中小型系統和並發訪問用戶不是很多的場合下被普遍使用,是開發和調試JSP 程序的首選。對於一個Java初學web的人來說,它是最佳的選擇

Tomcat 實際上運行JSP 頁面和Servlet。Tomcat最新版本為9.0。

....

工作3-5年之后,可以嘗試手寫Tomcat服務器;

下載tomcat:

  1. 安裝 or 解壓
  2. 了解配置文件及目錄結構
  3. 這個東西的作用

3、Tomcat

3.1、 安裝tomcat

tomcat官網:http://tomcat.apache.org/

1567825600842

1567825627138

3.2、Tomcat啟動和配置

文件夾作用:

1567825763180

啟動。關閉Tomcat

1567825840657

訪問測試:http://localhost:8080/

可能遇到的問題:

  1. Java環境變量沒有配置
  2. 閃退問題:需要配置兼容性
  3. 亂碼問題:配置文件中設置

3.3、配置

1567825967256

可以配置啟動的端口號

  • tomcat的默認端口號為:8080
  • mysql:3306
  • http:80
  • https:443
<Connector port="8081" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />

可以配置主機的名稱

  • 默認的主機名為:localhost->127.0.0.1
  • 默認網站應用存放的位置為:webapps
  <Host name="www.qinjiang.com"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

高難度面試題:

請你談談網站是如何進行訪問的!

  1. 輸入一個域名;回車

  2. 檢查本機的 C:\Windows\System32\drivers\etc\hosts配置文件下有沒有這個域名映射;

    1. 有:直接返回對應的ip地址,這個地址中,有我們需要訪問的web程序,可以直接訪問

      127.0.0.1       www.qinjiang.com
      
    2. 沒有:去DNS服務器找,找到的話就返回,找不到就返回找不到;

    1567827057913

  3. 可以配置一下環境變量(可選性)

3.4、發布一個web網站

不會就先模仿

  • 將自己寫的網站,放到服務器(Tomcat)中指定的web應用的文件夾(webapps)下,就可以訪問了

網站應該有的結構

--webapps :Tomcat服務器的web目錄
	-ROOT
	-kuangstudy :網站的目錄名
		- WEB-INF
			-classes : java程序
			-lib:web應用所依賴的jar包
			-web.xml :網站配置文件
		- index.html 默認的首頁
		- static 
            -css
            	-style.css
            -js
            -img
         -.....

HTTP協議 : 面試

Maven:構建工具

  • Maven安裝包

Servlet 入門

  • HelloWorld!
  • Servlet配置
  • 原理

4、Http

4.1、什么是HTTP

HTTP(超文本傳輸協議)是一個簡單的請求-響應協議,它通常運行在TCP之上。

  • 文本:html,字符串,~ ….
  • 超文本:圖片,音樂,視頻,定位,地圖…….
  • 80

Https:安全的

  • 443

4.2、兩個時代

  • http1.0

    • HTTP/1.0:客戶端可以與web服務器連接后,只能獲得一個web資源,斷開連接
  • http2.0

    • HTTP/1.1:客戶端可以與web服務器連接后,可以獲得多個web資源。‘

4.3、Http請求

  • 客戶端---發請求(Request)---服務器

百度:

Request URL:https://www.baidu.com/   請求地址
Request Method:GET    get方法/post方法
Status Code:200 OK    狀態碼:200
Remote(遠程) Address:14.215.177.39:443
Accept:text/html  
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9    語言
Cache-Control:max-age=0
Connection:keep-alive

1、請求行

  • 請求行中的請求方式:GET
  • 請求方式:Get,Post,HEAD,DELETE,PUT,TRACT…
    • get:請求能夠攜帶的參數比較少,大小有限制,會在瀏覽器的URL地址欄顯示數據內容,不安全,但高效
    • post:請求能夠攜帶的參數沒有限制,大小沒有限制,不會在瀏覽器的URL地址欄顯示數據內容,安全,但不高效。

2、消息頭

Accept:告訴瀏覽器,它所支持的數據類型
Accept-Encoding:支持哪種編碼格式  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language:告訴瀏覽器,它的語言環境
Cache-Control:緩存控制
Connection:告訴瀏覽器,請求完成是斷開還是保持連接
HOST:主機..../.

4.4、Http響應

  • 服務器---響應-----客戶端

百度:

Cache-Control:private    緩存控制
Connection:Keep-Alive    連接
Content-Encoding:gzip    編碼
Content-Type:text/html   類型

1.響應體

Accept:告訴瀏覽器,它所支持的數據類型
Accept-Encoding:支持哪種編碼格式  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language:告訴瀏覽器,它的語言環境
Cache-Control:緩存控制
Connection:告訴瀏覽器,請求完成是斷開還是保持連接
HOST:主機..../.
Refresh:告訴客戶端,多久刷新一次;
Location:讓網頁重新定位;

2、響應狀態碼

200:請求響應成功 200

3xx:請求重定向

  • 重定向:你重新到我給你新位置去;

4xx:找不到資源 404

  • 資源不存在;

5xx:服務器代碼錯誤 500 502:網關錯誤

常見面試題:

當你的瀏覽器中地址欄輸入地址並回車的一瞬間到頁面能夠展示回來,經歷了什么?

5、Maven

我為什么要學習這個技術?

  1. 在Javaweb開發中,需要使用大量的jar包,我們手動去導入;

  2. 如何能夠讓一個東西自動幫我導入和配置這個jar包。

    由此,Maven誕生了!

5.1 Maven項目架構管理工具

我們目前用來就是方便導入jar包的!

Maven的核心思想:約定大於配置

  • 有約束,不要去違反。

Maven會規定好你該如何去編寫我們的Java代碼,必須要按照這個規范來;

5.2 下載安裝Maven

官網;https://maven.apache.org/

1567842350606

下載完成后,解壓即可;

小狂神友情建議:電腦上的所有環境都放在一個文件夾下,方便管理;

5.3 配置環境變量

在我們的系統環境變量中

配置如下配置:

  • M2_HOME maven目錄下的bin目錄
  • MAVEN_HOME maven的目錄
  • 在系統的path中配置 %MAVEN_HOME%\bin

1567842882993

測試Maven是否安裝成功,保證必須配置完畢!

5.4 阿里雲鏡像

1567844609399

  • 鏡像:mirrors
    • 作用:加速我們的下載
  • 國內建議使用阿里雲的鏡像
<mirror>
    <id>nexus-aliyun</id>  
    <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>  
    <name>Nexus aliyun</name>  
    <url>http://maven.aliyun.com/nexus/content/groups/public</url> 
</mirror>

5.5 本地倉庫

在本地的倉庫,遠程倉庫;

建立一個本地倉庫:localRepository

<localRepository>D:\Environment\apache-maven-3.6.2\maven-repo</localRepository>

5.6、在IDEA中使用Maven

  1. 啟動IDEA

  2. 創建一個MavenWeb項目

    1567844785602

    1567844841172

    1567844917185

    1567844956177

    1567845029864

  3. 等待項目初始化完畢

    1567845105970

    1567845137978

  4. 觀察maven倉庫中多了什么東西?

  5. IDEA中的Maven設置

    注意:IDEA項目創建成功后,看一眼Maven的配置

    1567845341956

    1567845413672

  6. 到這里,Maven在IDEA中的配置和使用就OK了!

5.7、創建一個普通的Maven項目

1567845557744

1567845717377

這個只有在Web應用下才會有!

1567845782034

5.8 標記文件夾功能

1567845910728

1567845957139

1567846034906

1567846073511

5.9 在 IDEA中配置Tomcat

1567846140348

1567846179573

1567846234175

1567846369751

解決警告問題

必須要的配置:為什么會有這個問題:我們訪問一個網站,需要指定一個文件夾名字;

1567846421963

1567846546465

1567846559111

1567846640372

5.10 pom文件

pom.xml 是Maven的核心配置文件

1567846784849

<?xml version="1.0" encoding="UTF-8"?>

<!--Maven版本和頭文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <!--這里就是我們剛才配置的GAV-->
  <groupId>com.kuang</groupId>
  <artifactId>javaweb-01-maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <!--Package:項目的打包方式
  jar:java應用
  war:JavaWeb應用
  -->
  <packaging>war</packaging>


  <!--配置-->
  <properties>
    <!--項目的默認構建編碼-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!--編碼版本-->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <!--項目依賴-->
  <dependencies>
    <!--具體依賴的jar包配置文件-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
  </dependencies>

  <!--項目構建用的東西-->
  <build>
    <finalName>javaweb-01-maven</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

1567847410771

maven由於他的約定大於配置,我們之后可以能遇到我們寫的配置文件,無法被導出或者生效的問題,解決方案:

<!--在build中配置resources,來防止我們資源導出失敗的問題-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

5.12 IDEA操作

1567847630808

1567847662429

5.13 解決遇到的問題

  1. Maven 3.6.2

    解決方法:降級為3.6.1

    1567904721301

  2. Tomcat閃退

  3. IDEA中每次都要重復配置Maven
    在IDEA中的全局默認配置中去配置

    1567905247201

    1567905291002

  4. Maven項目中Tomcat無法配置

  5. maven默認web項目中的web.xml版本問題

    1567905537026

  6. 替換為webapp4.0版本和tomcat一致

    <?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"
             metadata-complete="true">
    
    
    
    </web-app>
    
  7. Maven倉庫的使用

    地址:https://mvnrepository.com/

    1567905870750

    1567905982979

    1567906017448

    1567906039469

6、Servlet

6.1、Servlet簡介

  • Servlet就是sun公司開發動態web的一門技術
  • Sun在這些API中提供一個接口叫做:Servlet,如果你想開發一個Servlet程序,只需要完成兩個小步驟:
    • 編寫一個類,實現Servlet接口
    • 把開發好的Java類部署到web服務器中。

把實現了Servlet接口的Java程序叫做,Servlet

6.2、HelloServlet

Serlvet接口Sun公司有兩個默認的實現類:HttpServlet,GenericServlet

  1. 構建一個普通的Maven項目,刪掉里面的src目錄,以后我們的學習就在這個項目里面建立Moudel;這個空的工程就是Maven主工程;

  2. 關於Maven父子工程的理解:

    父項目中會有

        <modules>
            <module>servlet-01</module>
        </modules>
    

    子項目會有

        <parent>
            <artifactId>javaweb-02-servlet</artifactId>
            <groupId>com.kuang</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
    

    父項目中的java子項目可以直接使用

    son extends father
    
  3. Maven環境優化

    1. 修改web.xml為最新的
    2. 將maven的結構搭建完整
  4. 編寫一個Servlet程序

    1567911804700

    1. 編寫一個普通類

    2. 實現Servlet接口,這里我們直接繼承HttpServlet

      public class HelloServlet extends HttpServlet {
          
          //由於get或者post只是請求實現的不同的方式,可以相互調用,業務邏輯都一樣;
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              //ServletOutputStream outputStream = resp.getOutputStream();
              PrintWriter writer = resp.getWriter(); //響應流
              writer.print("Hello,Serlvet");
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              doGet(req, resp);
          }
      }
      
      
  5. 編寫Servlet的映射

    為什么需要映射:我們寫的是JAVA程序,但是要通過瀏覽器訪問,而瀏覽器需要連接web服務器,所以我們需要再web服務中注冊我們寫的Servlet,還需給他一個瀏覽器能夠訪問的路徑;

    
        <!--注冊Servlet-->
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
        </servlet>
        <!--Servlet的請求路徑-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
    
  6. 配置Tomcat

    注意:配置項目發布的路徑就可以了

  7. 啟動測試,OK!

6.3、Servlet原理

Servlet是由Web服務器調用,web服務器在收到瀏覽器請求之后,會:

1567913793252

6.4、Mapping問題

  1. 一個Servlet可以指定一個映射路徑

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  2. 一個Servlet可以指定多個映射路徑

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello2</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello3</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello4</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello5</url-pattern>
        </servlet-mapping>
    
    
  3. 一個Servlet可以指定通用映射路徑

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello/*</url-pattern>
        </servlet-mapping>
    
  4. 默認請求路徑

        <!--默認請求路徑-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    
  5. 指定一些后綴或者前綴等等….

    
    <!--可以自定義后綴實現請求映射
        注意點,*前面不能加項目映射的路徑
        hello/sajdlkajda.qinjiang
        -->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.qinjiang</url-pattern>
    </servlet-mapping>
    
  6. 優先級問題
    指定了固有的映射路徑優先級最高,如果找不到就會走默認的處理請求;

    <!--404-->
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>error</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    
    

6.5、ServletContext

web容器在啟動的時候,它會為每個web程序都創建一個對應的ServletContext對象,它代表了當前的web應用;

1、共享數據

我在這個Servlet中保存的數據,可以在另外一個servlet中拿到;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        //this.getInitParameter()   初始化參數
        //this.getServletConfig()   Servlet配置
        //this.getServletContext()  Servlet上下文
        ServletContext context = this.getServletContext();

        String username = "秦疆"; //數據
        context.setAttribute("username",username); //將一個數據保存在了ServletContext中,名字為:username 。值 username

    }

}

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字"+username);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.kuang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

測試訪問結果;

2、獲取初始化參數

    <!--配置一些web應用初始化參數-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String url = context.getInitParameter("url");
    resp.getWriter().print(url);
}

3、請求轉發

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    System.out.println("進入了ServletDemo04");
    //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); //轉發的請求路徑
    //requestDispatcher.forward(req,resp); //調用forward實現請求轉發;
    context.getRequestDispatcher("/gp").forward(req,resp);
}

1567924457532

4、讀取資源文件

Properties

  • 在java目錄下新建properties
  • 在resources目錄下新建properties

發現:都被打包到了同一個路徑下:classes,我們俗稱這個路徑為classpath:

思路:需要一個文件流;

username=root12312
password=zxczxczxc
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");

        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user+":"+pwd);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

訪問測試即可ok;

6.6、HttpServletResponse

web服務器接收到客戶端的http請求,針對這個請求,分別創建一個代表請求的HttpServletRequest對象,代表響應的一個HttpServletResponse;

  • 如果要獲取客戶端請求過來的參數:找HttpServletRequest
  • 如果要給客戶端響應一些信息:找HttpServletResponse

1、簡單分類

負責向瀏覽器發送數據的方法

ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;

負責向瀏覽器發送響應頭的方法

    void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);

    void setDateHeader(String var1, long var2);

    void addDateHeader(String var1, long var2);

    void setHeader(String var1, String var2);

    void addHeader(String var1, String var2);

    void setIntHeader(String var1, int var2);

    void addIntHeader(String var1, int var2);

響應的狀態碼

    int SC_CONTINUE = 100;
    int SC_SWITCHING_PROTOCOLS = 101;
    int SC_OK = 200;
    int SC_CREATED = 201;
    int SC_ACCEPTED = 202;
    int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    int SC_NO_CONTENT = 204;
    int SC_RESET_CONTENT = 205;
    int SC_PARTIAL_CONTENT = 206;
    int SC_MULTIPLE_CHOICES = 300;
    int SC_MOVED_PERMANENTLY = 301;
    int SC_MOVED_TEMPORARILY = 302;
    int SC_FOUND = 302;
    int SC_SEE_OTHER = 303;
    int SC_NOT_MODIFIED = 304;
    int SC_USE_PROXY = 305;
    int SC_TEMPORARY_REDIRECT = 307;
    int SC_BAD_REQUEST = 400;
    int SC_UNAUTHORIZED = 401;
    int SC_PAYMENT_REQUIRED = 402;
    int SC_FORBIDDEN = 403;
    int SC_NOT_FOUND = 404;
    int SC_METHOD_NOT_ALLOWED = 405;
    int SC_NOT_ACCEPTABLE = 406;
    int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_REQUIRED = 411;
    int SC_PRECONDITION_FAILED = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_FAILED = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

2、下載文件

  1. 向瀏覽器輸出消息 (一直在講,就不說了)
  2. 下載文件
    1. 要獲取下載文件的路徑
    2. 下載的文件名是啥?
    3. 設置想辦法讓瀏覽器能夠支持下載我們需要的東西
    4. 獲取下載文件的輸入流
    5. 創建緩沖區
    6. 獲取OutputStream對象
    7. 將FileOutputStream流寫入到buffer緩沖區
    8. 使用OutputStream將緩沖區中的數據輸出到客戶端!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. 要獲取下載文件的路徑
    String realPath = "F:\\班級管理\\西開【19525】\\2、代碼\\JavaWeb\\javaweb-02-servlet\\response\\target\\classes\\秦疆.png";
    System.out.println("下載文件的路徑:"+realPath);
    // 2. 下載的文件名是啥?
    String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    // 3. 設置想辦法讓瀏覽器能夠支持(Content-Disposition)下載我們需要的東西,中文文件名URLEncoder.encode編碼,否則有可能亂碼
    resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
    // 4. 獲取下載文件的輸入流
    FileInputStream in = new FileInputStream(realPath);
    // 5. 創建緩沖區
    int len = 0;
    byte[] buffer = new byte[1024];
    // 6. 獲取OutputStream對象
    ServletOutputStream out = resp.getOutputStream();
    // 7. 將FileOutputStream流寫入到buffer緩沖區,使用OutputStream將緩沖區中的數據輸出到客戶端!
    while ((len=in.read(buffer))>0){
        out.write(buffer,0,len);
    }

    in.close();
    out.close();
}

3、驗證碼功能

驗證怎么來的?

  • 前端實現
  • 后端實現,需要用到 Java 的圖片類,生產一個圖片
package com.kuang.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //如何讓瀏覽器3秒自動刷新一次;
        resp.setHeader("refresh","3");
        
        //在內存中創建一個圖片
        BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到圖片
        Graphics2D g = (Graphics2D) image.getGraphics(); //筆
        //設置圖片的背景顏色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //給圖片寫數據
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

        //告訴瀏覽器,這個請求用圖片的方式打開
        resp.setContentType("image/jpeg");
        //網站存在緩存,不讓瀏覽器緩存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //把圖片寫給瀏覽器
        ImageIO.write(image,"jpg", resp.getOutputStream());

    }

    //生成隨機數
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length() ; i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

4、實現重定向

1567931587955

B一個web資源收到客戶端A請求后,B他會通知A客戶端去訪問另外一個web資源C,這個過程叫重定向

常見場景:

  • 用戶登錄
void sendRedirect(String var1) throws IOException;

測試:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    /*
        resp.setHeader("Location","/r/img");
        resp.setStatus(302);
         */
    resp.sendRedirect("/r/img");//重定向
}

面試題:請你聊聊重定向和轉發的區別?

相同點

  • 頁面都會實現跳轉

不同點

  • 請求轉發的時候,url不會產生變化
  • 重定向時候,url地址欄會發生變化;

1567932163430

5、簡單實現登錄重定向

<%--這里提交的路徑,需要尋找到項目的路徑--%>
<%--${pageContext.request.contextPath}代表當前的項目--%>

<form action="${pageContext.request.contextPath}/login" method="get">
    用戶名:<input type="text" name="username"> <br>
    密碼:<input type="password" name="password"> <br>
    <input type="submit">
</form>


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //處理請求
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username+":"+password);

        //重定向時候一定要注意,路徑問題,否則404;
        resp.sendRedirect("/r/success.jsp");
    }

  <servlet>
    <servlet-name>requset</servlet-name>
    <servlet-class>com.kuang.servlet.RequestTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>requset</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>Success</h1>

</body>
</html>

6.7、HttpServletRequest

HttpServletRequest代表客戶端的請求,用戶通過Http協議訪問服務器,HTTP請求中的所有信息會被封裝到HttpServletRequest,通過這個HttpServletRequest的方法,獲得客戶端的所有信息;

1567933996830

1567934023106

獲取參數,請求轉發

1567934110794

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");

    String username = req.getParameter("username");
    String password = req.getParameter("password");
    String[] hobbys = req.getParameterValues("hobbys");
    System.out.println("=============================");
    //后台接收中文亂碼問題
    System.out.println(username);
    System.out.println(password);
    System.out.println(Arrays.toString(hobbys));
    System.out.println("=============================");


    System.out.println(req.getContextPath());
    //通過請求轉發
    //這里的 / 代表當前的web應用
    req.getRequestDispatcher("/success.jsp").forward(req,resp);

}

面試題:請你聊聊重定向和轉發的區別?

相同點

  • 頁面都會實現跳轉

不同點

  • 請求轉發的時候,url不會產生變化 307
  • 重定向時候,url地址欄會發生變化; 302

7、Cookie、Session

7.1、會話

會話:用戶打開一個瀏覽器,點擊了很多超鏈接,訪問多個web資源,關閉瀏覽器,這個過程可以稱之為會話;

有狀態會話:一個同學來過教室,下次再來教室,我們會知道這個同學,曾經來過,稱之為有狀態會話;

你能怎么證明你是西開的學生?

你 西開

  1. 發票 西開給你發票
  2. 學校登記 西開標記你來過了

一個網站,怎么證明你來過?

客戶端 服務端

  1. 服務端給客戶端一個 信件,客戶端下次訪問服務端帶上信件就可以了; cookie
  2. 服務器登記你來過了,下次你來的時候我來匹配你; seesion

7.2、保存會話的兩種技術

cookie

  • 客戶端技術 (響應,請求)

session

  • 服務器技術,利用這個技術,可以保存用戶的會話信息? 我們可以把信息或者數據放在Session中!

常見常見:網站登錄之后,你下次不用再登錄了,第二次訪問直接就上去了!

7.3、Cookie

1568344447291

  1. 從請求中拿到cookie信息
  2. 服務器響應給客戶端cookie
Cookie[] cookies = req.getCookies(); //獲得Cookie
cookie.getName(); //獲得cookie中的key
cookie.getValue(); //獲得cookie中的vlaue
new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一個cookie
cookie.setMaxAge(24*60*60); //設置cookie的有效期
resp.addCookie(cookie); //響應給客戶端一個cookie

cookie:一般會保存在本地的 用戶目錄下 appdata;

一個網站cookie是否存在上限!聊聊細節問題

  • 一個Cookie只能保存一個信息;
  • 一個web站點可以給瀏覽器發送多個cookie,最多存放20個cookie;
  • Cookie大小有限制4kb;
  • 300個cookie瀏覽器上限

刪除Cookie;

  • 不設置有效期,關閉瀏覽器,自動失效;
  • 設置有效期時間為 0 ;

編碼解碼:

URLEncoder.encode("秦疆","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")

7.4、Session(重點)

1568344560794

什么是Session:

  • 服務器會給每一個用戶(瀏覽器)創建一個Seesion對象;
  • 一個Seesion獨占一個瀏覽器,只要瀏覽器沒有關閉,這個Session就存在;
  • 用戶登錄之后,整個網站它都可以訪問!--> 保存用戶的信息;保存購物車的信息…..

1568342773861

Session和cookie的區別:

  • Cookie是把用戶的數據寫給用戶的瀏覽器,瀏覽器保存 (可以保存多個)
  • Session把用戶的數據寫到用戶獨占Session中,服務器端保存 (保存重要的信息,減少服務器資源的浪費)
  • Session對象由服務創建;

使用場景:

  • 保存一個登錄用戶的信息;
  • 購物車信息;
  • 在整個網站中經常會使用的數據,我們將它保存在Session中;

使用Session:

package com.kuang.servlet;

import com.kuang.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        //解決亂碼問題
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        
        //得到Session
        HttpSession session = req.getSession();
        //給Session中存東西
        session.setAttribute("name",new Person("秦疆",1));
        //獲取Session的ID
        String sessionId = session.getId();

        //判斷Session是不是新創建
        if (session.isNew()){
            resp.getWriter().write("session創建成功,ID:"+sessionId);
        }else {
            resp.getWriter().write("session以及在服務器中存在了,ID:"+sessionId);
        }

        //Session創建的時候做了什么事情;
//        Cookie cookie = new Cookie("JSESSIONID",sessionId);
//        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

//得到Session
HttpSession session = req.getSession();

Person person = (Person) session.getAttribute("name");

System.out.println(person.toString());

HttpSession session = req.getSession();
session.removeAttribute("name");
//手動注銷Session
session.invalidate();

會話自動過期:web.xml配置

<!--設置Session默認的失效時間-->
<session-config>
    <!--15分鍾后Session自動失效,以分鍾為單位-->
    <session-timeout>15</session-timeout>
</session-config>

1568344679763

8、JSP

8.1、什么是JSP

Java Server Pages : Java服務器端頁面,也和Servlet一樣,用於動態Web技術!

最大的特點:

  • 寫JSP就像在寫HTML
  • 區別:
    • HTML只給用戶提供靜態的數據
    • JSP頁面中可以嵌入JAVA代碼,為用戶提供動態數據;

8.2、JSP原理

思路:JSP到底怎么執行的!

  • 代碼層面沒有任何問題

  • 服務器內部工作

    tomcat中有一個work目錄;

    IDEA中使用Tomcat的會在IDEA的tomcat中生產一個work目錄

    1568345873736

    我電腦的地址:

    C:\Users\Administrator\.IntelliJIdea2018.1\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\ROOT\org\apache\jsp
    

    發現頁面轉變成了Java程序!

    1568345948307

瀏覽器向服務器發送請求,不管訪問什么資源,其實都是在訪問Servlet!

JSP最終也會被轉換成為一個Java類!

JSP 本質上就是一個Servlet

//初始化
  public void _jspInit() {
      
  }
//銷毀
  public void _jspDestroy() {
  }
//JSPService
  public void _jspService(.HttpServletRequest request,HttpServletResponse response)
      
  1. 判斷請求

  2. 內置一些對象

    final javax.servlet.jsp.PageContext pageContext;  //頁面上下文
    javax.servlet.http.HttpSession session = null;    //session
    final javax.servlet.ServletContext application;   //applicationContext
    final javax.servlet.ServletConfig config;         //config
    javax.servlet.jsp.JspWriter out = null;           //out
    final java.lang.Object page = this;               //page:當前
    HttpServletRequest request                        //請求
    HttpServletResponse response                      //響應
    
  3. 輸出頁面前增加的代碼

    response.setContentType("text/html");       //設置響應的頁面類型
    pageContext = _jspxFactory.getPageContext(this, request, response,
                                              null, true, 8192, true);
    _jspx_page_context = pageContext;
    application = pageContext.getServletContext();
    config = pageContext.getServletConfig();
    session = pageContext.getSession();
    out = pageContext.getOut();
    _jspx_out = out;
    
  4. 以上的這些個對象我們可以在JSP頁面中直接使用!

1568347078207

在JSP頁面中;

只要是 JAVA代碼就會原封不動的輸出;

如果是HTML代碼,就會被轉換為:

out.write("<html>\r\n");

這樣的格式,輸出到前端!

8.3、JSP基礎語法

任何語言都有自己的語法,JAVA中有,。 JSP 作為java技術的一種應用,它擁有一些自己擴充的語法(了解,知道即可!),Java所有語法都支持!

JSP表達式

  <%--JSP表達式
  作用:用來將程序的輸出,輸出到客戶端
  <%= 變量或者表達式%>
  --%>
  <%= new java.util.Date()%>

jsp腳本片段


  <%--jsp腳本片段--%>
  <%
    int sum = 0;
    for (int i = 1; i <=100 ; i++) {
      sum+=i;
    }
    out.println("<h1>Sum="+sum+"</h1>");
  %>

腳本片段的再實現

  <%
    int x = 10;
    out.println(x);
  %>
  <p>這是一個JSP文檔</p>
  <%
    int y = 2;
    out.println(y);
  %>

  <hr>


  <%--在代碼嵌入HTML元素--%>
  <%
    for (int i = 0; i < 5; i++) {
  %>
    <h1>Hello,World  <%=i%> </h1>
  <%
    }
  %>

JSP聲明

  <%!
    static {
      System.out.println("Loading Servlet!");
    }

    private int globalVar = 0;

    public void kuang(){
      System.out.println("進入了方法Kuang!");
    }
  %>

JSP聲明:會被編譯到JSP生成Java的類中!其他的,就會被生成到_jspService方法中!

在JSP,嵌入Java代碼即可!

<%%>
<%=%>
<%!%>

<%--注釋--%>

JSP的注釋,不會在客戶端顯示,HTML就會!

8.4、JSP指令

<%@page args.... %>
<%@include file=""%>

<%--@include會將兩個頁面合二為一--%>

<%@include file="common/header.jsp"%>
<h1>網頁主體</h1>

<%@include file="common/footer.jsp"%>

<hr>


<%--jSP標簽
    jsp:include:拼接頁面,本質還是三個
    --%>
<jsp:include page="/common/header.jsp"/>
<h1>網頁主體</h1>
<jsp:include page="/common/footer.jsp"/>

8.5、9大內置對象

  • PageContext 存東西
  • Request 存東西
  • Response
  • Session 存東西
  • Application 【SerlvetContext】 存東西
  • config 【SerlvetConfig】
  • out
  • page ,不用了解
  • exception
pageContext.setAttribute("name1","秦疆1號"); //保存的數據只在一個頁面中有效
request.setAttribute("name2","秦疆2號"); //保存的數據只在一次請求中有效,請求轉發會攜帶這個數據
session.setAttribute("name3","秦疆3號"); //保存的數據只在一次會話中有效,從打開瀏覽器到關閉瀏覽器
application.setAttribute("name4","秦疆4號");  //保存的數據只在服務器中有效,從打開服務器到關閉服務器

request:客戶端向服務器發送請求,產生的數據,用戶看完就沒用了,比如:新聞,用戶看完沒用的!

session:客戶端向服務器發送請求,產生的數據,用戶用完一會還有用,比如:購物車;

application:客戶端向服務器發送請求,產生的數據,一個用戶用完了,其他用戶還可能使用,比如:聊天數據;

8.6、JSP標簽、JSTL標簽、EL表達式

<!-- JSTL表達式的依賴 -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!-- standard標簽庫 -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

EL表達式: ${ }

  • 獲取數據
  • 執行運算
  • 獲取web開發的常用對象

JSP標簽

<%--jsp:include--%>

<%--
http://localhost:8080/jsptag.jsp?name=kuangshen&age=12
--%>

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="kuangshen"></jsp:param>
    <jsp:param name="age" value="12"></jsp:param>
</jsp:forward>

JSTL表達式

JSTL標簽庫的使用就是為了彌補HTML標簽的不足;它自定義許多標簽,可以供我們使用,標簽的功能和Java代碼一樣!

格式化標簽

SQL標簽

XML 標簽

核心標簽 (掌握部分)

1568362473764

JSTL標簽庫使用步驟

  • 引入對應的 taglib
  • 使用其中的方法
  • 在Tomcat 也需要引入 jstl的包,否則會報錯:JSTL解析錯誤

c:if

<head>
    <title>Title</title>
</head>
<body>


<h4>if測試</h4>

<hr>

<form action="coreif.jsp" method="get">
    <%--
    EL表達式獲取表單中的數據
    ${param.參數名}
    --%>
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="登錄">
</form>

<%--判斷如果提交的用戶名是管理員,則登錄成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="管理員歡迎您!"/>
</c:if>

<%--自閉合標簽--%>
<c:out value="${isAdmin}"/>

</body>

c:choose c:when

<body>

<%--定義一個變量score,值為85--%>
<c:set var="score" value="55"/>

<c:choose>
    <c:when test="${score>=90}">
        你的成績為優秀
    </c:when>
    <c:when test="${score>=80}">
        你的成績為一般
    </c:when>
    <c:when test="${score>=70}">
        你的成績為良好
    </c:when>
    <c:when test="${score<=60}">
        你的成績為不及格
    </c:when>
</c:choose>

</body>

c:forEach

<%

    ArrayList<String> people = new ArrayList<>();
    people.add(0,"張三");
    people.add(1,"李四");
    people.add(2,"王五");
    people.add(3,"趙六");
    people.add(4,"田六");
    request.setAttribute("list",people);
%>


<%--
var , 每一次遍歷出來的變量
items, 要遍歷的對象
begin,   哪里開始
end,     到哪里
step,   步長
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/> <br>
</c:forEach>

<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
    <c:out value="${people}"/> <br>
</c:forEach>

9、JavaBean

實體類

JavaBean有特定的寫法:

  • 必須要有一個無參構造
  • 屬性必須私有化
  • 必須有對應的get/set方法;

一般用來和數據庫的字段做映射 ORM;

ORM :對象關系映射

  • 表--->類
  • 字段-->屬性
  • 行記錄---->對象

people表

id name age address
1 秦疆1號 3 西安
2 秦疆2號 18 西安
3 秦疆3號 100 西安
class People{
    private int id;
    private String name;
    private int id;
    private String address;
}

class A{
    new People(1,"秦疆1號",3,"西安");
    new People(2,"秦疆2號",3,"西安");
    new People(3,"秦疆3號",3,"西安");
}
  • 過濾器
  • 文件上傳
  • 郵件發送
  • JDBC 復習 : 如何使用JDBC , JDBC crud, jdbc 事務

10、MVC三層架構

什么是MVC: Model view Controller 模型、視圖、控制器

10.1、早些年

1568423664332

用戶直接訪問控制層,控制層就可以直接操作數據庫;

servlet--CRUD-->數據庫
弊端:程序十分臃腫,不利於維護  
servlet的代碼中:處理請求、響應、視圖跳轉、處理JDBC、處理業務代碼、處理邏輯代碼

架構:沒有什么是加一層解決不了的!
程序猿調用
|
JDBC
|
Mysql Oracle SqlServer ....

10.2、MVC三層架構

1568424227281

Model

  • 業務處理 :業務邏輯(Service)
  • 數據持久層:CRUD (Dao)

View

  • 展示數據
  • 提供鏈接發起Servlet請求 (a,form,img…)

Controller (Servlet)

  • 接收用戶的請求 :(req:請求參數、Session信息….)

  • 交給業務層處理對應的代碼

  • 控制視圖的跳轉

    登錄--->接收用戶的登錄請求--->處理用戶的請求(獲取用戶登錄的參數,username,password)---->交給業務層處理登錄業務(判斷用戶名密碼是否正確:事務)--->Dao層查詢用戶名和密碼是否正確-->數據庫
    

11、Filter (重點)

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

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

1568424858708

Filter開發步驟:

  1. 導包

  2. 編寫過濾器

    1. 導包不要錯

      1568425162525

      實現Filter接口,重寫對應的方法即可

      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銷毀");
          }
      }
      
      
  3. 在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連接數據庫!

1568439601825

需要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','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');


SELECT	* FROM users;

導入數據庫依賴

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

IDEA中連接數據庫:

1568440926845

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,"24736743@qq.com");//給第四個占位符? 的值賦值為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");
}

1568442261610

失敗的時候是紅色:

1568442289597

搭建一個環境

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();
            }
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM