HttpServletRequest对象表明客户端的请求,当客户端经过HTTP协议访问服务器时,HTTP请求头中的全部信息都封装在这个对象中,经过这个对象提供的方法,能够得到客户端请求的全部信息。css
在eclipse中新建一个web项目,目录结构以下:java
在jsp页面的最开始,获取项目的根路径:jquery
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
在中,插入下述代码:web
<base href="<%=basePath%>" />
这句代码的做用是将整个页面的根路径设置为项目路径。spring
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); }
getHeader(string name)方法:Stringdocker
getHeaders(String name)方法:Enumerationbootstrap
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); } }
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>
提交以下表单:
后台打印:
运行结果以下:
有以下表单:
<%@ 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); } }
从新提交表单,中文乱码解决:
有以下表单:
<%@ 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); } }
从新提交表单,中文乱码解决:
请求转发:指一个web资源收到客户端请求后,通知服务器去调用另一个web资源进行处理。
请求转发的应用场景:MVC设计模式
在Servlet中实现请求转发的两种方式:
一、经过ServletContext的getRequestDispatcher(String path)方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法能够实现请求转发。
例如:将请求转发的test.jsp页面
RequestDispatcher reqDispatcher =this.getServletContext().getRequestDispatcher("/test.jsp"); reqDispatcher.forward(request, response);
二、经过request对象提供的getRequestDispatche(String path)方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法能够实现请求转发。
例如:将请求转发的test.jsp页面
request.getRequestDispatcher("/test.jsp").forward(request, response);
request对象同时也是一个域对象(Map容器),开发人员经过request对象在实现转发时,把数据经过request对象带给其它web资源处理。
例如:请求RequestDemo06 Servlet,RequestDemo06将请求转发到test.jsp页面
package gacl.request.study; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDemo06 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="你们好,我是孤傲苍狼,我正在总结JavaWeb"; /** * 将数据存放到request对象中,此时把request对象看成一个Map容器来使用 */ request.setAttribute("data", data); //客户端访问RequestDemo06这个Servlet后,RequestDemo06通知服务器将请求转发(forward)到test.jsp页面进行处理 request.getRequestDispatcher("/test.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
test.jsp页面代码以下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Request对象实现请求转发</title> </head> <body> 使用普通方式取出存储在request对象中的数据: <h3 style="color:red;"><%=(String)request.getAttribute("data")%></h3> 使用EL表达式取出存储在request对象中的数据: <h3 style="color:red;">${data}</h3> </body> </html>
request对象做为一个域对象(Map容器)使用时,主要是经过如下的四个方法来操做
一个web资源收到客户端请求后,通知服务器去调用另一个web资源进行处理,称之为请求转发/307。
一个web资源收到客户端请求后,通知浏览器去访问另一个web资源进行处理,称之为请求重定向/302。
参考资料
http://www.cnblogs.com/xdp-gacl/p/3798347.html https://www.cnblogs.com/Zender/p/7647503.html
文章有不当之处,欢迎指正,若是喜欢微信阅读,你也能够关注个人微信公众号:
好好学java
,获取优质学习资源。