1. 程式人生 > >servlet學習(二)request物件獲取請求頭資訊

servlet學習(二)request物件獲取請求頭資訊

一、作用

封存了當前請求的所有請求資訊

二、使用

獲取請求頭的資訊包括:

1.請求行:請求方式 請求URL/URI 協議版本

//獲取請求行
		     String method=req.getMethod();
		     StringBuffer url=req.getRequestURL();
		     String uri=req.getRequestURI();
		     String scheme=req.getScheme();
		     System.out.println("請求行:"+method+" "+uri+" "+scheme);

2.請求頭:鍵值對

 //獲取請求頭
		     Enumeration enumeration=req.getHeaderNames();
		     System.out.println("請求頭:");
		     while(enumeration.hasMoreElements()) {
		    	 String name=(String)enumeration.nextElement();
		    	 String value=req.getHeader(name);
		    	 System.out.println(name+" "+value);
		     }

3.請求資料

  //獲取請求實體
		     req.getParameter("鍵名");       //返回指定的使用者資料
		     req.getParameterValues("鍵名"); //返回同鍵不同值的string陣列,如前臺頁面的多選框
		     req.getParameterNames();        //返回所有使用者請求資料的列舉集合

 

執行結果:

請求行:GET /sx/s2 http
請求頭:
host localhost:8080
connection keep-alive
cache-control max-age=0
upgrade-insecure-requests 1
user-agent Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
accept text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding gzip, deflate, br
accept-language zh-CN,zh;q=0.9

注意:如果是URL則:完整的瀏覽器訪問地址(http://localhost:8080/sx/s2

注意:如果是URI則:虛擬專案名+對應的servlet名字(/sx/s2

注意:獲取請求實體資料的時候,無論是get方式還是post方式,都是用 req.getParameter("鍵名");