1. request對象和response對象的原理
1. request和response對象是由服務器創建的。我們來使用它們
2. request對象是來獲取請求消息,response對象是來設置響應消息
2. request對象繼承體系結構:
ServletRequest -- 接口
| 繼承
HttpServletRequest -- 接口
| 實現
org.apache.catalina.connector.RequestFacade 類(tomcat)
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
* 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():獲取所有的請求頭名稱
3. 獲取請求體數據:
* 請求體:只有POST請求方式,才有請求體,在請求體中封裝了POST請求的請求參數
* 步驟:
1. 獲取流對象
* BufferedReader getReader():獲取字符輸入流,只能操作字符數據
* ServletInputStream getInputStream():獲取字節輸入流,可以操作所有類型數據
* 在文件上傳知識點后講解
2. 再從流對象中拿數據
2. 其他功能:
1. 獲取請求參數通用方式:不論get還是post請求方式都可以使用下列方法來獲取請求參數
1. String getParameter(String name):根據參數名稱獲取參數值 username=zs&password=123
2. String[] getParameterValues(String name):根據參數名稱獲取參數值的數組 hobby=xx&hobby=game
3. Enumeration<String> getParameterNames():獲取所有請求的參數名稱
4. Map<String,String[]> getParameterMap():獲取所有參數的map集合
* 中文亂碼問題:
* 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)
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()
