如何在 Serlvet 中獲取請求信息:

如何在 Serlvet 中獲取請求信息:

1). Servlet 的 service() 方法用於應答請求: 因爲每次請求都會調用 service() 方法

public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException

ServletRequest: 封裝了請求信息. 可以從中獲取到任何的請求信息.
ServletResponse: 封裝了響應信息, 如果想給用戶什麼響應, 具體可以使用該接口的方法實現.

這兩個接口的實現類都是服務器給予實現的, 並在服務器調用 service 方法時傳入.

2). ServletRequest: 封裝了請求信息. 可以從中獲取到任何的請求信息.

①. 獲取請求參數:

String getParameter(String name): 根據請求參數的名字, 返回參數值.
若請求參數有多個值(例如 checkbox), 該方法只能獲取到第一個提交的值.

String[] getParameterValues(String name): 根據請求參數的名字, 返回請求參數對應的字符串數組.

Enumeration getParameterNames(): 返回參數名對應的 Enumeration 對象,
類似於 ServletConfig(或 ServletContext) 的 getInitParameterNames() 方法.

Map getParameterMap(): 返回請求參數的鍵值對: key: 參數名, value: 參數值, String 數組類型.

②. 獲取請求的 URI:

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

String requestURI = httpServletRequest.getRequestURI();
System.out.println(requestURI); //  /day_29/loginServlet

③. 獲取請求方式:

String method = httpServletRequest.getMethod();
System.out.println(method); //GET

④. 若是一個 GET 請求, 獲取請求參數對應的那個字符串, 即 ? 後的那個字符串.

String queryString = httpServletRequest.getQueryString();
System.out.println(queryString); //user=atguigu&password=123456&interesting=game&interesting=party&interesting=shopping

⑤. 獲取請求的 Serlvet 的映射路徑

String servletPath = httpServletRequest.getServletPath();
System.out.println(servletPath); // /loginServlet

⑥. 和 attribute 相關的幾個方法:

3). HttpServletRequest: 是 SerlvetRequest 的子接口. 針對於 HTTP 請求所定義. 裏邊包含了大量獲取 HTTP 請求相關的方法.

4). ServletResponse: 封裝了響應信息, 如果想給用戶什麼響應, 具體可以使用該接口的方法實現.

①. *getWriter(): 返回 PrintWriter 對象. 調用該對象的 print() 方法, 將把 print() 中的參數直接打印
到客戶的瀏覽器上.

②. 設置響應的內容類型: response.setContentType(“application/msword”);

③. void sendRedirect(String location): 請求的重定向. (此方法爲 HttpServletResponse 中定義.)


在 web.xml 文件中設置兩個 WEB 應用的初始化參數, user, password.
定義一個 login.html, 裏邊定義兩個請求字段: user, password. 發送請求到 loginServlet
在創建一個 LoginServlet, 在其中獲取請求的 user, password. 比對其和 web.xml 文件中定義的請求參數是否一致
若一致, 響應 Hello:xxx, 若不一致, 響應 Sorry: xxx xxx 爲 user.

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