HTTP協議:
1. 請求消息:客戶端發送給服務器端的數據
- 數據格式:
- 請求行
- 請求頭
- 請求空行
- 請求體
2. 響應消息:服務器端發送給客戶端的數據
- 數據格式:
- 響應行
- 組成:協議/版本 響應狀態碼 狀態碼描述
- 響應狀態碼:服務器告訴客戶端瀏覽器本次請求和響應的一個狀態。
- 狀態碼都是3位數字
- 分類:
- 1xx:服務器就收客戶端消息,但沒有接受完成,等待一段時間後,發送1xx多狀態碼
- 2xx:成功。代表:200
- 3xx:重定向。代表:302(重定向),304(訪問緩存)
- 4xx:客戶端錯誤。
代表:
- 404(請求路徑沒有對應的資源)
- 405:請求方式沒有對應的doXxx方法
- 5xx:服務器端錯誤。代表:500(服務器內部出現異常)
- 響應頭:
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. 設置響應行
- 格式:HTTP/1.1 200 ok
- 設置狀態碼:setStatus(int sc)
2. 設置響應頭:setHeader(String name, String value)
3. 設置響應體:
- 使用步驟:
- 獲取輸出流
- 字符輸出流:PrintWriter getWriter()
- 字節輸出流:ServletOutputStream getOutputStream()
- 使用輸出流,將數據輸出到客戶端瀏覽器
案例1:完成重定向:
- 重定向:資源跳轉的方式
下圖所示:
代碼實現:
//1. 設置狀態碼爲302
response.setStatus(302);
//2.設置響應頭location
response.setHeader("location","/day15/responseDemo2");
//簡單的重定向方法
response.sendRedirect("/day15/responseDemo2");
面試題:轉發和重定向的區別
- 重定向的特點:redirect
- 地址欄發生變化
- 重定向可以訪問其他站點(服務器)的資源
- 重定向是兩次請求。不能使用request對象來共享數據
- 轉發的特點:forward
- 轉發地址欄路徑不變
- 轉發只能訪問當前服務器下的資源
- 轉發是一次請求,可以使用request對象來共享數據
路徑寫法–路徑分類:
1. 相對路徑:通過相對路徑不可以確定唯一資源
- 如:./index.html
- 不以/開頭,以.開頭路徑
- 規則:找到當前資源和目標資源之間的相對位置關係
- ./:當前目錄
- ../:後退一級目錄
2. 絕對路徑:通過絕對路徑可以確定唯一資源。如:http://localhost/day15/responseDemo2 /day15/responseDemo2
- 以/開頭的路徑
- 規則:判斷定義的路徑是給誰用的?判斷請求將來從哪兒發出
- 給客戶端瀏覽器使用:需要加虛擬目錄(項目的訪問路徑)
- 建議虛擬目錄動態獲取:request.getContextPath()------如 <a> , <form> 重定向…等
- 給服務器使用:不需要加虛擬目錄
- 轉發路徑
動態獲取虛擬目錄:
//動態獲取虛擬目錄
String contextPath = request.getContextPath();
//簡單的重定向方法
response.sendRedirect(contextPath+"/Servlet");
//response.sendRedirect("http://www.itcast.cn");
案例2: 服務器輸出字符數據到瀏覽器
- 步驟:
- 獲取字符輸出流
- 輸出數據
- 注意:
- 亂碼問題:
1. PrintWriter pw = response.getWriter();獲取的流的默認編碼是ISO-8859-1
2. 設置該流的默認編碼
3. 告訴瀏覽器響應體使用的編碼
//簡單的形式,設置編碼,是在獲取流之前設置
response.setContentType(“text/html;charset=utf-8”);
代碼:
//設置編碼
response.setContentType("text/html;charset=utf-8");
//1.獲取字符輸出流
PrintWriter pw = response.getWriter();
//2.輸出數據
pw.write("你好");
案例3:服務器輸出字節數據到瀏覽器(圖片等)
- 步驟:
- 獲取字節輸出流
- 輸出數據
//設置編碼
response.setContentType("text/html;charset=utf-8");
//1.獲取字節輸入流
ServletOutputStream sos = response.getOutputStream();
//2.輸出數據
sos.write("你好".getBytes("utf-8"));
案例4:驗證碼
1. 本質:圖片
2. 目的:防止惡意表單註冊
編寫Servlet代碼:
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.創建一對象,在內存中圖片(驗證碼圖片對象)
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.美化圖片
//2.1 填充背景色
Graphics graphics = bi.getGraphics();//畫筆對象
graphics.setColor(Color.PINK);//設置顏色
graphics.fillRect(0,0,width,height);
//2.2畫邊框
graphics.setColor(Color.BLUE);
graphics.drawRect(0,0,width-1,height-1);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成隨機角標
Random random = new Random();
for (int i =1;i<=4;i++) {
int index = random.nextInt(str.length());
//獲取字符
char ch = str.charAt(index);
graphics.drawString(ch+"",width/5*i,height/2);
}
//2.4畫干擾線
graphics.setColor(Color.GREEN);
//隨機生成座標點
for (int i = 0;i<10;i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
//3.將圖片輸出到頁面展示
ImageIO.write(bi,"jpg", response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("aaaa");
this.doPost(request,response);
}
}
利用js實現圖片切換
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function () {
//1.獲取圖片對象
var img = document.getElementById("checkCode");
//2.綁定單擊事件
img.onclick = function () {
//加時間戳
var date = new Date().getTime();
img.src = "/day01/CheckCodeServlet?" + date;
}
}
</script>
</head>
<body>
<img id="checkCode" src="/day01/CheckCodeServlet">
</body>
</html>
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. 域對象:共享數據
- setAttribute(String name,Object value)
- getAttribute(String name)
- removeAttribute(String name)
- ServletContext對象範圍:所有用戶所有請求的數據
3. 獲取文件的真實(服務器)路徑
- 方法:String getRealPath(String path)
src目錄下的文件,在/WEB-INF/classes/
案例:
文件下載需求:
1. 頁面顯示超鏈接
2. 點擊超鏈接後彈出下載提示框
3. 完成圖片文件下載
分析:
1. 超鏈接指向的資源如果能夠被瀏覽器解析,則在瀏覽器中展示,如果不能解析,則彈出下載提示框。不滿足需求
2. 任何資源都必須彈出下載提示框
3. 使用響應頭設置資源的打開方式:
- content-disposition:attachment;filename=xxx
步驟:
1. 定義頁面,編輯超鏈接href屬性,指向Servlet,傳遞資源名稱filename
2. 定義Servlet
- 獲取文件名稱
- 使用字節輸入流加載文件進內存
- 指定response的響應頭: content-disposition:attachment;filename=xxx
- 將數據寫出到response輸出流
問題:
- 中文文件問題解決思路
- 獲取客戶端使用的瀏覽器版本信息
- 根據不同的版本信息,設置filename的編碼方式不同
編寫Servlet代碼:
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.獲取請求參數,文件名稱
String fillname = request.getParameter("fillname");
//2.使用字節輸入流加載文件進內存
//2.1找到文件服務器路徑
ServletContext context = this.getServletContext();
String downloadPath = context.getRealPath("/img/" + fillname);
//2.2用字節流關聯
FileInputStream fis = new FileInputStream(downloadPath);
//3.設置response的響應頭
//3.1設置響應頭類型:content-type
String type = context.getMimeType(fillname);
response.setHeader("content-type", type);
//3.2設置響應頭打開方式:content-disposition
//解決中文文件名問題
//1.獲取user-agent請求頭
String user_agent = request.getHeader("user-agent");
//2.使用工具類方法編碼文件名即可
String fileName = DownLoadUtils.getFileName(user_agent, fillname);
response.setHeader("content-disposition", "attachment;filename=" + fileName);
//4.將輸入流的數據寫出到輸出流中
ServletOutputStream sos = response.getOutputStream();
byte[] buff = new byte[1024 * 8];
int len = 0;
while ((len = fis.read(buff)) != -1) {
sos.write(buff, 0, len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
編寫前端下載代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>download</title>
</head>
<body>
<a href="/day01/img/2.jpg">圖片</a>
<a href="/day01/img/1.avi">視頻</a>
<hr>
<a href="/day01/DownloadServlet?fillname=2.jpg">圖片</a>
<a href="/day01/DownloadServlet?fillname=九尾.jpg">視頻</a>
</body>
</html>