本文是servlet的入門篇,主要簡單介紹下http協議
1.什么是http
_ 1.http協議:_
1. 復雜解釋:
http(超文本傳輸協議)是一個基于請求與響應模式的、無狀態的、應用層的協議,常基于TCP的連接方式,HTTP1.1版本中給出一種持續連接的機制,絕大多數的Web開發,都是構建在HTTP協議之上的Web應用。
2. 簡單說:
對瀏覽器客戶端 和 服務器端 之間數據傳輸的格式規范.
3. 協議版本:
http1.0:當前瀏覽器客戶端與服務器端建立連接之后,只能發送一次請求,一次請求之后連接關閉。
http1.1:當前瀏覽器客戶端與服務器端建立連接之后,可以在一次連接中發送多次請求。(基本都使用1.1)
請求一次資源就會出現一次請求,比如三張圖片,就有三次請求,如果圖片是一樣 的就只有一次請求;
2.查看http協議的工具:
1. chrome(谷歌)瀏覽器查看:
右鍵點擊查看元素(inspect element),點擊network即可;

2. 火狐:
使用火狐的firebug插件(右鍵->firebug->網絡)
3. 使用系統自帶的telnet工具(遠程訪問工具)
a)telnet localhost 8080 訪問tomcat服務器
b)ctrl+] 回車.可以看到回顯
c)輸入請求內容,回車,即可查看到服務器響應信息。
GET / HTTP/1.1Host: www.baidu.com
2.http協議內容:
- 請求:
GET /HttpSer HTTP/1.1Host: localhost:8080Connection: keep-aliveAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.85 Chrome/45.0.2454.85 Safari/537.36Accept-Encoding: gzip, deflate, sdchAccept-Language: en-US,en;q=0.8
- 響應:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/HttpSer/ Transfer-Encoding: chunked Date: Fri, 09 Oct 2015 08:55:42 GMT
下面將對這兩個協議進行介紹:
3.http請求介紹:
GET /HttpSer HTTP/1.1-請求行Host: localhost:8080Connection: keep-aliveAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.85 Chrome/45.0.2454.85 Safari/537.36Accept-Encoding: gzip, deflate, sdchAccept-Language: en-US,en;q=0.8
請求行介紹
GET /HttpSer HTTP/1.1 -請求行
1.請求資源的URL和URI比較:
URL: 統一資源定位符。http://localhost:8080/HttpSer/index.html。只能定位互聯網資源。是URI 的子集.
URI: 統一資源標記符。/HttpSer/index.html。用于標記任何資源。可以是本地文件系統,局域網的資源(//192.168.14.10/HttpSer/index.html),可以是互聯網。
2.請求方式:
常見的請求方式: GET 、 POST、 HEAD、 TRACE、 PUT、 CONNECT 、DELETE
常用的請求方式: GET(有將實體信息放在瀏覽器地址欄) 和 POST(隱藏實體內容)
3. servlet獲得請求行信息:_
/*** 1.1請求行的獲得*/System.out.println("請求方式:"+request.getMethod());System.out.println("請求URI:"+request.getRequestURI());System.out.println("請求url:"+request.getRequestURL());System.out.println("獲得協議:"+request.getProtocol());##輸出:請求方式:GET請求URI:/HttpSer/TestRequst請求url:http:獲得協議:HTTP/1.1
4. 測試提交方式:
新建立web工程,建立TestMethod.html文件:

建立Servlet類TestMethod.java修改get和post方法:
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("get 方式提交"); }
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("post 方式提交"); }
運行tomcat可以看淡提交方式的不同:瀏覽器地址欄顯示的不同,servlet調用的方法也不同;
get提交

post提交

經過對比請求可以發現
get方式在請求行多了?name=wang&pass=123
post多了實體內容:Content-Type: application/x-www-form-urlencoded
請求內容同如下:
#get方式:GET /HttpSer/TestMethod?name=wang&pass=123 HTTP/1.1Host: localhost:8080Connection: keep-aliveAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,**;q=0.8Origin: http:Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.85 Chrome/45.0.2454.85 Safari/537.36Content-Type: application/x-www-form-urlencodedReferer: http:Accept-Encoding: gzip, deflateAccept-Language: en-US,en;q=0.8
請求頭介紹:
1. 請求頭介紹:
請求頭主要包含一些有用信息:
1.Host: localhost:8080主機地址和端口
2.Connection: keep-alive 連接方式
3.User-Agent:瀏覽器的一些信息
4.Referer:來訪頁面
5.Content:實體內容;post才有
2. servlet獲得請求頭主要的方法:
request.getHeader(“Host”));通過建獲得相應請求的內容;
Enumeration headerNames = request.getHeaderNames();獲得請求頭所有的鍵值
3. 演示如下:
修改doget方法
/*** 設置參數查詢的編碼*該方法只能對請求實體內容的數據編碼起作用。POST提交的數據在實體內容中,所以該方法對POST方法有效!*GET方法的參數放在URI后面,所以對GET方式無效!!! */request.setCharacterEncoding("utf-8");/** * 1.1請求行的獲得 */ System.out.println("請求方式:"+request.getMethod()); System.out.println("請求URI:"+request.getRequestURI()); System.out.println("請求url:"+request.getRequestURL()); System.out.println("獲得協議:"+request.getProtocol());/** * 1.2請求頭的獲得 */ System.out.println("獲得host:"+request.getHeader("Host")); System.out.println("獲得瀏覽器的User-Agent:"+request.getHeader("User-Agent")); Enumeration<String> headerNames = request.getHeaderNames();while(headerNames.hasMoreElements()){ String key=headerNames.nextElement(); System.out.println(key+":"+request.getHeader(key)); }/** * 得到請求實體內容 * 比如:實體為name=peace&pass=1234 */ ServletInputStream in = request.getInputStream();byte[] buf=newbyte[1024];int len=0;while((len=in.read(buf))!=-1){ String str=new String(buf,0,len); System.out.println(str); }#輸出如下:請求方式:GET請求URI:/HttpSer/TestRequst請求url:http:獲得協議:HTTP/1.1獲得host:localhost:8080獲得瀏覽器的User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.101 Chrome/45.0.2454.101 Safari/537.36host:localhost:8080connection:keep-aliveaccept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*
輸入參數的介紹:
1. 輸入參數:
輸入參數:
對于get來說就是跟在url后面的內容
/TestParam?name=”peace”&password=”sisi” ;name=”peace”&password=”sisi”這就是輸入參數
對于post來說就是實體內容,不可見
2. Servlet中獲得輸入參數的方法:
String name=request.getParameter(“name”);獲得對應輸入參數名字的內容
Enumeration params = request.getParameterNames();獲得所有輸入參數的名字,返回一個迭代器
String[] hobits = request.getParameterValues(names);如果對應名字的內容是一個數組,使用這個方法獲得,比如復選框
3. 演示如下:
1.建立testParam.html

2.修改doget方法:
request.setCharacterEncoding("utf-8") //獲得所有的方式
System.out.println("提交方式:"+request.getMethod()) //獲得輸入參數 String name=request.getParameter("name") String pass=request.getParameter("password") System.out.println("name:"+name+",pass:"+pass) System.out.println(">>>>>>>>>>>>>>>>>") //獲得所有輸入參數的名字 Enumeration<String> params = request.getParameterNames() while(params.hasMoreElements()) { String names=params.nextElement() //如果是復選框,使用getParameterValues(names) if("hobit".equals(names)){ System.out.println(names+":") String[] hobits = request.getParameterValues(names) for(String s:hobits) System.out.print(s+",") System.out.println() }
else{ System.out.println(names+":"+request.getParameter(names)) } }##輸出結果如下:提交方式:POSTname:peace,pass:124>>>>>>>>>>>>>>>>>name:peacepassword:124gender:男籍貫:湖南hobit:籃球,足球,info:一條小鯊魚peaceid:001
4.http響應介紹:
HTTP/1.1 302 Found ---響應行 Server: Apache-Coyote/1.1 ---響應頭, 有多個key-value組成Location: http://localhost:8080/HttpSer/ Transfer-Encoding: chunked Date: Fri, 09 Oct 2015 08:55:42 GMT
響應行介紹:
HTTP/1.1 302 Found
1基本介紹
1.HTTP/1.1:采用的協議
2.302:狀態碼
常見的狀態:
200 : 表示請求處理完成并完美返回
302: 表示請求需要進一步細化。
404: 表示客戶訪問的資源找不到。
500: 表示服務器的資源發送錯誤。(服務器內部錯誤)
3.Found:狀態描述,常見ok和found
2. servlet中的方法
tomcat服務器把請求信息封裝到HttpServletRequest對象,且把響應信息封裝到HttpServletResponse
response.setStatus(404);//設置狀態碼
response.sendError(404);// 設置錯誤頁面
3. 演示如下
response.setStatus(404)response.sendError(404)#輸出結果:HTTP/1.1404 Not FoundServer: Apache-Coyote/1.1Content-Type: text/htmlContent-Language: enContent-Length: 949Date: Sat, 10 Oct 201513:09:53 GMT

響應頭介紹:
1. 基本介紹
格式:Server: Apache-Coyote/1.1;Server響應頭名,后面的是響應值;
頭里面主要包括:Server,服務器類型;Location:跳轉網頁地址 Conten*:實體內容
2. servlet中的方法
response.setHeader(“server”, “JBoss”);修改對應頭名的內容;
3. 演示如下
response.setHeader("server", "JBoss");/** * 修改實體內容 */ response.getWriter().println("hello peace");#輸出如下:HTTP/1.1200 OKserver: JBossContent-Length: 12Date: Sat, 10 Oct 201513:11:04 GMTHTTP/1.1200 OKserver: JBossContent-Length: 12Date: Sat, 10 Oct 201513:11:04 GMT

幾個常要的方面介紹
- 測試重定向:與轉發不同
/** * 測試重定向:與轉發不同 * 使用請求重定向:發送一個302狀態嗎+location的響應 * */response.setStatus(302);response.setHeader("location", "/HttpSer/adv.html");#輸出:HTTP/1.1302 FoundServer: Apache-Coyote/1.1location: /HttpSer/adv.htmlContent-Length: 12Date: Sat, 10 Oct 201513:15:26 GMT
- 定時刷新:
//response.setHeader("refresh", "1") //隔5秒后轉到另外的資源 //response.setHeader("refresh", "5;url=/HttpSer/adv.html")#輸出: HTTP/1.1200 OKServer: Apache-Coyote/1.1refresh:1Content-Length: 12Date: Sat, 10 Oct 201513:18:39 GMTHTTP/1.1200 OKServer: Apache-Coyote/1.1refresh:5Content-Length: 12Date: Sat, 10 Oct 201513:21:29 GMT
- 設置編碼:
response.setCharacterEncoding("utf-8");
/** * 1. 服務器發送給瀏覽器的數據類型和內容編碼 */
- 設置為下載方式打開文件:
/** * 設置以下載方式打開文件 */
- 發送硬盤圖片給瀏覽器:
File file = new File("/media/peace/本地磁盤/andriod/1.png");/** * 發送圖片 */ FileInputStream in = new FileInputStream(file);byte[] buf = newbyte[1024];int len = 0;
while( (len=in.read(buf))!=-1 ){ response.getOutputStream().write(buf, 0, len); }
來自一條小鯊魚(rlovep.com)
代碼下載