HttpServletRequest對象方法的用法小結
深入體驗JavaWeb開發(fā)內幕——關于HttpServletRequestRequest對象
HttpServletRequest對象代表客戶端的請求,當客戶端通過HTTP協(xié)議訪問服務器時,HTTP請求頭中的所有信息都封裝在這個對象中,開發(fā)人員通過這個對象的相關方法,即可以獲得客戶的這些信息。
一、通過request常用方法獲得相關信息:
1、通過request常用方法獲得客戶機信息
getRequestURL方法返回客戶端發(fā)出請求時的完整URL。
getRequestURI方法返回請求行中的資源名部分。
getQueryString 方法返回請求行中的參數(shù)部分。
getRemoteAddr方法返回發(fā)出請求的客戶機的IP地址
getRemoteHost方法返回發(fā)出請求的客戶機的完整主機名
getRemotePort方法返回客戶機所使用的網絡端口號
getLocalAddr方法返回WEB服務器的IP地址。
getLocalName方法返回WEB服務器的主機名
getMethod得到客戶機請求方式
例如在Request.Java中加入如下代碼:
//返回相關請求的信息 String uri=request.getRequestURI(); Stringrad = request.getRemoteAddr(); Stringrh = request.getRemoteHost(); Stringru = request.getRemoteUser(); intrp = request.getRemotePort(); Stringcp = request.getContextPath(); Stringla = request.getLocalAddr(); Stringce = request.getCharacterEncoding(); Stringgm = request.getMethod(); Stringqs = request.getQueryString(); System.out.println(uri); System.out.println(rad); System.out.println(rh); System.out.println(ru); System.out.println(rp); System.out.println(cp); System.out.println(la); System.out.println(ce); System.out.println(gm); System.out.println(qs);
即可獲取相關信息。
2、通過request常用方法獲得客戶機請求頭信息
getHead(name)方法
getHeaders(String name)方法
getHeaderNames方法
如:
private void getRequestValue(HttpServletRequest request) {
//獲得客戶機請求頭及請求頭的值
System.out.println(request.getHeader("method"));
Enumeration e = request.getHeaderNames();
while(e.hasMoreElements()){
String name = (String)e.nextElement();
String value = request.getHeader(name);
System.out.println(name+":"+value);
}
}
3.獲得客戶機請求參數(shù)(客戶端提交的數(shù)據(jù))
getParameter(name):獲取指定名稱的參數(shù)值。這是最為常用的方法之一。
getParameterValues(String name):獲取指定名稱參數(shù)的所有值數(shù)組。它適用于一個參數(shù)名對應多個值的情況。如頁面表單中的復選框,多選列表提交的值。
getParameterNames():返回一個包含請求消息中的所有參數(shù)名的Enumeration對象。通過遍歷這個Enumeration對象,就可以獲取請求消息中所有的參數(shù)名
getParameterMap():返回一個保存了請求消息中的所有參數(shù)名和值的Map對象。Map對象的key是字符串類型的參數(shù)名,value是這個參數(shù)所對應的Object類型的值數(shù)組。
二、request的常見應用
1、 各種表單輸入項數(shù)據(jù)的獲取
如可以獲取form表單中的text、password、radio、checkbox、 file、select、textarea、 hidden、image、button等組件的值進行數(shù)據(jù)庫操作或其他處理操作。
來看一個具體應用:

界面代碼主體部分如下:
Register.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN">
<html>
<head>
<title>Register.html</title>
<metahttp-equivmetahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equivmetahttp-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<!--<link rel="stylesheet" type="text/css"href="./styles.css" rel="external nofollow" >-->
</head>
<body>
<form action ="RequestLogin" method ="post">
用戶名:<input type="text"name = "username" ><br/>
密碼: <inputtypeinputtype="password" name = "password"><br/>
性別:<input type="radio"name = "sex" value ="male">男
<input type="radio" name = "sex" value="female">女<br/>
籍貫: <select name="city">
<option value ="HeBei">河北</option>
<opton value ="HuBei">湖北</opton>
<option value ="ShanXi">山西</option>
</select><br/>
簡歷:<br/>
&nsp;<textarea rows="5" cols="20" name="intro"></textarea>
<br/>
愛好:<br/>
<input type="checkbox" name="hobbies" value ="sing"/>唱歌
<input type="checkbox" name="hobbies" value ="dance"/>跳舞
<input type="checkbox" name="hobbies" value ="readbook"/>讀書
<input type="checkbox" name="hobbies" value ="readnewspaper"/>看報<br/>
上傳頭像:<br/>
<input type="file" value="image" name ="browser"><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
然后,定義一個RequestLogin.java類通過request對象獲取表單中組件的值:
如調用自定義方法:
private void getInformation(HttpServletRequest request)
throws UnsupportedEncodingException {
//取出參數(shù)值
String name = request.getParameter("username");
String pass = request.getParameter("password");
String sex = request.getParameter("sex");
String city = request.getParameter("city");
String intro = request.getParameter("intro");
String [] hobbies = request.getParameterValues("hobbies");
String hobby ="";
//hobbies!=null對所取值為空時進行設置
for(int i=0;hobbies!=null&&i<hobbies.length;i++)
{ String hovalue = hobbies[i]; hobby += hovalue; }
//獲取頭像信息 // String image = request.getParameter("image");
System.out.println("username:"+name);
System.out.println("password:"+pass);
System.out.println("sex:"+sex); System.out.println("city:"+city);
System.out.println("intro:"+intro); System.out.println("hobby:"+hobby);}
即可獲取表單中組件的值。
2、請求參數(shù)的中文亂碼問題
前面我們提到了Response對象中出現(xiàn)亂碼問題及相應的解決措施,那么在Request中如何解決編碼問題呢?
下面來看具體的例子:
例如我想將一個form表單中的信息提取到并在控制臺輸出如圖:

假設在服務端并未Request對象給指定編碼時即服務器端接收請求的字符編碼為ISO8859-1,這時你在客戶端添加信息如:

當填入的信息有中文時,假設設置表單的提交方式為post方式提交
則在服務端輸出如下:

此時輸出結果出現(xiàn)亂碼。
客戶端主體代碼同上:
Register.html
<body>
<form action ="RequestLogin" method ="post">
用戶名:<input type="text" name = "username" ><br/>
密碼: <input type="password" name = "password"><br/>
性別:<input type="radio" name = "sex" value ="male">男
<input type="radio" name = "sex" value ="female">女<br/>
籍貫: <select name ="city">
<option value ="HeBei">河北</option>
<opton value ="HuBei">湖北</opton>
<option value ="ShanXi">山西</option>
</select><br/>
簡歷:<br/>
&nsp;<textarea rows="5" cols="20" name ="intro"></textarea>
<br/>
愛好:<br/>
<input type="checkbox" name ="hobbies" value ="sing"/>唱歌
<input type="checkbox" name ="hobbies" value ="dance"/>跳舞
<input type="checkbox" name ="hobbies" value ="readbook"/>讀書
<input type="checkbox" name ="hobbies" value ="readnewspaper"/>看報<br/>
上傳頭像:<br/>
<input type="file" value ="image" name ="browser"><br/>
<input type="submit" value ="提交"/>
</form>
</body>
服務端主體代碼如下:
RequestLogin.java
package net.csdn.request;
import java.io.IOException;
import java.io.PrintWriter;
importjava.io.UnsupportedEncodingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class RequestLogin extendsHttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
getInformation(request);
}
private voidgetParameter(HttpServletRequest request)
throws UnsupportedEncodingException
{
private voidgetInformation(HttpServletRequest request)
throws UnsupportedEncodingException {
//取出參數(shù)值
String name =request.getParameter("username");
String pass =request.getParameter("password");
String sex =request.getParameter("sex");
String city =request.getParameter("city");
String intro = request.getParameter("intro");
String [] hobbies =request.getParameterValues("hobbies");
String hobby ="";
//hobbies!=null對所取值為空時進行設置
for(inti=0;hobbies!=null&&i<hobbies.length;i++)
{ String hovalue = hobbies[i]; hobby +=hovalue; }
//獲取頭像信息 // String image = request.getParameter("image");
System.out.println("username:"+name);
System.out.println("password:"+pass);
System.out.println("sex:"+sex);System.out.println("city:"+city);
System.out.println("intro:"+intro);System.out.println("hobby:"+hobby);}
public void doPost(HttpServletRequestrequest, HttpServletResponse response)
throws ServletException, IOException{doGet(request, response);}}
這里會出現(xiàn)亂碼問題,是因為你在RegisterLogin.java中并沒有給Request對象設置編碼集,而Request對象的默認編碼集是ISO8859-1是不支持漢字的,所以你只需要在此類中為其指明相應的編碼即可:
改正:在doGet方法中加入如下代碼指明接收請求的編碼方式:
request.setCharacterEncoding("utf-8");
即可輸出:

但是這種修改方式只在提交方式為post時才有效。當提交方式為get時是不起作用的。
即;
<form action ="RequestLogin" method ="get">
時即便在
RequestLogin.java
中再設置
request.setCharacterEncoding("utf-8");
也不會起任何作用了程序還會輸出如圖所示信息:

這時就需要在
RequestLogin.java
中含有中文的地方進行如下設置了即在doGet方法中加入如下代碼:
String username = new String(name.getBytes("iso8859-1"),"utf-8");
String introduction = new String(intro.getBytes("iso8859-1"),"utf-8");
System.out.println("username:"+username);
System.out.println("password:"+introduction);
此時再度測試時就OK了!如圖

好了到這里,你大概已經知道該如何對Response和Request對象中的亂碼問題進行操作了吧!
3、防盜鏈
所謂的防盜鏈就是當你以一個非正常渠道去訪問某一個Web資源的時候,服務器會將你的請求忽略并且將你的當前請求變?yōu)榘凑G涝L問時的請求并返回到相應的頁面,用戶只有通過該頁面中的相關操作去訪問想要請求的最終資源。
例如,你有一個訪問某資源的網址,但是你事先不知道這個網址是有防盜鏈的,那么當你輸入該網址時你可能會發(fā)現(xiàn),并沒有馬上跳轉到你想要的資源頁面而是一些無關的信息頁面,但是就是在這些信息頁面中你發(fā)現(xiàn)有一個超鏈接或是其他操作可以跳轉到你所訪問的最終資源頁面。
這就是防盜鏈技術了,好了來看一個具體應用:
Rquest.java
public class Request extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {getDoorChain(request, response);}
private void getDoorChain(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//通過request獲取請求頭參數(shù)
String referer = request.getHeader("referer");
if(referer==null || !referer.endsWith("http://localhost:8080/Request/index.jsp")){
response.sendRedirect("http://localhost:8080/Request/index.jsp");
return;
}
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset =utf-8");
PrintWriter pw = response.getWriter();
pw.write("喜劇片《東成西就》");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
index.jsp部分的主體代碼:
<body> 這里是防盜鏈技術的應用檢測! <br> <a href ="/Request/Request" >喜劇片 </a> </body> </html>
效果如圖:

例如我最終想要通過http://lcoalhost:8080/Request/Request這個網址獲取到我想要的《東成西就》
的資源可是當我真正的輸入這個網址時,卻轉到了:
http://localhost:8080/Request/index.jsp這個頁面

只有當你點擊“喜劇片”這個超鏈接時才會真正的得到你想要的資源頁面即:

好了趕快自己動手試一試吧!
4、request對象實現(xiàn)請求轉發(fā):
Servlet API中定義了一個RequestDispatcher接口,俗稱請求分派器。它定義了如下兩個方法: public void forward(ServletRequest request, ServletResponseresponse) 、public void include(ServletRequest request,ServletResponse response) ,
獲取RequestDispatcher實例的方式主要有兩種:
調用ServletContext接口提供的getRequestDispatcher(Stringurl)方法。
調用ServletRequest接口提供的getRequestDispatcher(Stringurl)方法。
RequestDispatcher:
被包含的Servlet程序不能改變響應消息的狀態(tài)碼和響應頭,如果它里面存在這樣的語句,這些語句的執(zhí)行結果將被忽略。
例:
request.getRequestDispatcher("./Welcome.jsp").forward(request,response);即可從當前應用跳轉到相應的"./Welcome.jsp"頁面。
request對象提供了一個getRequestDispatcher方法,該方法返回一個RequestDispatcher對象,調用這個對象的forward方法可以實現(xiàn)請求轉發(fā)。
request對象同時也是一個域對象,開發(fā)人員通過request對象在實現(xiàn)轉發(fā)時,把數(shù)據(jù)通過request對象帶給其它web資源處理。
可通過如下方法對request中的數(shù)據(jù)對象進行操作:
setAttribute方法 ;
getAttribute方法 ;
removeAttribute方法;
getAttributeNames方法;
三、關于請求轉發(fā)的一些細節(jié)
forward方法用于將請求轉發(fā)到RequestDispatcher對象封裝的資源。
如果在調用forward方法之前,在Servlet程序中寫入的部分內容已經被真正地傳送到了客戶端,forward方法將拋出IllegalStateException異常。
如果在調用forward方法之前向Servlet引擎的緩沖區(qū) (response)中寫入了內容,只要寫入到緩沖區(qū)中的內容還沒有被真正輸出到客戶端,forward方法就可以被正常執(zhí)行,原來寫入到輸出緩沖區(qū)中的 內容將被清空,但是,已寫入到HttpServletResponse對象中的響應頭字段信息保持有效。
四、請求重定向和請求轉發(fā)的區(qū)別
一個web資源收到客戶端請求后,通知服務器去調用另外一個web資源進行處理,稱之為請求轉發(fā)。
一個web資源收到客戶端請求后,通知瀏覽器去訪問另外一個web資源,稱之為請求重定向。
注意:
RequestDispatcher.forward方法只能將請求 轉發(fā)給同一個WEB應用中的組件;而HttpServletResponse.sendRedirect方法還可以重定向到同一個站點上的其他應用程序中的資源,甚至是使用絕對URL重定向到其他站點的資源。 如果傳遞HttpServletResponse.sendRedirect方法的相對URL以“/”開頭,它是相對于整個WEB站點的根目錄;如果創(chuàng)建RequestDispatcher對象時指定的相對URL以“/”開頭,它是相對于當前WEB應用程序的根目錄。
調用HttpServletResponse.sendRedirect方法重定向的訪問過程結束后,瀏覽器地址欄中顯示的URL會發(fā)生改變,由初始的URL 地址變成重定向的目標URL;調用RequestDispatcher.forward 方法的請求轉發(fā)過程結束后,瀏覽器地址欄保持初始的URL地址不變。
HttpServletResponse.sendRedirect 方法對瀏覽器的請求直接作出響應,響應的結果就是告訴瀏覽器去重新發(fā)出對另外一個URL的訪問請求;RequestDispatcher.forward方法在服務器端內部將請求轉發(fā)給另外一個資源,瀏覽器只知道發(fā)出了請求并得到了響應結果,并不知道在服務器程序內部發(fā)生了轉發(fā)行為。
RequestDispatcher.forward方法的調用者與 被調用者之間共享相同的request對象和response對象,它們屬于同一個訪問請求和響應過程;而 HttpServletResponse.sendRedirect方法調用者與被調用者使用各自的request對象和response對象,它們屬于 兩個獨立的訪問請求和響應過程。
關于請求消息頭我們在以后的學習中還會經常用到request對象是我們目前在JavaWeb開發(fā)中學到的三個作用域即ServletContext、Request和Session域之一,是非常重要的一個請求對象,希望以上的相關介紹對能你有所幫助!
相關文章
Java的wait(), notify()和notifyAll()使用心得
本篇文章是對java的 wait(),notify(),notifyAll()進行了詳細的分析介紹,需要的朋友參考下2013-08-08
SpringBoot+Hutool+thymeleaf完成導出Excel的實現(xiàn)方法
這篇文章主要介紹了SpringBoot+Hutool+thymeleaf完成導出Excel,本篇示例當中不僅僅有后端,而且還提供了前端html,html當中利用js將后端 輸出流直接下載為文件,需要的朋友可以參考下2022-03-03
SpringBoot的@Scheduled和@Schedules區(qū)別小結
本文主要介紹了SpringBoot的@Scheduled和@Schedules區(qū)別小結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-01-01
springboot項目中application.properties無法變成小樹葉問題解決方案
這篇文章主要介紹了springboot項目中application.properties無法變成小樹葉問題解決,本文通過圖文實例代碼相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
rabbitmq使用springboot實現(xiàn)direct模式(最新推薦)
這篇文章主要介紹了rabbitmq使用springboot實現(xiàn)direct模式,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07

