request物件常用方法總結(及示例)----JSP內建物件
阿新 • • 發佈:2018-12-22
JSP內建物件:request物件
客戶端的請求資訊被封裝在request物件中,通過它才能瞭解到客戶的需求,然後做出響應。它是HttpServletRequest類的例項。request物件具有請求域,即完成客戶端的請求之前,該物件一直有效。常用方法如下:
常用方法 | 方法介紹 |
---|---|
String getParameter(String name) | 返回name指定引數的引數值 |
String[] getParameterValues(String name) | 返回包含引數name的所有值的陣列 |
void setAttribute(String,Object) | 儲存此請求中的屬性 |
Object getAttribute(String name) | 返回指定屬性的屬性值 |
String getContentType() | 得到請求體的MIME型別 |
String getProtocol() | 返回請求用的協議型別及版本號 |
String getServerName() | 返回接受請求的伺服器主機名 |
int getServerPort() | 返回伺服器接受此請求所用的埠號 |
String getCharacterEncoding() | 返回字元編碼方式 |
void setCharacterEncoding() | 設定請求的字元編碼方式 |
int getContentLength() | 返回請求體的長度(以位元組數) |
String getRemoteAddr() | 返回傳送此請求的客戶端IP地址 |
String getRealPath(String path) | 返回一虛擬路徑的真實路徑 |
String request.getContextPath() | 返回上下文路徑 |
程式碼執行後瀏覽器中顯示如下,程式碼放在最後面;
程式碼檔案有兩個:
reg.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>使用者註冊</h1>
<form name="regForm" action="request.jsp" method="get">
<table>
<tr>
<td>使用者名稱:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>愛好:</td>
<td><input type="checkbox" name="favorite" value="read">讀書
<input type="checkbox" name="favorite" value="music">音樂
<input type="checkbox" name="favorite" value="moive">電影
<input type="checkbox" name="favorite" value="internet">上網</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交" /></td>
</tr>
</table>
</form>
<br>
<br>
<a href="request.jsp?username=xxx">測試URL傳引數</a>
</body>
</html>
request.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>request內建物件</h1>
<%
request.setAttribute("password", "123456");
%>
使用者名稱:<%=request.getParameter("username")%>
<br>
愛好:
<%
if (request.getParameterValues("favorite") != null) {
String[] fav = request.getParameterValues("favorite");
for (int i = 0; i < fav.length; i++) {
out.println(fav[i] + " ");
}
}
%>
<br>
密碼:<%=request.getAttribute("password")%><br>
請求體的mime型別:<%=request.getContentType()%><br>
協議型別及版本號:<%=request.getProtocol()%><br>
伺服器主機名:<%=request.getServerName()%><br>
請求的埠號:<%=request.getServerPort()%><br>
字元編碼方式:<%=request.getCharacterEncoding()%><br>
請求體的長度:<%=request.getContentLength()%><br>
返回傳送請求的客戶端IP地址:<%=request.getRemoteAddr()%><br>
返回虛擬路徑的真實路徑:<%=request.getRealPath("request.jsp")%><br>
返回上下文路徑:<%=request.getContextPath()%><br>
</body>
</html>
參考資料: