java基礎-11 Web

目錄

 

Eclipse中集成Tomcat

網站訪問的全過程

Web

Idea配置tomcat:https://www.jianshu.com/p/3c75f7fd2f90

什麼是WEB

什麼是JavaWEB

軟件架構

WEB服務器

常見哪些web服務器

WEB開發中的資源

Tomcat的目錄結構

動態WEB資源的目錄結構

Tomcat項目發佈的三種方式

虛擬主機

HTTP協議

Servlet

Servlet的實現子類

使用Eclipse開發Servlet

Servlet的生命週期

代碼演示Servlet的生命週期

Servlet的啓動時加載

Servlet的訪問路徑的配置

ServletConfig對象

ServletContext

Response

Response對象響應的中文亂碼處理

Request

獲得請求頭的方法


  • Eclipse中集成Tomcat

1.選擇window

2.彈出界面選擇Server

3.添加服務

4.選擇Tomcat服務

5.配置服務

6.設置服務

7.創建一個web項目

  • 網站訪問的全過程

Web

Idea配置tomcat:https://www.jianshu.com/p/3c75f7fd2f90

  • 什麼是WEB

web(World Wide Web)即全球廣域網,也稱爲萬維網,它是一種基於超文本和HTTP的、全球性的、動態交互的、跨平臺的分佈式圖形信息系統。是建立在Internet上的一種網絡服務,爲瀏覽者在Internet上查找和瀏覽信息提供了圖形化的、易於訪問的直觀界面,其中的文檔及超級鏈接將Internet上的信息節點組織成一個互爲關聯的網狀結構。

  • 什麼是JavaWEB

使用Java語言進行WEB的開發

  • 軟件架構

  1. CS結構的軟件
    1. CS:Client/Server 客戶端和服務器,這種軟件往往需要安裝。比如QQ、迅雷、播放器。
    2. 優缺點:
      1. 優點:
        1. 可以減輕服務器端壓力,將部分代碼寫到客戶端。
        2. 界面很美觀。
      2. 缺點:
        1. 一旦服務器更新了,客戶端也需要更新。
        2. 分佈式開發比較弱。
  2. BS結構的軟件
    1. BS:Browser/Server 瀏覽器和服務器,這種軟件不需要安裝,只需要通過瀏覽器就可以訪問。
    2. 優缺點:
      1. 優點:
        1. 服務器一旦更新,不需要更新客戶端,因爲客戶端就是瀏覽器
        2. 比較強的分佈式能力
      2. 缺點:
        1. 服務器端壓力會比較大。
        2. 界面效果不如CS結構軟件。
  • WEB服務器

  1. 服務器:
    1. 硬件:其實就是一臺電腦(這臺電腦配置要求很高)。
    2. 軟件:需要在這臺電腦上安裝web服務器的軟件。
  • 常見哪些web服務器

  1. Tomcat              :Apache組織提供的一個開源的免費的web服務器。滿足EE的Serlet和JSP的規範。
  2. WebSphere      :IBM公司開發的一個收費的大型web服務器。滿足了EE開發的所有規範。
  3. WebLogic         :BEA公司開發的一個收費的大型web服務器。滿足了EE開發的所有規範。
  4. IIS                     :應用在.NET平臺上。
  5. Apache             :應用在PHP平臺上。
  • WEB開發中的資源

  1. 靜態web資源
    1. HTML
    2. CSS
    3. JS
  2. 動態web資源
    1. ServletJSP
    2. PHP
    3. ASP
  • Tomcat的目錄結構

  1. bin             :二進制文件(命令文件:開啓和關閉)
  2. conf           :配置文件
  3. lib              :tomcat所需要的jar包
  4. logs           :tomcat服務器日誌文件
  5. temp         :tomcat運行產生臨時文件
  6. webapps  :需要發佈的項目需要放在webapps
  7. work         :JSP翻譯(編譯)成Servlet產生的代碼
  • 動態WEB資源的目錄結構

website

         |------靜態頁面(HTML、CSS、JS、圖片)

         |------JSP頁面

         |------WEB-INF

                            |-----web.xml   (必須的)

                            |-----classes       (可選的)

                            |-----lib               (可選的)

  • Tomcat項目發佈的三種方式

  1. 一種:直接將項目複製到tomcat/webapps下
  2. 二種:在tomcat/conf/server.xml配置tomcat的虛擬路徑
  3. 三種:在tomcat/conf/Catalina/localhost/下配置tomcat的虛擬路徑

Tomcat的項目發佈方式一

  • 一種:直接將項目複製到tomcat/webapps下

訪問地址:http://localhost:8080/項目名稱/index.html               index.html可省略

 

  • 二種:在tomcat/conf/server.xml配置tomcat的虛擬路徑( 不推薦使用第二種方式,原因:需要修改tpmcat的核心配置文件,可能導致tomcat啓動都報錯)

這種方式是需要配置Tomcat的虛擬路徑。

虛擬路徑:配置一個名稱與一個真實的路徑進行綁定,然後訪問這個名稱從而找到真實路徑。
如何配置虛擬路徑
在tomcat/conf/server.xml中進行配置(可以在tomcat的文檔中找到)。
    第一步:創建一個項目
    第二步:配置虛擬路徑

...
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
			   
		<Context path="/toroidals" docBase="F:\桌面\資料\web 項目\登錄\cpts_1036_bnv"></Context>
		
      </Host>
    </Engine>
  </Service>
</Server>
  • 三種:在tomcat/conf/Catalina/localhost/下配置tomcat的虛擬路徑

第三種方式也需要配置虛擬路徑,第二種需要修改server.xml。server.xml是tomcat的核心配置文件,一旦你修改錯了,那麼tomcat服務器就會出現問題。推薦使用第三種配置方式。

  1. 第一步:創建web項目
  2. 第二步:創建一個xml(在tomcat/conf/Catalina/localhost)
  3. 第三步:配置虛擬路徑:文件的名稱就是虛擬路徑(itcast),只需要訪問itcast就可以訪問C:\ccc這個路徑

<?xml version='1.0' encoding='utf-8'?>
<Context path="/toroidals" docBase="F:\桌面\資料\web 項目\登錄\cpts_1036_bnv"></Context>
  • 虛擬主機

虛擬主機:在電腦上設置一個目錄,使用一個名稱與該目錄進行綁定。這個路徑稱爲是虛擬主機。主機是可以發佈web項目的。

  • 虛擬主機的配置

修改百度主頁爲自定義主頁

修改本地的hosts文件

C:\Windows\System32\drivers\etc\hosts

192.168.115.1 www.baidu.com

注意: 

  1. HTTP服務器,默認的端口號爲80/tcp
  2. HTTPS(securely transferring web pages)服務器,默認的端口號爲443/tcp 443/udp
  3. TOMCAT,默認的端口號爲8080; 

修改 server.xml

修改端口號

將路徑中的website去掉

配置默認的首頁

web.xml

  • HTTP協議

什麼是HTTP協議: 超文本傳輸協議

http是一個簡單的請求-響應協議,它通常運行在TCP之上。它指定了客戶端可能發送給服務器什麼樣的消息以及得到什麼樣的響應。請求和響應消息的頭以ASCII碼形式給出;而消息內容則具有一個類似MIME的格式。這個簡單模型是早期Web成功的有功之臣,因爲它使得開發和部署是那麼的直截了當。

什麼是https: 超文本傳輸安全協議

HTTPS (全稱:Hyper Text Transfer Protocol over SecureSocket Layer),是以安全爲目標的 HTTP 通道,在HTTP的基礎上通過傳輸加密和身份認證保證了傳輸過程的安全性  。HTTPS 在HTTP 的基礎下加入SSL 層,HTTPS 的安全基礎是 SSL,因此加密的詳細內容就需要 SSL。 HTTPS 存在不同於 HTTP 的默認端口及一個加密/身份驗證層(在 HTTP與 TCP 之間)。這個系統提供了身份驗證與加密通訊方法。現在它被廣泛用於萬維網上安全敏感的通訊,例如交易支付等方面

HTTP的特性

  1. 基於請求和響應模型
    1. 必須要先有請求,後有響應。
    2. 請求和響應必須成對出現。
  2. 簡單快捷
    1. 因爲發送請求的時候只需要發送請求方式和請求路徑即可

HTTP的版本

  1. HTTP1.0   :
  2. HTTP1.1  

分析HTTP協議

請求部分詳解

請求部分可以分成三塊

  1. 請求行
    1. 請求方式
      1. 請求方式有很多種,常用就兩種GETPOST
      2. GETPOST的區別?
        1. GET:請求的參數會顯示到地址欄。通常是有大小的限制。沒有請求體
        2. POST:請求的參數不會顯示到地址欄(在請求體中)。POST沒有大小的限制。有請求體(請求參數)。只有表單設置method=”post”纔是post請求。
    2. 請求路徑
    3. 協議版本
  2. 請求頭
    1. 請求頭的格式一般都是一個key對應一個value的,也有一個key對應多個value的情況。
    2. 記住一些請求頭:
      1. Referer              :代表網頁的來源。(防盜鏈)。
      2. User-Agent       :獲得客戶端瀏覽器類型。
  3. 請求體
    1. 只有POST請求方式纔有請求體,而且請求體是POST方式請求參數。

響應部分詳解

響應部分分成三塊內容

  1. 響應行
    1. 協議版本
    2. 狀態碼
      1. 200  :代表響應成功
      2. 302  :需要進行重定向操作
      3. 304  :需要查找本地緩存
      4. 404  :請求資源不存在
      5. 500  :服務器內部錯誤
    3. 狀態碼描述
  2. 響應頭
    1. 通常一個key對應一個value,也有一個key對應多個value。
    2. 記住響應頭:
      1. Location   :重定向的路徑。
      2. Refresh     :定時刷新。
      3. Content-Disposition:文件下載的時候使用。
  3. 響應體
    1. 就是顯示到瀏覽器上頁面的代碼。
  • Servlet

什麼是Servlet: Servlet其實就一個運行在web服務器上的小的Java程序,用於處理從web客戶端發送的請求,並且對請求作出響應。

Servlet(Server Applet)是Java Servlet的簡稱,稱爲小服務程序或服務連接器,用Java編寫的服務器端程序,具有獨立於平臺和協議的特性,主要功能在於交互式地瀏覽和生成數據,生成動態Web內容。

狹義的Servlet是指Java語言實現的一個接口,廣義的Servlet是指任何實現了這個Servlet接口的類,一般情況下,人們將Servlet理解爲後者。Servlet運行於支持Java的應用服務器中。從原理上講,Servlet可以響應任何類型的請求,但絕大多數情況下Servlet只用來擴展基於HTTP協議的Web服務器。

最早支持Servlet標準的是JavaSoft的Java Web Server,此後,一些其它的基於Java的Web服務器開始支持標準的Servlet。

  • 使用Servlet

    編寫一個Java類實現Servlet的接口
    配置Servlet

實現servlet接口,重寫service方法

package com.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletTest implements Servlet{

	/*
	 * 處理用戶請求,對請求做出響應 
	 */
	@Override
	public void service(ServletRequest request, ServletResponse respose) throws ServletException, IOException {
		// 向頁面輸出一個"海納百川, 有容乃大, 壁立千仞, 無欲則剛"
		respose.getWriter().println("send masegge 海納百川, 有容乃大, 壁立千仞, 無欲則剛");
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}

在web.xml中配置這個類的映射

  <!-- 配置Servlet -->
   <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.servlet.ServletTest</servlet-class>
  </servlet>
  <!-- 配置Servlet映射 -->
   <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

啓動服務直接訪問: http://localhost:8080/JavaWeb/hello

此處中文未能正常顯示

  • Servlet的執行流程
  1. 根據請求路徑http://localhost:8080/JavaWeb/hello到web.xml <servlet-mapping> 查找 url-pattern 匹配項
  2. 找到url-pattern對應的servlet-name
  3. 在 <servlet> 中找到 servlet-name 對應的類
  4. 執行類中的 service方法
  • Servlet的實現子類

Servlet接口                      

         |

GenericServlet類             通用的Servlet,是一個與協議無關的Servlet

         |

HttpServlet類                    Http專用的Servlet

實現關係的概述

SUN設計之初,認爲以後的互聯網不僅僅只使用http協議,可以通過GenericServlet實現。HttpServlet是一個與協議相關的Servlet是專門用來處理HTTP協議的請求。通常編寫一個Servlet一般都會讓這個Servlet繼承HttpServlet重寫service方法。

service方法內部根據請求方式不同執行不同的doXXX的方法(get請求執行doGet方法,如果是post請求就會執行doPost方法)。

所以往往繼承了HttpServlet之後不需要重寫service方法,只需要重寫doGetdoPost方法即可。往往請求要處理的內容的代碼都是一致的,所以需要讓doGetdoPost相互調用可以簡化編程。

配置 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JavaWeb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置Servlet -->
   <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.servlet.ServletTest</servlet-class>
  </servlet>
  
  <!-- 配置Servlet映射 -->
   <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
    <!-- 配置Servlet -->
   <servlet>
    <servlet-name>HttpServlet</servlet-name>
    <servlet-class>com.servlet.HttpServletTest</servlet-class>
  </servlet>
  <!-- 配置Servlet映射 -->
   <servlet-mapping>
    <servlet-name>HttpServlet</servlet-name>
    <url-pattern>/httpServlet</url-pattern>
  </servlet-mapping>
  
</web-app>

繼承 HttpServlet 類

package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpServletTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是GET請求就會執行doGet中的代碼
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是Post請求就會執行doPost中的代碼
		resp.getWriter().println("httpServlet... 囂張");
	}
}
  • 使用Eclipse開發Servlet

新建Servlet

第二個爲 url映射路徑

package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EclipseServletTest
 */
public class EclipseServletTest extends HttpServlet {
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EclipseServletTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

注意 web.xml 不用再手動配置,eclipse會自動添加

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JavaWeb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.servlet.ServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>HttpServlet</servlet-name>
    <servlet-class>com.servlet.HttpServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HttpServlet</servlet-name>
    <url-pattern>/httpServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>EclipseServletTest</display-name>
    <servlet-name>EclipseServletTest</servlet-name>
    <servlet-class>com.servlet.EclipseServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EclipseServletTest</servlet-name>
    <url-pattern>/eclispeServlet</url-pattern>
  </servlet-mapping>
</web-app>
  • Servlet的生命週期

Servlet生命週期:Servlet對象從創建到銷燬的過程。

  1. Servlet何時被創建又是何時被銷燬的?

Servlet中有init,service,destroy方法,這幾個方法稱爲是Servlet生命週期相關的方法。

  1. Servlet是在第一次被訪問的時候會被實例化,只要Servlet一被實例化那麼Servlet中的init方法就會執行(init只會執行一次)。
  2. 任何一次從客戶端發送來的請求,那麼Servlet中的service方法就會執行(在service方法的內部根據請求的方式不同調用不同doXXX方法)。
  3. 當Servlet從服務器中移除或者服務器關閉的時候Servlet對象被銷燬,裏面的destroy方法就會執行,然後垃圾回收就會將其回收掉。
  • 代碼演示Servlet的生命週期

public class ServletDemo implements Servlet{
	
	/*
	 * Servlet對象被實例化的時候init方法就會執行,而且只執行一次。(Servlet是單例的)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("init執行了......");
	}
	
	/*
	 * service方法:任何一次請求都會執行service方法。可以執行多次。
	 */
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("service執行了......");
	}
	
	/*
	 * Servlet從服務器中移除或者服務器關閉的時候銷燬Servlet。執行一次。
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("destroy執行了......");
	}
...
init執行了......              第一次發送請求
service執行了......           第一次發送請求
service執行了......           第二次發送請求
service執行了......           第三次發送請求
...

destroy執行了......           停止tomcat服務
...
  • Servlet的啓動時加載

  • 爲什麼使用啓動時加載

Servlet對象是第一次被訪問的時候會被創建的,init方法就會執行。假設在init方法中做了一些比較耗時的操作(比如:加載了一些配置文件並且解析可能需要花費3秒鐘)。第一個用戶第一次訪問這個Servlet的時候,需要等待3秒鐘。如何使第一個用戶在第一次訪問的時候不需要花費這麼長時間?

  • 什麼是啓動時加載

Servlet默認是在第一次訪問的時候創建的對象,現在通過一個配置將Servlet的實例化的過程放在服務器啓動的時候(讓服務器啓動的時候創建Servlet的對象)。如果現在這樣做那麼之前花費的時間就會在服務器啓動的時候一起花費掉了。對於用戶來講就不需要額外花費這個時間。

  • 配置啓動時加載

注意: load-on-startup 的啓動優先級不能高於2,一般設置爲2,因爲tomcat默認servlet啓動優先爲1(數字越小優先級越高)

    <servlet>
    <description></description>
    <display-name>ServletDemo</display-name>
    <servlet-name>ServletDemo</servlet-name>
    <servlet-class>com.servlet.ServletDemo</servlet-class>
    <!-- 配置啓動時加載 -->
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/ServletDemo</url-pattern>
  </servlet-mapping>
...
信息: Starting Servlet engine: [Apache Tomcat/9.0.27]
init執行了......                啓動時
十一月 20, 2019 5:19:36 下午 org.apache.coyote.AbstractProtocol start
信息: 開始協議處理句柄["http-nio-8080"]
十一月 20, 2019 5:19:36 下午 org.apache.coyote.AbstractProtocol start
信息: 開始協議處理句柄["ajp-nio-8009"]
十一月 20, 2019 5:19:36 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in [413] milliseconds
service執行了......             第一次發送請求
service執行了......             第二次發送請求
service執行了......             第三次發送請求
十一月 20, 2019 5:20:08 下午 org.apache.catalina.core.StandardServer await
信息: A valid shutdown command was received via the shutdown port. Stopping the Server instance.
十一月 20, 2019 5:20:08 下午 org.apache.coyote.AbstractProtocol pause
信息: Pausing ProtocolHandler ["http-nio-8080"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol pause
信息: Pausing ProtocolHandler ["ajp-nio-8009"]
十一月 20, 2019 5:20:09 下午 org.apache.catalina.core.StandardService stopInternal
信息: Stopping service [Catalina]
destroy執行了......             停止tomcat服務
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol stop
信息: Stopping ProtocolHandler ["http-nio-8080"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol stop
信息: Stopping ProtocolHandler ["ajp-nio-8009"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol destroy
信息: 正在摧毀協議處理器 ["http-nio-8080"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol destroy
信息: 正在摧毀協議處理器 ["ajp-nio-8009"]
  • Servlet的訪問路徑的配置

  • Servlet中的urlPattern的配置
  1. 完全路徑匹配
    1. 以 / 開始                 比如:/ServletDemo1    /aaa/ServletDemo2

  1. 目錄匹配
    1. 以 / 開始,以 /*結束           比如:/*          /aaa/*      /aaa/bbb/*

  1. 擴展名匹配
    1. 不能以 / 開始,以*開始               比如:*.action        *.do          *.jsp

  • 訪問的優先級

完全路徑匹配  >  目錄匹配  >  擴展名匹配

  • ServletConfig對象

ServletConfig用來獲得Servlet的相關的配置信息。

如何獲得 ServletConfig 對象,調用 Servlet 的 getServletConfig() 方法。

 ServletConfig getServletConfig()
          Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.

 ServletConfig 方法

Method Summary
 String getInitParameter(String name)
          返回包含指定初始化參數的值的 String,如果參數不存在,則返回 null。 
 Enumeration getInitParameterNames()
          Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
 ServletContext getServletContext()
          返回對調用者在其中執行操作的 ServletContext 的引用。 
 String getServletName()
         返回此 servlet 實例的名稱。該名稱可能是通過服務器管理提供的,在 Web 應用程序部署描述符中分配,或者對於未註冊(和未命名)的 servlet 實例,該名稱將是該 servlet 的類名稱。
  <servlet>
    <servlet-name>httpServlet1</servlet-name>
    <servlet-class>com.servlet.HttpServletTest</servlet-class>
    <!-- 配置Servlet的初始化參數 -->
    <init-param>
    	<param-name>userName</param-name>
    	<param-value>root</param-value>
    </init-param>
        <init-param>
    	<param-name>password</param-name>
    	<param-value>123456</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>httpServlet1</servlet-name>
    <url-pattern>/httpServlet2</url-pattern>
  </servlet-mapping>
public class HttpServletTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//獲得ServletConfig對象
		ServletConfig seConf = this.getServletConfig();
		//獲取初始化參數的值
		String userName = seConf.getInitParameter("userName");
		String password = seConf.getInitParameter("password");
		System.out.println("userName: " + userName + ", password: " + password);
		System.out.println("-------------------");
		
		//獲得所有初始化參數的名稱
		Enumeration<String> names = seConf.getInitParameterNames();
		while(names.hasMoreElements()) {
			String name = names.nextElement();
			String value = seConf.getInitParameter(name);
			System.out.println("name: " + name + ", value: " + value);
		}
		System.out.println("-------------------");
		
		//獲得Servlet的名稱
		String servletName = seConf.getServletName();
		System.out.println(servletName);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是Post請求就會執行doPost中的代碼
		doGet(req, resp);
	}

}

/*
userName: root, password: 123456
-------------------
name: password, value: 123456
name: userName, value: root
-------------------
httpServlet1
*/
  • ServletContext

ServletContext:Servlet的上下文對象。ServletContext對象對Servlet之前和之後的內容都知道。這個對象一個web項目只有一個。在服務器啓動的時候爲每個web項目創建一個單獨的ServletContext對象。

作用一:用來獲取web項目信息

因爲一個web項目只有一個ServletContext對象,所以這個對象對整個項目的相關內容都是瞭解的。

  1. 方法:獲取文件的MIME類型

獲取web項目請求工程名:

獲取web項目的初始化參數:

  • 作用二:讀取web項目下的文件

之前使用IO流就可以讀取文件(java項目中)。現在是一個web項目,web項目需要發佈到tomcat下才能訪問的。獲取web項目下的文件如果使用傳統的IO就會出現問題(原因:路徑中使用的是相對路徑,相對的是JRE環境)。

public class HttpServletTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//獲得ServletContext對象
		test3();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是Post請求就會執行doPost中的代碼
		doGet(req, resp);
	}
	
	/**
	 * 讀取web項目下的文件:使用ServletContext讀取
	 * @throws IOException 
	 */
	private void test3() throws IOException{
		// 使用ServletContext方式:
		Properties properties = new Properties();
		
		// 創建一個文件的輸入流:
		//傳統模式,根據getServletContext獲取絕對路徑
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		System.out.println(path);
		InputStream is = new FileInputStream(path);
		
		//創建一個文件的輸入流:
		//InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		
		properties.load(is);
		// 獲取數據:
		String driverClassName = properties.getProperty("driverClassName");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		// 輸出到控制檯
		System.out.println(driverClassName);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}	
	/**
	 * 讀取web項目下的文件:使用ServletContext讀取
	 * @throws IOException 
	 */
	private void test2() throws IOException{
		// 使用ServletContext方式:
		Properties properties = new Properties();
		// 創建一個文件的輸入流:
		// InputStream is = new FileInputStream("classes/db.properties");
		InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		properties.load(is);
		// 獲取數據:
		String driverClassName = properties.getProperty("driverClassName");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		// 輸出到控制檯
		System.out.println(driverClassName);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}

	/**
	 * 傳統方式讀取文件(不好使)
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void test1() throws FileNotFoundException, IOException {
		// 傳統方式:
		Properties properties = new Properties();
		// 創建一個文件的輸入流:
		InputStream is = new FileInputStream("classes/db.properties");
		properties.load(is);
		// 獲取數據:
		String driverClassName = properties.getProperty("driverClassName");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		// 輸出到控制檯
		System.out.println(driverClassName);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}
}

/*
E:\JAVA2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JavaWeb\WEB-INF\classes\db.properties
com.mysql.jdbc.Driver
jdbc:mysql:///test
root
123456
*/
  • 作用三:ServletContext對象作爲域對象存取數據

什麼是域對象
域對象:指的是將數據存入到域對象中,這個數據就會有一定的作用範圍。域指的是一定的作用範圍。

  • ServletContext作爲域對象的作用範圍

ServletContext是在服務器啓動的時候爲每個web項目單獨創建一個ServletContext對象。當web項目從服務器中移除,或者是關閉服務器的時候ServletContext對象會被銷燬。向ServletContext中保存的數據一直存在(當服務器關閉的時候ServletContext對象被銷燬,然後裏面數據纔會失效)。範圍:整個web應用。

  • ServletContext作爲域對象:
返回類型 方法 描述
Object getAttribute(String name) 返回具有給定名稱的 servlet 容器屬性,如果不具有該名稱的屬性,則返回 null。
 Enumeration getAttributeNames() 返回包含此 servlet 上下文中可用屬性的名稱的 Enumeration。使用帶有一個屬性名稱的 #getAttribute 方法獲取屬性值。
 void removeAttribute(String name) 從 servlet 上下文中移除具有給定名稱的屬性。
 void setAttribute(String name, Object object) 將對象綁定到此 servlet 上下文中的給定屬性名稱。如果已將指定名稱用於某個屬性,則此方法將使用新屬性替換具有該名稱的屬性。 如果在 ServletContext 上配置了偵聽器,則容器將相應地通知它們。 如果傳遞了 null 值,則效果將與調用 removeAttribute() 相同。
public class ServletContextAttribute1 extends HttpServlet {
	
	@Override
	public void init(){
		//當ServletContextAttribute1被創建時,向ServletContext存入一個值
		this.getServletContext().setAttribute("name1", "ServletContextAttribute1");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取存入的值
		Object name1 = this.getServletContext().getAttribute("name1");
		System.out.println(name1);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}



public class ServletContextAttribute2 extends HttpServlet {
	
	@Override
	public void init(){
		//當ServletContextAttribute2被創建時,向ServletContext存入一個值
		this.getServletContext().setAttribute("name2", "ServletContextAttribute2");
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name1 = (String)this.getServletContext().getAttribute("name1");
		System.out.println(name1);
		String name2 = (String)this.getServletContext().getAttribute("name2");
		System.out.println(name2);
		System.out.println("-----------------------");
		Enumeration<String> names = this.getServletContext().getAttributeNames();
		while(names.hasMoreElements()) {
			String name = names.nextElement();
			Object value = this.getServletContext().getAttribute(name);
			System.out.println("name: " + name + ", value: " + value);
		}	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




/*
ServletContextAttribute1


ServletContextAttribute1
ServletContextAttribute2
-----------------------
name: javax.servlet.context.tempdir, value: E:\JAVA2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\JavaWeb
name: org.apache.catalina.resources, value: org.apache.catalina.webresources.StandardRoot@1c90fab5
name: org.apache.tomcat.InstanceManager, value: org.apache.catalina.core.DefaultInstanceManager@6e5b32b6
name: org.apache.catalina.jsp_classpath, value: /D:/software/apache-tomcat-9.0.27/lib/;/D:/software/apache-tomcat-9.0.27/lib/annotations-api.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-ant.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-ha.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-storeconfig.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-tribes.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina.jar;/D:/software/apache-tomcat-9.0.27/lib/ecj-4.13.jar;/D:/software/apache-tomcat-9.0.27/lib/el-api.jar;/D:/software/apache-tomcat-9.0.27/lib/jasper-el.jar;/D:/software/apache-tomcat-9.0.27/lib/jasper.jar;/D:/software/apache-tomcat-9.0.27/lib/jaspic-api.jar;/D:/software/apache-tomcat-9.0.27/lib/jsp-api.jar;/D:/software/apache-tomcat-9.0.27/lib/servlet-api.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-api.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-coyote.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-dbcp.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-cs.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-de.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-es.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-fr.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-ja.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-ko.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-pt-BR.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-ru.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-zh-CN.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-jdbc.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-jni.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-util-scan.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-util.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-websocket.jar;/D:/software/apache-tomcat-9.0.27/lib/websocket-api.jar;/D:/software/apache-tomcat-9.0.27/bin/bootstrap.jar;/D:/software/apache-tomcat-9.0.27/bin/tomcat-juli.jar;/D:/software/Java/jdk1.8.0_171/lib/tools.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/access-bridge-64.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/cldrdata.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/dnsns.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/jaccess.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/jfxrt.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/localedata.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/nashorn.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunec.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunjce_provider.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunmscapi.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunpkcs11.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/zipfs.jar
name: javax.websocket.server.ServerContainer, value: org.apache.tomcat.websocket.server.WsServerContainer@609cd10d
name: name2, value: ServletContextAttribute2
name: name1, value: ServletContextAttribute1
name: org.apache.jasper.compiler.TldCache, value: org.apache.jasper.compiler.TldCache@64a359c6
name: org.apache.tomcat.JarScanner, value: org.apache.tomcat.util.scan.StandardJarScanner@7cbf05fa
*/
  • Response

  • Response關於響應行的方法

 

Modifier Constructor 描述
void setStatus(int sc)  設置此響應的狀態代碼。
void setStatus(int sc, String sm)  從版本 2.1 起,由於消息參數的含義不明確。使用 setStatus(int) 設置狀態代碼,使用 sendError(int, String) 發送帶描述的錯誤。 設置此響應的狀態代碼和消息。 sc 狀態代碼 sm 狀態消息 
 
  1. 設置響應的狀態碼
    1. 200 正確
    2. 302 重定向
    3. 304 查找本地緩存
    4. 404 請求資源不存在
    5. 500 服務器內部錯誤
  • Response關於響應頭的方法
  1. set開頭的方法:針對一個key對應一個value的情況。
    1. 舉例:比如有一個頭 content-Type:text/html  setHeader(“content-Type”,”text/plain”);
    2. 最終得到頭的結果:content-Type:text/plain
 void setDateHeader(String name, long date)
          Sets a response header with the given name and date-value.
 void setHeader(String name, String value)
          Sets a response header with the given name and value.
 void setIntHeader(String name, int value)
          Sets a response header with the given name and integer value.
  1. add開頭的方法:針對一個key對應多個value的情況。
    1. 舉例:比如有一個content-Type:text/html    addHeader(“content-Type”,”text/plain”);
    2. 最終得到頭的結果:content-Type:text/html,text/plain
 void addCookie(Cookie cookie)
          Adds the specified cookie to the response.
 void addDateHeader(String name, long date)
          Adds a response header with the given name and date-value.
 void addHeader(String name, String value)
          Adds a response header with the given name and value.
 void addIntHeader(String name, int value)
          Adds a response header with the given name and integer value.
  • Response關於響應體的方法

在httpServletResponse的父類中

ServletOutputStream getOutputStream()
          Returns a ServletOutputStream suitable for writing binary data in the response.
 PrintWriter getWriter()
          Returns a PrintWriter object that can send character text to the client.

重定向的方法

 void sendRedirect(String location)
          Sends a temporary redirect response to the client using the specified redirect location URL.

設置瀏覽器打開頁面時候採用的字符集

 void setContentType(String type)
          Sets the content type of the response being sent to the client, if the response has not been committed yet.

設置響應字符流的緩衝區字符集

 void setCharacterEncoding(String charset)
          Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

服務器向瀏覽器回寫Cookie的方法

 void addCookie(Cookie cookie)
          Adds the specified cookie to the response.
  • Response對象API的代碼演示

重定向:302狀態碼和Location響應頭結合使用的效果。

public class NotFoundRedirect extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");  //解決中文不能正常顯示問題
		response.getWriter().println("404頁面找不到了!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}


public class ResultRedirect extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//重定向
		response.setStatus(302);
		//設置響應頭
		response.setHeader("Location", "/JavaWeb/NotFoundRedirect");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

  • 實際開發中可以使用:response.sendRedirect(“/JavaWeb/NotFoundRedirect”);替換重定向兩句寫法
public class ResultRedirect extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//重定向
		response.setStatus(302);
		//設置響應頭
		//response.setHeader("Location", "/JavaWeb/NotFoundRedirect");
		//替換重定向兩句寫法
		response.sendRedirect("/JavaWeb/NotFoundRedirect");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

定時刷新

public class Fresh extends HttpServlet {
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//定時刷新
		response.setContentType("text/html;charset=UTF-8");  //解決中文不能正常顯示問題
		response.getWriter().println("頁面5秒後跳轉");
		response.setHeader("Refresh", "5;url=/JavaWeb/NotFoundRedirect");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

使用JS完成讀秒的效果

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="5;url=/JavaWeb/demo2.html">
<title>Insert title here</title>
<script type="text/javascript">
	var i = 5;
	function load(){
		window.setInterval("changeSeconds()",1000);
	}
	
	function changeSeconds(){
		i--;
		document.getElementById("span1").innerHTML=i;
	}
</script>
</head>
<body onload="load()">
<h1>demo1.html</h1>
<h3>頁面將在<span id="span1">5</span>秒後跳轉到demo2.html</h3>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>demo2.html</h1>
</body>
</html>
  • Response對象響應的中文亂碼處理

ServletOutputStream getOutputStream()
          Returns a ServletOutputStream suitable for writing binary data in the response.
 PrintWriter getWriter()
          Returns a PrintWriter object that can send character text to the client.

使用字節流響應中文

  1. 編寫代碼

****使用上述代碼向頁面輸出中文是否會有亂碼?

  1. 不一定
    1. 其實這個亂碼的產生與中文轉成字節數組及瀏覽器打開方式(打開的時候採用的默認字符集)有關
  2. 解決:
    1. 將中文轉成字節數組的時候和瀏覽器默認打開的時候採用的字符集一致即可。

使用字符流響應中文

  1. 編寫代碼

****使用上述代碼向頁面輸出中文是否會產生亂碼?

  1. 一定亂碼
    1. 原因:
      1. 字符流是有緩衝區的,response獲得字符流,response設計默認的緩衝區編碼是ISO-8859-1。這個字符集不支持中文的。
    2. 解決:
      1. 設置response獲得字符流緩衝區的編碼和設置瀏覽器默認打開時候採用的字符集一致即可。

字符流向頁面響應中文,有一種簡化的方式:

 

/**
 * Response響應中文的處理
 */
public class ResponseDemo3 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		test2(response);
	}
	/**
	 * 使用字符流輸出中文
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	private void test2(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
		// 設置瀏覽器默認打開的時候採用的字符集:
		// response.setHeader("Content-Type", "text/html;charset=UTF-8");
		// 設置response獲得字符流的緩衝區的編碼:
		// response.setCharacterEncoding("UTF-8");
		// 簡化代碼
		response.setContentType("text/html;charset=UTF-8");
		// 會不會產生亂碼
		response.getWriter().println("中文");
	}
	/**
	 * 使用字節流輸出中文
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	private void test1(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
		// 使用字節流的方式輸出中文:
		ServletOutputStream outputStream = response.getOutputStream();
		// 設置瀏覽器默認打開的時候採用的字符集
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		// 設置中文轉成字節數組字符集編碼
		outputStream.write("中文".getBytes("UTF-8"));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
  • Request

什麼是Request對象:開發的軟件都是B/S結構軟件,從瀏覽器向服務器提交一些數據,將這些內容進行封裝就封裝成了一個請求對象(Request對象)。

獲得請求的方式

String getMethod()
          返回用於發出此請求的 HTTP 方法的名稱,例如 GET、POST 或 PUT。

獲得請求路徑後的提交參數的字符串

 String getQueryString()
          返回包含在請求 URL 中路徑後面的查詢字符串。如果 URL 沒有查詢字符串,則此方法返回 null。

獲得請求路徑的URL和URI

URL:URL(Uniform Resource Locator,統一資源定位符),它是WWW的統一資源定位標誌,就是指網絡地址。

URI:統一資源標識符(Uniform Resource Identifier,URI)是一個用於標識某一互聯網資源名稱的字符串。 該種標識允許用戶對任何(包括本地和互聯網)的資源通過特定的協議進行交互操作。

StringBuffer getRequestURL() 重新構造客戶端用於發出請求的 URL。返回的 URL 包含一個協議、服務器名稱、端口號、服務器路徑,但是不包含查詢字符串參數。
String getRequestURI() 返回此請求的 URL 的一部分,從協議名稱一直到 HTTP 請求的第一行中的查詢字符串。Web 容器不會解碼此 String。例如: HTTP 請求的第一行  返回的值 
POST /some/path.html HTTP/1.1  /some/path.html  
GET http://foo.bar/a.html HTTP/1.0   /a.html  
HEAD /xyz?a=b HTTP/1.1  /xyz  

獲得客戶機的IP地址: 方法在其父類裏面

 String getRemoteAddr()
         返回發送請求的客戶端或最後一個代理的 Internet Protocol (IP) 地址。
  • 獲得請求頭的方法

獲得一個key對應一個value的請求頭

 String getHeader(String name)
          Returns the value of the specified request header as a String.

獲得一個key對應多個value的請求頭

Enumeration getHeaders(String name)
          Returns all the values of the specified request header as an Enumeration of String objects.

獲得請求參數的方法

  • 獲得提交的參數(一個name對應一個value)

  • 獲得提交的參數(一個name對應多個value)

  • 獲得提交的參數,將提交的參數的名稱和對應的值存入到一個Map集合中

請求地址: http://192.168.109.1:8080/JavaWeb/RequestDemo1?id=01&name=‘l李茂貞’

package com.request;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RequestDemo1
 */
public class RequestDemo1 extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲得請求的方式
		String requestMethod = request.getMethod();
		System.out.println("獲得請求的方式:" + requestMethod);
		
		//獲得請求路徑後的提交參數的字符串
		String parameters = request.getQueryString();
		System.out.println("獲取路徑後的參數:" + parameters);
		
		//獲得客戶機的IP地址: 方法在其父類裏面
		String ip = request.getRemoteAddr();
		System.out.println("客戶機的IP地址:" + ip);
		
		// 獲得請求頭的信息
		System.out.println("獲得客戶機瀏覽器類型:"+request.getHeader("User-Agent"));
		
		// 獲得請求路徑的URL和URI
		System.out.println("請求路徑的URL:"+request.getRequestURL());
		System.out.println("請求路徑的URI:"+request.getRequestURI());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

/*
獲得請求的方式:GET
獲取路徑後的參數:id=01&name=%27%E6%9D%8E%E8%8C%82%E8%B4%9E%27
客戶機的IP地址:192.168.109.1
獲得客戶機瀏覽器類型:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36
請求路徑的URL:http://192.168.109.1:8080/JavaWeb/RequestDemo1
請求路徑的URI:/JavaWeb/RequestDemo1

*/
  • Request作爲域對象存取數據的方法

  • 向request域中存數據

  • 從request域中獲取數據

  • 從request域中移除數據

 

 

 String getParameter(String name)
          以 String 形式返回請求參數的值,如果該參數不存在,則返回 null。
 Map getParameterMap()
          返回此請求的參數的 java.util.Map。請求參數是與請求一起發送的額外信息。
 Enumeration getParameterNames()
          返回包含此請求中所包含參數的名稱的 String 對象的 Enumeration。如果該請求沒有參數,則此方法返回一個空的 Enumeration。 
 String[] getParameterValues(String name)
          返回包含給定請求參數擁有的所有值的 String 對象數組,如果該參數不存在,則返回 null。 
/**
 * 表單提交數據
 */
public class RequestDemo02 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// getParameter接收用戶名和密碼:
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username:" + username + ", password:" + password);
		
		// 接收愛好:
		String[] hobby = request.getParameterValues("hobby");
		System.out.println("愛好:" + Arrays.toString(hobby));
				
		//getParameterMap()
		Map<String, String[]> map = request.getParameterMap();
		for (String key:map.keySet()) {
			String[] value = map.get(key);
			System.out.println(key+"    "+Arrays.toString(value));
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

get請求方式

<h1>request接收表單參數</h1>
<form action="/web01/RequestDemo2" method="get">
	用戶名:<input type="text" name="username"/><br/>
	密碼:<input type="password" name="password"><br/>
	性別:<input type="radio" name="sex" value="man"/>男<input type="radio" name="sex" value="woman"/>女<br/>
	籍貫:<select name="city">
		<option value="beijing">北京市</option>
		<option value="shanghai">上海市</option>
		<option value="shenzhen">深圳市</option>
	</select><br/>
	愛好:<input type="checkbox" name="hobby" value="basketball"/>籃球
	<input type="checkbox" name="hobby" value="football"/>足球
	<input type="checkbox" name="hobby" value="volleyball"/>排球<br/>
	自我介紹:<textarea name="info" rows="3" cols="8"></textarea><br/>
	<input type="submit" value="提交">
</form> 

 

http://localhost:8080/JavaWeb/RequestDemo02?username=%E6%9D%8E%E8%8C%82%E8%B4%9E&password=123456&sex=man&city=shanghai&hobby=basketball&hobby=football&info=%E5%A3%81%E7%AB%8B%E5%8D%83%E4%BB%9E%EF%BC%8C%E6%97%A0%E6%AC%B2%E5%88%99%E5%88%9A


/*
username:李茂貞, password:123456
愛好:[basketball, football]
username    [李茂貞]
password    [123456]
sex    [man]
city    [shanghai]
hobby    [basketball, football]
info    [壁立千仞,無欲則剛]

*/

post請求方式

<h1>request接收表單參數</h1>
<form action="/JavaWeb/RequestDemo02" method="post">
	用戶名:<input type="text" name="username"/><br/>
	密碼:<input type="password" name="password"><br/>
	性別:<input type="radio" name="sex" value="man"/>男<input type="radio" name="sex" value="woman"/>女<br/>
	籍貫:<select name="city">
		<option value="beijing">北京市</option>
		<option value="shanghai">上海市</option>
		<option value="shenzhen">深圳市</option>
	</select><br/>
	愛好:<input type="checkbox" name="hobby" value="basketball"/>籃球
	<input type="checkbox" name="hobby" value="football"/>足球
	<input type="checkbox" name="hobby" value="volleyball"/>排球<br/>
	自我介紹:<textarea name="info" rows="3" cols="8"></textarea><br/>
	<input type="submit" value="提交">
</form> 

http://localhost:8080/JavaWeb/RequestDemo02
/*
username:ææ·³é£, password:123456
愛好:[basketball, football]
username    [ææ·³é£]
password    [123456]
sex    [man]
city    [shenzhen]
hobby    [basketball, football]
info    [海纳ç¾å·ï¼æ容ä¹å¤§]

*/
  • Request對象接收中文亂碼問題

/**
 * Request接收中文數據
 */
public class RequestDemo3 extends HttpServlet {
	/**
	 * 演示get方式處理中文亂碼
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 接收數據:
		// request.setCharacterEncoding("UTF-8");
		/**
		 * 產生亂碼原因:
		 * * get方式提交的數據在請求行的url後面,在地址欄上其實就已經進行了一次URL的編碼了。
		 * 解決方案:
		 * * 將存入到request緩衝區中的值以ISO-8859-1的方式獲取到,以UTF-8的方式進行解碼。
		 */
		String name = request.getParameter("name");
		/*String encode = URLEncoder.encode(name, "ISO-8859-1");
		String decode = URLDecoder.decode(encode, "UTF-8");
		System.out.println("姓名:"+decode);*/
		String value = new String(name.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println("姓名:"+value);
	}

	/**
	 * 演示post方式處理中文亂碼
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// 接收數據:
		/**
		 * 產生亂碼的原因:
		 * * post方式提交的數據是在請求體中,request對象接收到數據之後,放入request的緩衝區中。緩衝區就有編碼(默認ISO-8859-1:不支持中文).
		 * 解決方案:
		 * * 將request的緩衝區的編碼修改了即可。
		 */
		// 設置緩衝區的編碼
		request.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		System.out.println("姓名:"+name);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章