HTTP:
* 概念:Hyper Text Transfer Protocol 超文本傳輸協議
* 傳輸協議:定義了,客戶端和服務器端通信時,發送數據的格式
* 特點:
1. 基於TCP/IP的高級協議
2. 默認端口號:80
3. 基於請求/響應模型的:一次請求對應一次響應
4. 無狀態的:每次請求之間相互獨立,不能交互數據
* 歷史版本:
* 1.0:每一次請求響應都會建立新的連接,一次請求響應結束後自動斷開連接
* 1.1:複用連接,一次請求響應結束後等待一段時間看是否有請求
* 請求消息數據格式:四部分:請求行、請求頭、請求空行、請求體
1. 請求行
格式:請求方式 請求url 請求協議/版本
如:GET /login.html HTTP/1.1
* 請求方式:
* HTTP協議有7中請求方式,常用的有兩種
* GET:
1. 請求參數在請求行中,在url後。
2. 請求的url長度有限制的
3. 不太安全
* POST:
1. 請求參數在請求體中
2. 請求的url長度沒有限制的
3. 相對安全
2. 請求頭:客戶端瀏覽器告訴服務器一些信息
請求頭名稱: 請求頭值
* 常見的請求頭:
1. User-Agent:瀏覽器告訴服務器,我訪問你使用的瀏覽器版本信息
* 可以在服務器端獲取該頭的信息,解決瀏覽器的兼容性問題
2. Referer:http://localhost/login.html
* 告訴服務器,我(當前請求)從哪裏來,即從哪裏超鏈接過來。
* 作用:
1. 防盜鏈:
2. 統計工作:
3. 請求空行
空行,就是用於分割POST請求的請求頭,和請求體的。
4. 請求體(正文):
* 封裝POST請求消息的請求參數的
* 字符串格式:
POST /login.html HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: http://localhost/login.html
Connection: keep-alive
Upgrade-Insecure-Requests: 1
/* 這裏是請求空行 */
username=zhangsan
* 響應消息數據格式
Request:請求消息
1. request對象和response對象的原理
1. request和response對象是由服務器創建的。我們來使用它們
2. request對象是來獲取請求消息,response對象是來設置響應消息
2. request對象繼承體系結構:
ServletRequest -- 接口
| 繼承
HttpServletRequest -- 接口
| 實現
org.apache.catalina.connector.RequestFacade 類(tomcat實現)(System.out.println(req);)
3. request功能:
1. 獲取請求消息數據
1. 獲取請求行數據
* GET /day14/demo1?name=zhangsan HTTP/1.1
* 方法:
1. 獲取請求方式 :GET
* String getMethod()
2. 獲取虛擬目錄:/day14 ————常用
* String getContextPath()
3. 獲取Servlet路徑: /demo1
* String getServletPath()
4. 獲取get方式請求參數:name=zhangsan
* String getQueryString()
5. 獲取請求URI:/day14/demo1 ————常用
* String getRequestURI(): /day14/demo1
* StringBuffer getRequestURL() :http://localhost/day14/demo1
URI、URL區別:
* URL:統一資源定位符 : http://localhost/day14/demo1 中華人民共和國
* URI:統一資源標識符 : /day14/demo1 共和國(範圍更大)
6. 獲取協議及版本:HTTP/1.1
* String getProtocol()
7. 獲取客戶機的IP地址:
* String getRemoteAddr()
2. 獲取請求頭數據
* 方法:
* String getHeader(String name):通過請求頭的名稱獲取請求頭的值。————常用(請求體就那些,需要什麼獲取什麼)
* Enumeration<String> getHeaderNames():獲取所有的請求頭名稱,Enumeration可相當於迭代器遍歷
// 獲取所有請求頭名稱
Enumeration<String> headerNames = req.getHeaderNames();
while(headerNames.hasMoreElements()){
String headName = headerNames.nextElement();
System.out.println(headName);
}
// 獲取指定請求頭名稱的值,並根據值判斷瀏覽器
String str = req.getHeader("user-agent");
if(str.contains("Chrome")){
System.out.println("谷歌");
}else if (str.contains("Firefox")){
System.out.println("火狐");
}
// 獲取鏈接來源
System.out.println(req.getHeader("referer")); //打印鏈接來源,即那個頁面鏈接到此地址,若不是鏈接過來的,則爲null
3. 獲取請求體數據:
* 請求體:只有POST請求方式,纔有請求體,在請求體中封裝了POST請求的請求參數
* 步驟:
1. 獲取流對象
* BufferedReader getReader():獲取字符輸入流,只能操作字符數據
BufferedReader bufferedReader = req.getReader();
System.out.println(bufferedReader.readLine());
* ServletInputStream getInputStream():獲取字節輸入流,可以操作所有類型數據
* 在文件上傳知識點後講解
2. 再從流對象中拿數據
2. 其他功能:————重要常用
1. 獲取請求參數通用方式:不論get還是post請求方式都可以使用下列方法來獲取請求參數
1. String getParameter(String name):(常用)根據參數名稱獲取參數值,只能獲取一個值,複選框選擇多個時不好用,此時使用第二種
2. String[] getParameterValues(String name):根據參數名稱獲取參數值的數組 hobby=xx&hobby=game
3. Enumeration<String> getParameterNames():獲取所有請求的參數名稱
4. Map<String,String[]> getParameterMap():(常用)獲取所有參數的map集合
以上方法不論Get還是Post都一樣,那麼只需實現一個get即可,post方法體調用get方法。
* 中文亂碼問題:
* get方式:tomcat 8 已經將get方式亂碼問題解決了
* post方式:會亂碼
* 解決:在獲取參數前,設置request的編碼request.setCharacterEncoding("utf-8");
2. 請求轉發:一種在服務器內部的資源跳轉方式,一次請求訪問多個資源
1. 步驟:
1. 通過request對象獲取請求轉發器對象:RequestDispatcher getRequestDispatcher(String path)
2. 使用RequestDispatcher對象來進行轉發:forward(ServletRequest request, ServletResponse response)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Demo2");
// 跳轉到demo4路徑執行,但瀏覽器地址還是當前地址
req.getRequestDispatcher("/demo4").forward(req, resp);
}
2. 特點:
1. 瀏覽器地址欄路徑不發生變化
2. 只能轉發到當前服務器內部資源中。
3. 轉發是一次請求
3. 共享數據:
* 域對象:一個有作用範圍的對象,可以在範圍內共享數據
* request域:代表一次請求的範圍,一般用於請求轉發的多個資源中共享數據
* 方法:
1. void setAttribute(String name,Object obj):存儲數據
2. Object getAttitude(String name):通過鍵獲取值
3. void removeAttribute(String name):通過鍵移除鍵值對
在請求轉發中,可在請求轉發中設置共享數據,然後在轉發後的方法體中訪問共享數據。
4. 獲取ServletContext:
* ServletContext getServletContext()
請求響應消息過程示意圖:
Referer的一些作用:
響應消息:
響應消息:服務器端發送給客戶端的數據
* 數據格式:
1. 響應行
1. 組成:協議/版本 響應狀態碼 狀態碼描述
2. 響應狀態碼:服務器告訴客戶端瀏覽器本次請求和響應的一個狀態。
1. 狀態碼都是3位數字
2. 分類:
1. 1xx:服務器就收客戶端消息,但沒有接受完成,等待一段時間後,發送1xx多狀態碼(很少出現)
2. 2xx:成功。代表:200
3. 3xx:重定向。代表:302(重定向),304(訪問緩存)
重定向:跳轉操作。告訴客戶端去訪問另一個資源
訪問緩存:告訴客戶端文件資源沒有更改且客戶端本地有緩存,這樣可以直接去加載本地緩存
4. 4xx:客戶端錯誤。
* 代表:
* 404(請求路徑沒有對應的資源)
* 405:請求方式沒有對應的doXxx方法
5. 5xx:服務器端錯誤。代表:500(服務器內部出現異常)
2. 響應頭:
1. 格式:頭名稱: 值
2. 常見的響應頭:
1. Content-Type:服務器告訴客戶端本次響應體數據格式以及編碼格式
2. Content-disposition:服務器告訴客戶端以什麼格式打開響應體數據
* 值:
* in-line:默認值,在當前頁面內打開
* attachment;filename=xxx:以附件形式打開響應體。文件下載
3. 響應空行
4. 響應體:傳輸的數據
* 響應字符串格式
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Content-Length: 101
Date: Wed, 06 Jun 2018 07:08:42 GMT
<html>
<head>
<title>$Title$</title>
</head>
<body>
hello , response
</body>
</html>
Response對象
* 功能:設置響應消息
1. 設置響應行
1. 格式:HTTP/1.1 200 ok
2. 設置狀態碼:setStatus(int sc)
2. 設置響應頭:setHeader(String name, String value)
3. 設置響應體:
* 使用步驟:
1. 獲取輸出流
* 字符輸出流:PrintWriter getWriter()
* 字節輸出流:ServletOutputStream getOutputStream()
2. 使用輸出流,將數據輸出到客戶端瀏覽器
* 案例:
1. 完成重定向(重要)
* 重定向:資源跳轉的方式
* 代碼實現:
//1. 設置狀態碼爲302,告訴瀏覽器重定向
response.setStatus(302);
//2.設置響應頭location,告訴瀏覽器重定向的路徑
response.setHeader("location","/day15/responseDemo2");
//簡單的重定向方法
response.sendRedirect("/day15/responseDemo2");
* 重定向的特點:redirect
1. 地址欄發生變化
2. 重定向可以訪問其他站點(服務器)的資源
3. 重定向是兩次請求。不能使用request對象來共享數據
* 轉發的特點:forward
1. 轉發地址欄路徑不變
2. 轉發只能訪問當前服務器下的資源
3. 轉發是一次請求,可以使用request對象來共享數據
* forward 和 redirect 區別
* 路徑寫法:
1. 路徑分類
1. 相對路徑:通過相對路徑不可以確定唯一資源
* 如:./index.html
* 不以/開頭,以.開頭路徑
* 規則:找到當前資源和目標資源之間的相對位置關係
* ./:當前目錄
* ../:後退一級目錄
2. 絕對路徑:通過絕對路徑可以確定唯一資源
* 如:http://localhost/day15/responseDemo2 /day15/responseDemo2
* 以/開頭的路徑
* 規則:判斷定義的路徑是給誰用的?判斷請求將來從哪兒發出
* 給客戶端瀏覽器使用:需要加虛擬目錄(項目的訪問路徑)
* 建議虛擬目錄動態獲取:request.getContextPath()
* <a> , <form> 重定向...
* 給服務器使用:不需要加虛擬目錄
* 轉發路徑
2. 服務器輸出字符數據到瀏覽器
* 步驟:
1. 獲取字符輸出流PrintWriter pw = response.getWriter();
2. 輸出數據pw.write("");
* 注意:
* 亂碼問題:
1. PrintWriter pw = response.getWriter();獲取的流的默認編碼是ISO-8859-1
2. 設置該流的默認編碼
3. 告訴瀏覽器響應體使用的編碼
//簡單的形式,設置編碼,是在獲取流之前設置
response.setContentType("text/html;charset=utf-8");
3. 服務器輸出字節數據到瀏覽器
* 步驟:
1. 獲取字節輸出流resp.getOutputStream();
2. 輸出數據write("hell0".getBytes());裏面傳入二進制數組
4. 驗證碼
1. 本質:圖片
2. 目的:防止惡意表單註冊
ServletContext對象
1. 概念:代表整個web應用,可以和程序的容器(服務器)來通信
2. 獲取:兩種獲取的是同一個對象,都一樣。
1. 通過request對象獲取
request.getServletContext();
2. 通過HttpServlet獲取
this.getServletContext();
3. 功能:
1. 獲取MIME類型:
* MIME類型:在互聯網通信過程中定義的一種文件數據類型
* 格式: 大類型/小類型 text/html image/jpeg
* 獲取:String getMimeType(String file)
2. 域對象:共享數據
1. setAttribute(String name,Object value)
2. getAttribute(String name)
3. removeAttribute(String name)
* ServletContext對象範圍:所有用戶所有請求的數據。謹慎使用!!
3. 獲取文件的真實(服務器)路徑
1. 方法:String getRealPath(String path)
String b = context.getRealPath("/b.txt");//web目錄下資源訪問
System.out.println(b);
String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目錄下的資源訪問
System.out.println(c);
String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目錄下的資源訪問
System.out.println(a);
* 文件下載需求:
1. 頁面顯示超鏈接
2. 點擊超鏈接後彈出下載提示框
3. 完成圖片文件下載
* 分析:
1. 超鏈接指向的資源如果能夠被瀏覽器解析,則在瀏覽器中展示,如果不能解析,則彈出下載提示框。不滿足需求
2. 任何資源都必須彈出下載提示框
3. 使用響應頭設置資源的打開方式:
* content-disposition:attachment;filename=xxx
文件下載案例
* 步驟:
1. 定義頁面,編輯超鏈接href屬性,指向Servlet,傳遞資源名稱filename
2. 定義Servlet
1. 獲取文件名稱
2. 使用字節輸入流加載文件進內存
3. 指定response的響應頭: content-disposition:attachment;filename=xxx
4. 將數據寫出到response輸出流
* 問題:
* 中文文件問題
* 解決思路:
1. 獲取客戶端使用的瀏覽器版本信息
2. 根據不同的版本信息,設置filename的編碼方式不同
驗證碼生成
package web;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
/**
* 生成驗證碼,響應給頁面
*/
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1 生成驗證碼圖片
int width = 100;
int height = 40;
//1.1 生成一個圖片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//1.2 填充背景色
Graphics g = image.getGraphics(); //畫筆對象
g.setColor(Color.pink);
g.fillRect(0, 0, width, height);
//1.3畫邊框
g.setColor(Color.blue);
g.drawRect(0,0, width-1, height-1);
//1.4 生成隨機字符並寫到圖片上
String string = "ABCDEFGHIGKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random ran = new Random();
StringBuilder checkCode = new StringBuilder();
g.setFont(new Font(null, Font.BOLD + Font.ITALIC, 20));
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(string.length()-1);
char ch = string.charAt(index);
checkCode.append(ch);
g.drawString(String.valueOf(ch),width/5*i, height>>1);
}
//1.5 畫干擾線
for (int i = 1; i <= 5; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//將圖片輸出到頁面
ImageIO.write(image, "jpg", resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
將驗證碼應用到html頁面,如下一個註冊頁面,點擊驗證碼則切換。
<!DOCTYPE html>
<html lang="CH">
<head>
<meta charset="UTF-8">
<title>註冊</title>
<style>
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body{
background: url("./backgroud.jpg") no-repeat center;
padding-top: 25px;
}
table{
margin:auto; /*居中*/
margin-top: 40px;
width: 40%;
height: 100%;
background: azure;
/*border: gray solid 5px;*/
}
.td_left{
width: 150px;
height: 45px;
text-align: right;
/*border: crimson solid 1px;*/
}
.td_right{
width: 250px;
height: 45px;
text-align: left;
/*border: crimson solid 1px;*/
}
.submit{
text-align: center;
height: 45px;
/*border: crimson solid 1px;*/
}
#password,#name,#username,#tel,#email,#sex{
margin-left: 50px;
width: 200px;
height: 25px;
border-radius: 5px;
horiz-align: center;
}
#checkImg{
margin-left: 50px;
margin-top: 10px;
margin-bottom: 10px;
width: 200px;
height: 25px;
border-radius: 5px;
horiz-align: center;
}
#img_checkCode{
float: right;
width: 100px;
height: 35px;
margin-bottom: 5px;
margin-top: 5px;
margin-right: 100px;
}
#submit{
width: 40px;
height: 25px;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="main-border">
<form action="/login/registerServlet" method="post">
<table>
<tr>
<td class="td_left">姓名</td>
<td class="td_right"><input type="text" name="name" placeholder="請輸入姓名" id="name" required></td>
</tr>
<tr>
<td class="td_left">姓別</td>
<td class="td_right">
<span id="sex">男</span>
<input type="radio" name="sex" value="male">
<span>女</span>
<input type="radio" name="sex" value="female" >
</td>
</tr>
<tr>
<td class="td_left">用戶名</td>
<td class="td_right"><input type="text" name="username" placeholder="請輸入用戶名" id="username" required></td>
</tr>
<tr>
<td class="td_left">密碼</td>
<td class="td_right"><input type="password" placeholder="請輸入密碼" name="password" id="password" required></td>
</tr>
<tr>
<td class="td_left">電話號碼</td>
<td class="td_right"><input type="number" name="tel" id="tel" required></td>
</tr>
<tr>
<td class="td_left">電子郵箱</td>
<td class="td_right"><input type="email" name="email" id="email" required></td>
</tr>
<tr>
<td class="td_left">驗證碼</td>
<td class="td_right">
<input type="text" name="checkImg" id="checkImg" required>
<img src="/login/checkCodeServlet" id="img_checkCode">
</td>
</tr>
<tr>
<td class="submit" colspan="2"><input type="submit" value="註冊" id="submit"></td>
</tr>
</table>
</form>
</div>
<script>
/**
* 驗證碼點擊切換
*/
window.onload = function () {
//1 獲取圖片對象
var img = document.getElementById("img_checkCode");
// 2綁定單擊事件
img.onclick = function () {
//加時間戳
var date = new Date().getTime();
//由於瀏覽器本地緩存的原因,圖片名沒有變,請求後還是那個圖片,故瀏覽器還是加載原來的圖。
//故在後面加一個參數欺騙服務器,但要保證多次點擊不重複,參數用時間戳。
img.src = "/login/checkCodeServlet?"+date;
}
}
</script>
</body>
</html>
文件下載彈框實現。
定義一個頁面,頁面中定義超鏈接,鏈接到下載資源代碼;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>下載1</title>
</head>
<body>
<a href="/login/downloadServlet?filename=background.jpg">下載background.jpg</a>
</body>
</html>
package web;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 獲取請求參數,文件名稱
String filename = req.getParameter("filename");
//2. 使用字節輸入流加載進內存
//2.1 找到文件服務器地址
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename); //圖片放在web/img/下
//2.2 用字節流關聯
FileInputStream fileInputStream = new FileInputStream(realPath);
//3 設置response的響應頭
String mimeType = servletContext.getMimeType(filename);
resp.setHeader("content-type", mimeType);
resp.setHeader("content-disposition", "attachment;filename="+filename);
//4 將輸入流數據寫出到輸出流
ServletOutputStream outputStream = resp.getOutputStream();
byte[] ins = new byte[1024*8];
int len;
while((len=fileInputStream.read(ins))!=-1){
outputStream.write(ins,0, len);
}
fileInputStream.close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}