一:Reponse對象的概念
當客戶端發送http請求時,服務器端會對每一次請求,創建request對象和response對象。
response對象包括三個部分:響應頭、響應狀態碼以及響應體
二:response對象案例分析
1:向客戶端輸出中文數據
1 package com.hlcui.servlet; 2 3 import java.io.IOException; 4 import java.io.OutputStream; 5 import java.io.PrintWriter; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 public class ServletDemo6 extends HttpServlet { 13 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 17 String data = "好好學習!"; 18 //獲取向客戶端寫數據的輸出流 19 OutputStream out = response.getOutputStream(); 20 out.write(data.getBytes()); 21 } 22 23 public void doPost(HttpServletRequest request, HttpServletResponse response) 24 throws ServletException, IOException { 25 doGet(request,response); 26 } 27 28 }
瀏覽器打印:
結果正確!
這里面要注意,因為我在服務器端對數據進行編碼時,沒有指定使用哪種字符集,所以默認是使用gb2312,
而瀏覽器端解析時也是gb2312,所以正確顯示,如果我指定編碼字符為UTF-8,結果如下:
使用UTF-8對數據進行編碼:
1 out.write(data.getBytes("UTF-8"));
打印結果為亂碼:
因為我服務器端指定編碼為UTF-8,而瀏覽器還是使用默認的解碼方式進行解碼,導致亂碼。
解決方式:
可以通過設置瀏覽器的查看方式(使用UTF-8解析服務器發送過來的數據),但是不是根本辦法,最好的辦法是在
服務器端告訴瀏覽器以何種方式進行解碼。修改如下:
1 response.setHeader("content-type", "text/html;charset=utf-8");
結果是正確的!
可以使用html標簽中meta進行模擬服務器response響應頭:
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 String data = "好好學習!"; 4 //獲取向客戶端寫數據的輸出流 5 OutputStream out = response.getOutputStream(); 6 out.write("<meta http-equiv='content-type' content='text/html;charset=utf-8'>".getBytes()); 7 out.write(data.getBytes("UTF-8")); 8 }
結果依然是正確的!
這里我們要了解服務端使用字符集編碼以及瀏覽器解碼的機制:
1:服務器端對數據進行編碼,編碼時使用字符集(gb2312或者UTF-8),沒有指定默認為gb2312
2:瀏覽器解析response數據時,默認gb2312,它會拿着編碼數據導字符集中取查詢
如果我們想在瀏覽器輸出99,那么服務端首先端99進行編碼,在瀏覽器端,會拿着99的編碼到
字符集中查詢編碼對應的內容。
1 out.write("99".getBytes("UTF-8"));
對99這個字符串進行UTF-8的編碼。
printWriter對象與OutputStream對象
如果想瀏覽器寫圖片、視頻以及音頻文件等二進制文件時,必須使用字節流outputStream。
如果向瀏覽器寫字符串時,可以使用printwriter對象,下面使用printWriter向瀏覽器寫中文:
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 String data = "好好學習!"; 4 //獲取向客戶端寫數據的輸出流 5 PrintWriter out = response.getWriter(); 6 out.write(data); 7 }
輸出結果:
出現亂碼,因為response向對數據進行編碼時使用的ISO8859-1,而瀏覽器解析使用的gb2312,所以查詢不到,報????
解決方法:
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 //設置response對數據的編碼方式 4 response.setCharacterEncoding("UTF-8"); 5 //告訴瀏覽器解碼方式 6 response.setHeader("content-type", "text/html;charset=utf-8"); 7 String data = "好好學習!"; 8 //獲取向客戶端寫數據的輸出流 9 PrintWriter out = response.getWriter(); 10 out.write(data); 11 }
輸出正確結果:
其實還可以使用response.setContentType("text/html;charset=utf-8");
這是servlet封裝好的API,相當於下面兩句的內容
//設置response對數據的編碼方式
response.setCharacterEncoding("UTF-8");
//告訴瀏覽器解碼方式
response.setHeader("content-type", "text/html;charset=utf-8");