[toc]
## HTTP簡介
WEB瀏覽器與WEB服務器之間的一問一答的交互過程必須遵循一定的規則,這個規則就是HTTP協議。
HTTP是 hypertext transfer protocol(超文本傳輸協議)的簡寫,它是 TCP/IP 協議集中的一個應用層協議,用于定義WEB瀏覽器與WEB服務器之間交換數據的過程以及數據本身的格式。
## HTTP 的會話方式
四個步驟:

瀏覽器與WEB服務器的連接過程是短暫的,每次連接只處理一個請求和響應。對每一個頁面的訪問,瀏覽器與WEB服務器都要建立一次單獨的連接。
瀏覽器到WEB服務器之間的所有通訊都是完全獨立分開的請求和響應對。
## GET和POST請求
1.GET方法
GET方法是從指定的資源請求數據。<b>請注意,查詢字符串(名稱/值對)是在 GET 請求的 URL 中發送的。</b>
有關 GET 請求的其他一些注釋:
* GET 請求可被緩存
* GET 請求保留在瀏覽器歷史記錄中
* GET 請求可被收藏為書簽
* GET 請求不應在處理敏感數據時使用
* GET 請求有長度限制
* GET 請求只應當用于取回數據
2.POST方法
post方法是向指定的資源提交要被處理的數據,<b>請注意,查詢字符串(名稱/值對)是在 POST 請求的 HTTP 消息主體中發送的。</b>
有關 POST 請求的其他一些注釋:
* POST 請求不會被緩存
* POST 請求不會保留在瀏覽器歷史記錄中
* POST 不能被收藏為書簽
* POST 請求對數據長度沒有要求
## 如何在Servlet中獲取信息
這里我們可以新建一個Servlet(eclipse中直接有Servlet選項)。
~~~
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post");
}
}
~~~
在之前我們自己寫的Servlet當中,處理請求的service()方法,在這里其實也是,之所以能沒有出現service()方法,是因為HttpServlet這個類已經對原來不完整且代碼冗余的Servlet接口進行了實現和封裝。這里doGet和doPost分別對應接受get和post請求,方便、簡單。
這里可以對之前的表單進行驗證,看請求是否能夠發到對應的方法中。其中,方法的參數**HttpServletRequest request**和**HttpServletResponse response**封裝了**請求和響應**信息
#### 一.如何獲取請求信息
**HttpServletRequest**常用的方法:
①**String getParameter(String name)**
\--根據請求參數的名字,返回參數值,特別常用
~~~
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String password = request.getParameter("password");
System.out.println(user+" "+password);
}
~~~
②**String\[\] getParameterValues(String name)**
\--根據請求參數的名字,返回請求參數對應的字符串數組(例如:一組復選框-->名字是一樣的)
~~~
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String intrests[] = request.getParameterValues("hobby");
for(String str:intrests) {
System.out.println(str);
}
}
~~~
③Map getParameterMap()
\--返回請求參數的鍵值對:key:參數名,value:參數值(String數組)
#### 二.如何獲取響應信息
**HttpServletResponse**常用的方法:
①getWriter()方法
\--返回PrintWriter對象,調用這個對象的println()方法可以將信息直接打印在客戶的瀏覽器上
~~~
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("hello...");
}
~~~
②setContentType()方法
\--設置響應的類型
~~~
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/msword");
PrintWriter out = response.getWriter();
out.println("hello...");
}
~~~
③getOutputStream()方法,文件下載時講解使用。