zoukankan      html  css  js  c++  java
  • 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);
        }
    }

    重新提交表单,中文乱码解决:

  • 相关阅读:
    JS弹出层可拖拽
    DWZ搭建页面快速入门笔记
    JQuery 选择器总结
    最新身份证验证
    centos7磁盘扩容
    vue中使用vueamap(高德地图)
    后台数据格式有问题,更改数据格式
    《JavaScript高级程序设计(第3版)》问题收集
    slice()、substr()、substring()的结果
    【SQL】统计数据过程中利用Union去重
  • 原文地址:https://www.cnblogs.com/Zender/p/7647503.html
Copyright © 2011-2022 走看看