Java Web学习总结(5)HttpServletRequest
一,HttpServletRequest介绍
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息。
二,jsp页面引入js,css文件的方式
在eclipse中新建一个web项目,目录结构如下:
在jsp页面的最开始,获取项目的根路径:
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
在<head></head>中,插入下述代码:
<base href="<%=basePath%>" />
这句代码的作用是将整个页面的根路径设置为项目路径。
三,Request常用方法
1,获得客户机信息
getRequestURL() |
返回客户端发出请求时的完整URL。 |
getRequestURI() |
返回请求行中的资源名部分。 |
getQueryString () |
返回请求行中的参数部分。 |
getRemoteAddr() |
返回发出请求的客户机的IP地址。 |
getPathInfo() |
返回请求URL中的额外路径信息。额外路径信息是请求URL中的位于Servlet的路径之后和查询参数之前的内容,它以"/"开头。 |
getRemoteHost() |
返回发出请求的客户机的完整主机名。 |
getRemotePort() |
返回客户机所使用的网络端口号。 |
getLocalAddr() |
返回WEB服务器的IP地址。 |
getLocalName() |
返回WEB服务器的主机名。 |
private void RequestMessages(HttpServletRequest req, HttpServletResponse resp) throws IOException{
String reqUrl = req.getRequestURL().toString();//得到请求的URL地址
String reqUri = req.getRequestURI();//得到请求的资源
String queryString = req.getQueryString();//得到请求的URL地址中附带的参数
String remoteAddr = req.getRemoteAddr();//得到来访者的IP地址
String remoteHost = req.getRemoteHost();
int remotePort = req.getRemotePort();
String remoteUser = req.getRemoteUser();
String method = req.getMethod();//得到请求URL地址时使用的方法
String pathInfo = req.getPathInfo();
String localAddr = req.getLocalAddr();//获取WEB服务器的IP地址
String localName = req.getLocalName();//获取WEB服务器的主机名
resp.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
//通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
resp.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.write("获取到的客户机信息如下:");
out.write("<br/>");
out.write("请求的URL地址:"+reqUrl);
out.write("<br/>");
out.write("请求的资源:"+reqUri);
out.write("<br/>");
out.write("请求的URL地址中附带的参数:"+queryString);
out.write("<br/>");
out.write("来访者的IP地址:"+remoteAddr);
out.write("<br/>");
out.write("来访者的主机名:"+remoteHost);
out.write("<br/>");
out.write("使用的端口号:"+remotePort);
out.write("<br/>");
out.write("remoteUser:"+remoteUser);
out.write("<br/>");
out.write("请求使用的方法:"+method);
out.write("<br/>");
out.write("pathInfo:"+pathInfo);
out.write("<br/>");
out.write("localAddr:"+localAddr);
out.write("<br/>");
out.write("localName:"+localName);
}
private void RequestMessages(HttpServletRequest req, HttpServletResponse resp) throws IOException{
String reqUrl = req.getRequestURL().toString();//得到请求的URL地址
String reqUri = req.getRequestURI();//得到请求的资源
String queryString = req.getQueryString();//得到请求的URL地址中附带的参数
String remoteAddr = req.getRemoteAddr();//得到来访者的IP地址
String remoteHost = req.getRemoteHost();
int remotePort = req.getRemotePort();
String remoteUser = req.getRemoteUser();
String method = req.getMethod();//得到请求URL地址时使用的方法
String pathInfo = req.getPathInfo();
String localAddr = req.getLocalAddr();//获取WEB服务器的IP地址
String localName = req.getLocalName();//获取WEB服务器的主机名
resp.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
//通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
resp.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.write("获取到的客户机信息如下:");
out.write("<br/>");
out.write("请求的URL地址:"+reqUrl);
out.write("<br/>");
out.write("请求的资源:"+reqUri);
out.write("<br/>");
out.write("请求的URL地址中附带的参数:"+queryString);
out.write("<br/>");
out.write("来访者的IP地址:"+remoteAddr);
out.write("<br/>");
out.write("来访者的主机名:"+remoteHost);
out.write("<br/>");
out.write("使用的端口号:"+remotePort);
out.write("<br/>");
out.write("remoteUser:"+remoteUser);
out.write("<br/>");
out.write("请求使用的方法:"+method);
out.write("<br/>");
out.write("pathInfo:"+pathInfo);
out.write("<br/>");
out.write("localAddr:"+localAddr);
out.write("<br/>");
out.write("localName:"+localName);
}
2,获得客户机请求头
getHeader(string name)方法:String
getHeaders(String name)方法:Enumeration
getHeaderNames()方法
private void RequestHead(HttpServletRequest req, HttpServletResponse resp) throws IOException{
resp.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
//通过设置响应头控制浏览器以UTF-8的编码显示数据
resp.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
Enumeration<String> reqHeadInfos = req.getHeaderNames();//获取所有的请求头
out.write("获取到的客户端所有的请求头信息如下:");
out.write("<br/>");
while (reqHeadInfos.hasMoreElements()) {
String headName = (String) reqHeadInfos.nextElement();
String headValue = req.getHeader(headName);//根据请求头的名字获取对应的请求头的值
out.write(headName+":"+headValue);
out.write("<br/>");
}
out.write("<br/>");
out.write("获取到的客户端Accept-Encoding请求头的值:");
out.write("<br/>");
String value = req.getHeader("Accept-Encoding");//获取Accept-Encoding请求头对应的值
out.write(value); Enumeration<String> e = req.getHeaders("Accept-Encoding");
while (e.hasMoreElements()) {
String string = (String) e.nextElement();
System.out.println(string);
}
}
3,获得客户机请求参数
getParameter(String name) |
根据name获取请求参数(常用) |
getParameterValues(String name) |
根据name获取请求参数列表(常用) |
getParameterMap() |
返回的是一个Map类型的值,该返回值记录着前端(如jsp页面)所提交请求中的请求参数和请求参数值的映射关系。(编写框架时常用) |
如下表单:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表单提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<form class="form-horizontal" action="<%=request.getContextPath()%>/GetParameterRequest.html" role="form" method="post">
<div class="form-group">
<label for="firstname" class="col-sm-1 control-label">名字</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="name"
placeholder="请输入名字">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-1 control-label">年龄</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="age"
placeholder="请输年龄">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-1 control-label">性别</label>
<div class="col-sm-3">
<input type="radio" name="sex" value="男" checked>男
<input type="radio" name="sex" value="女">女
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-1 control-label">爱好</label>
<div class="col-sm-3">
<input type="checkbox" name="aihao" value="唱歌">唱歌
<input type="checkbox" name="aihao" value="上网">上网
<input type="checkbox" name="aihao" value="游戏">游戏
<input type="checkbox" name="aihao" value="看书">看书
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-3">
<button type="submit" class="btn btn-default">提交</button>
<button type="reset" class="btn btn-default">重置</button>
</div>
</div>
</form>
</body>
</html>
使用getParameter方法和getParameterValues方法接收表单参数:
public class GetParameterRequest extends HttpServlet{
private static final long serialVersionUID = 3903946972744326948L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//客户端是以UTF-8编码提交表单数据的,所以需要设置服务器端以UTF-8的编码进行接收,否则对于中文数据就会产生乱码
req.setCharacterEncoding("UTF-8");
//获取名字
String name = req.getParameter("name");
//获取年龄
String age = req.getParameter("age");
//获取性别
String sex = req.getParameter("sex");
//获取爱好,因为可以选中多个值,所以获取到的值是一个字符串数组,因此需要使用getParameterValues方法来获取
String[] aihaos = req.getParameterValues("aihao"); String aihao = "";
if(aihaos != null){
for (int i = 0; i < aihaos.length; i++) {
if(i == aihaos.length - 1){
aihao += aihaos[i];
} else {
aihao += aihaos[i] + ",";
}
}
}
System.out.println("名字:" + name);
System.out.println("年龄:" + age);
System.out.println("性别:" + sex);
System.out.println("爱好:" + aihao);
req.setAttribute("aihao", aihao);
//设置服务器端以UTF-8编码输出数据到客户端
resp.setCharacterEncoding("UTF-8");
this.getServletContext().getRequestDispatcher("/request.jsp").forward(req, resp);
}
}
响应页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表单提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<table class="table">
<thead>
<tr>
<th>名称</th>
<th>结果</th>
</tr>
</thead>
<tbody>
<tr>
<td>姓名</td>
<td><%=request.getParameter("name") %></td>
</tr>
<tr>
<td>年龄</td>
<td><%=request.getParameter("age") %></td>
</tr>
<tr>
<td>性别</td>
<td><%=request.getParameter("sex") %></td>
</tr>
<tr>
<td>爱好</td>
<td><%=request.getAttribute("aihao") %></td>
</tr>
</tbody>
</table>
</body>
</html>
提交如下表单:
后台打印:
运行结果如下:
四,request接收表单提交中文参数乱码问题
1,以POST方式提交表单中文参数的乱码问题
有如下表单:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表单提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<form class="form-horizontal" action="<%=request.getContextPath()%>/PostRequest.html" role="form" method="post">
<div class="form-group">
<label for="firstname" class="col-sm-1 control-label">名字</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="name"
placeholder="请输入名字">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-3">
<button type="submit" class="btn btn-default">提交</button>
<button type="reset" class="btn btn-default">重置</button>
</div>
</div>
</form>
</body>
</html>
后台接收参数:
public class PostRequest extends HttpServlet{
private static final long serialVersionUID = 3903946972744326948L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println("名字:" + name);
}
}
提交数据:
运行结果:
之所以会产生乱码,就是因为服务器和客户端沟通的编码不一致造成的,因此解决的办法是:在客户端和服务器之间设置一个统一的编码,之后就按照此编码进行数据的传输和接收。
由于客户端是以UTF-8字符编码将表单数据传输到服务器端的,因此服务器也需要设置以UTF-8字符编码进行接收,通过setCharacterEncoding方法统一编码格式:
public class PostRequest extends HttpServlet{
private static final long serialVersionUID = 3903946972744326948L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置服务器以UTF-8的编码接收数据
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
System.out.println("名字:" + name);
}
}
重新提交表单,中文乱码解决:
2,以GET方式提交表单中文参数的乱码问题
有如下表单:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表单提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<form class="form-horizontal" action="<%=request.getContextPath()%>/GetRequest.html" role="form" method="get">
<div class="form-group">
<label for="firstname" class="col-sm-1 control-label">名字</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="name"
placeholder="请输入名字">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-3">
<button type="submit" class="btn btn-default">提交</button>
<button type="reset" class="btn btn-default">重置</button>
</div>
</div>
</form>
</body>
</html>
后台接收参数:
public class GetRequest extends HttpServlet{
private static final long serialVersionUID = 3903946972744326948L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println("名字:" + name);
}
}
提交数据:
运行结果:
之所以会产生乱码,对于以get方式传输的数据,默认的还是使用ISO8859-1这个字符编码来接收数据,客户端以UTF-8的编码传输数据到服务器端,而服务器端的request对象使用的是ISO8859-1这个字符编码来接收数据,服务器和客户端沟通的编码不一致因此才会产生中文乱码的。
解决方法:
在接收到数据后,先获取request对象以ISO8859-1字符编码接收到的原始数据的字节数组,然后通过字节数组以指定的编码构建字符串
public class GetRequest extends HttpServlet{
private static final long serialVersionUID = 3903946972744326948L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
//以ISO8859-1字符编码接收到的原始数据的字节数组,然后通过字节数组以指定的编码构建字符串
name = new String(name.getBytes("ISO8859-1") , "UTF-8");
System.out.println("名字:" + name);
}
}
重新提交表单,中文乱码解决:
Java Web学习总结(5)HttpServletRequest的更多相关文章
- java web学习总结(十) -------------------HttpServletRequest对象
一.HttpServletRequest介绍 HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象 ...
- java web 学习十(HttpServletRequest对象1)
一.HttpServletRequest介绍 HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象 ...
- [原创]java WEB学习笔记11:HttpServlet(HttpServletRequest HttpServletRsponse) 以及关于 Servlet 小结
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- java web 学习笔记 编码问题总结
java web 学习笔记 编码问题总结 1.非form表单中提交的中文参数---------------------------传递给Servlet服务器时,默认以iso-8859-1解码 ...
- Java Web学习笔记之---EL和JSTL
Java Web学习笔记之---EL和JSTL (一)EL (1)EL作用 Expression Language(表达式语言),目的是代替JSP页面中复杂的代码 (2)EL表达式 ${变量名} ( ...
- Java Web 学习路线
实际上,如果时间安排合理的话,大概需要六个月左右,有些基础好,自学能力强的朋友,甚至在四个月左右就开始找工作了.大三的时候,我萌生了放弃本专业的念头,断断续续学 Java Web 累计一年半左右,总算 ...
- [原创]java WEB学习笔记95:Hibernate 目录
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问
本篇内容还是建立在上一篇Java Web学习系列——Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Jar包 这 ...
- Java Web学习系列——Maven Web项目中集成使用Spring
参考Java Web学习系列——创建基于Maven的Web项目一文,创建一个名为LockMIS的Maven Web项目. 添加依赖Jar包 推荐在http://mvnrepository.com/.h ...
- Java web 学习之旅
java web学习之旅 来公司十天了,感觉已经慢慢地融入了这个环境中,几个学长人都很好,都是在他们帮助下,我才能比较顺利的开始了学习java web的旅途. 来这里学习的第一个阶段是做一个简单的用户 ...
随机推荐
- php函数名后冒号+数据类型(返回值类型限制/php新特性)
在PHP7,一个新的功能,返回类型声明已被引入.返回类型声明指定的一个函数返回值的类型. int float bool string interfaces array callable 对象实例 如下 ...
- leetcode 141. 环形链表(C++)
给定一个链表,判断链表中是否有环. 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始). 如果 pos 是 -1,则在该链表中没有环. 示例 1: 输入: ...
- MapReduce(3): Partitioner, Combiner and Shuffling
Partitioner: Partitioning and Combining take place between Map and Reduce phases. It is to club the ...
- Python科学计算三维可视化(整理完结)
中国MOOC<Pyhton计算计算三维可视化>总结 课程url:here ,教师:黄天宇,嵩天 下文的图片和问题,答案都是从eclipse和上完课后总结的,转载请声明. Python数据三 ...
- 三级级联(js实现)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...
- python安装numpy
命令介绍: D:\computerSoft\python3.6.4\Scripts>python36 pip3.6.exe install numpy # 通过pip下载对应版本的numpy,然 ...
- 提交代码到github
1. 下载git 点击download下载即可.下载地址:https://gitforwindows.org/ 2. 注册github github地址:https://github.com/ 一定要 ...
- ORACLE USER视图
select * from USER_ALL_TABLES -- 包含对用户可用的表的描述. select * from USER_ARGUMENTS --列出对用户可存取的对象中的参数 ...
- HTML5中canvas与SVG有什么区别
SVG SVG 是一种使用 XML 描述 2D 图形的语言,它基于XML也就是我们可以为某个元素附加JavaScript事件处理器,如果SVG 对象的属性发生变化,那么浏览器能够自动重现图形. Can ...
- OC学习--OC中的类--类的定义,成员变量,方法
1. 类的定义 >用关键字@interface进行声名 @end 结束 >所有的类有一个基类NSobject >类名 也是标示符 第一个字母大写 如果多个字母组成 每个单词的首字母 ...