Request對象詳細介紹

1.Request對象

   是當客戶端向服務器端發送請求時,服務器爲本次請求創建request對象,並在調用Servlet的service方法時,將該對象傳遞給service方法。Request對象中封裝了客戶端發送過來的所有的請求數據。

 




2.Request常用的API

   Request對象的類型是HttpServletRequest,該類中定義了很多與http協議相關的方法,比如獲取請求頭信息,請求方式,客戶端ip地址等信息。下面是常用的API.

  (1)常用信息

     String getRemoteAddr():獲取客戶端ip地址

     String getMethod():獲取客戶端請求方式。例如:get或post

   (2)獲取請求頭信息

      String getHeader(String name):獲取單值的請求頭的值。

      int getIntHeader(String name):獲取單值int類型的請求頭的值


3.Request獲取請求參數方法



request對象獲取請求參數的方法有以下幾個,詳情請看錶1-1


1-1 request獲取請求參數方法介紹


方法名

方法介紹

String getParameter(String name )

獲取指定名稱的請求參數值,適用於單值的請求參數

String[] getParameterValues(String name)

獲取指定名稱的請求參數值,適用於多值的請求參數

Enumeration<String> getParameterNames()

獲取所有的請求參數名稱

Map<String,String[]> getParameterMap()

獲取所有請求參數,其中參數名作爲mapkey,參數值作爲mapvalue.


 牛刀小試

   客戶端表單

[html] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. <span style="font-family:SimSun;font-size:18px;"><body>  
  2. <h1>測試</h1>  
  3. <hr/>  
  4. <form action="/Test/ParamServlet" method="post">  
  5.   用戶名:<input type="text" name="username"/><br/>  
  6.   密 碼:<input type="password" name="password"/><br/>  
  7.   愛 好:<input type="checkbox" name="hobby" value="cf"/>吃飯  
  8.   <input type="checkbox" name="hobby" value="sj"/>睡覺  
  9.   <input type="checkbox" name="hobby" value="ddm"/>打代碼  
  10.   <br/>  
  11.   <input type="submit" value="提交"/>  
  12. </form>  
  13.   </body>  
  14. </span>  

   服務器端接收

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. <span style="font-family:SimSun;font-size:18px;">public class ParamServlet extends HttpServlet {  
  2.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  3.             throws ServletException, IOException {  
  4.         System.out.println("GET: " + request.getParameter("xxx"));  
  5.         System.out.println("GET: " + request.getParameter("yyy"));  
  6.     }  
  7.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  8.             throws ServletException, IOException {  
  9.         String username = request.getParameter("username");  
  10.         String password = request.getParameter("password");  
  11.         String[] hobby = request.getParameterValues("hobby");  
  12.           
  13.         System.out.println(username + ", " + password + ", " + Arrays.toString(hobby));  
  14.             }  
  15. }  
  16. </span>  



4.Request獲取請求路徑方法介紹

  Request對象中包含的是請求信息。下面以一個路徑爲例子,爲大家展示請求路徑的幾個方法。

  地址:http://localhost:8080/Test/login?username=zhangsan.

  Request對象通過以下方法來獲取請求路徑。

  (1)String getServerName():獲取服務器名:localhost

  (2)String getServerPort():獲取服務器端口號:8080

  (3)String getContextPath():獲取項目名:Test

  (4)String getServletPath():獲取Servlet路徑:/login

  (5)String getQueryString():獲取參數部門,即問號後面的部分:username=zhangsan

  (6)String getRequestURL():獲取請求URL


 下面用一張圖來展示一下








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章