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() |
獲取所有請求參數,其中參數名作爲map的key,參數值作爲map的value. |
牛刀小試
客戶端表單
- <span style="font-family:SimSun;font-size:18px;"><body>
- <h1>測試</h1>
- <hr/>
- <form action="/Test/ParamServlet" method="post">
- 用戶名:<input type="text" name="username"/><br/>
- 密 碼:<input type="password" name="password"/><br/>
- 愛 好:<input type="checkbox" name="hobby" value="cf"/>吃飯
- <input type="checkbox" name="hobby" value="sj"/>睡覺
- <input type="checkbox" name="hobby" value="ddm"/>打代碼
- <br/>
- <input type="submit" value="提交"/>
- </form>
- </body>
- </span>
服務器端接收
- <span style="font-family:SimSun;font-size:18px;">public class ParamServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("GET: " + request.getParameter("xxx"));
- System.out.println("GET: " + request.getParameter("yyy"));
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- String[] hobby = request.getParameterValues("hobby");
- System.out.println(username + ", " + password + ", " + Arrays.toString(hobby));
- }
- }
- </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
下面用一張圖來展示一下