版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41061455/article/details/82149605
request对象封装了由客户端生成的HTTP请求的所有细节,主要包括HTTP头信息,系统信息,请求方式和请求参数等.通过request对象提供的相应方法(如下所示)可以处理客户端浏览器提交的HTTP请求中的各项参数.
常用方法 | 方法介绍 |
---|---|
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"%>
<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="读书">读书
<input type="checkbox" name="favorite" value="音乐">音乐
<input type="checkbox" name="favorite" value="电影">电影
<input type="checkbox" name="favorite" value="上网">上网</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交" /></td>
</tr>
</table>
</form>
<br>
<br>
<a href="request.jsp">测试URL传参数</a>
</body>
</html>
<!-- request.jsp -->
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>request内置对象</h1>
<%
request.setCharacterEncoding("utf-8");
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>