Java servlet request 的常用方法

HttpServletRequest對象代表客戶端的請求,當客戶端通過HTTP協議訪問服務器時,HTTP請求頭中的所有信息都封裝在這個對象中,開發人員通過這個對象的方法,可以獲得客戶這些信息。

request常用方法

一、獲取客戶機環境信息常見方法

  1.getRequestURL方法返回客戶端發出請求時的完整URL。

  2.getRequestURI方法返回請求行中的資源名部分。

  3.getQueryString方法返回請求行的參數部分。

  4.getRemoteAddr方法返回發出請求的客戶機的IP地址。

  5.getRemoteHost方法返回發出請求的客戶機的完整主機名。

  6.getRemotePort方法返回客戶機所使用的網絡端口號。

  7.getLocalAddr方法返回WEB服務器的IP地址。

  8.getLocalName方法返回WEB服務器的主機名。

  9.getMethod得到客戶機請求方式。

import java.io.IOException;
 import java.io.OutputStream;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 public class RequestDemo extends HttpServlet {
 
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         /**
          * URL是URI的子集。
          * URI用來標識一個資源。
          * URL用來標識互聯網上的一個資源。
          */
         System.out.println(request.getRequestURL());//得到請求URL地址
         System.out.println(request.getRequestURI());//得到請求的資源
         System.out.println(request.getQueryString());
         System.out.println(request.getRemoteAddr());//得到來訪者IP
         System.out.println(request.getRemoteHost());
         //由於沒有在dns上註冊所以打印結果還是127.0.0.1,如果是百度訪問這個程序,則打印www.baidu.com
         System.out.println(request.getRemotePort());//得到客戶端端口號
         System.out.println(request.getMethod());//得到請求的方法
 }
 
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doGet(request,response);
 }
 }

 在瀏覽器地址欄輸入:http://localhost:8080/test/servlet/RequestDemo後後臺輸出入下圖:



 

 

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