• Request和Response学习笔记2


    Request 获取请求行数据

    获取方法

    String getMethod()
    // 获取请求方式
    
    String getContextPath()
    // 获取虚拟目录
    
    String getServletPath()
    // 获取Servlet路径
    
    String getRequestURI()
    StringBuffer getRequestURL()
    // 获取请求URI、URL
    
    String getProtocol()
    // 获取协议及版本
    
    String getRemoteAddr()
    // 获取客户机的IP地址
    

    URI & URL 的说明:

    • URL:统一资源定位符
    • URI:统一资源标识符

    如:

    1. 例子1
    2. 例子2
      • 中华人民共和国 —— URL
      • 共和国 —— URI

    创建一个类,继承HttpServlet类

    package study.request;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet("/study/request/demo01")
    public class RequestDemo01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
        }
    }
    

    String getMethod() 方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // String getMethod() 获取请求方式
        System.out.println(req.getMethod());
    }
    

    String getContextPath() 方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // String getContextPath() 获取虚拟目录
        System.out.println(req.getContextPath());
    }
    

    String getServletPath() 方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // String getServletPath() 获取Servlet路径
        System.out.println(req.getServletPath());
    }
    

    String getRequestURI()、StringBuffer getRequestURL() 方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // String getRequestURI() 获取请求URI
        // StringBuffer getRequestURL() 获取请求URL
        System.out.println(req.getRequestURI());
        System.out.println(req.getRequestURL());
    }
    

    String getProtocol() 方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // String getProtocol() 获取协议及版本
        System.out.println(req.getProtocol());
    }
    

    String getRemoteAddr() 方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // String getRemoteAddr() 获取客户机的IP地址
        System.out.println(req.getRemoteAddr());
    }
    

    创建一个html文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Request Study</title>
    </head>
    <body>
        <form action="/RequestAndResponse_war_exploded/study/request/demo01" method="get">
            <input name="username">
            <input type="submit" value="get提交">
        </form>
    </body>
    </html>
    

    开启服务器

    1. 用户访问:http://localhost:8080/RequestAndResponse_war_exploded/HelloRequest.html

    2. 随便输入点内容,提交,如输入:RequestTest

      页面跳转到:http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo01?username=RequestTest

      • 获取请求方式:getMethod() 方法输出

        GET
        
      • 获取虚拟目录:getContextPath() 方法输出

        /RequestAndResponse_war_exploded
        
      • 获取Servlet路径:getServletPath() 方法输出

        /study/request/demo01
        
      • 获取请求URI:getRequestURI() 方法输出

        /RequestAndResponse_war_exploded/study/request/demo01
        
      • 获取请求URL:getRequestURL() 方法输出

        http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo01
        
      • 获取协议及版本:getProtocol() 方法输出

        HTTP/1.1
        
      • 获取客户机的IP地址:getRemoteAddr() 方法输出

        0:0:0:0:0:0:0:1
        

    Request 获取请求头数据

    获取方法

    String getHeader(String name)
    // 通过请求头的名称获取请求头的值
    
    Enumeration<String> getHeaderNames()
    // 获取所有的请求头名称
    

    创建一个类(RequestDemo02.java),使用这两个方法

    package study.request;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Enumeration;
    
    @WebServlet("/study/request/demo02")
    public class RequestDemo02 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // 获取所有请求头名称
            Enumeration<String> headerNames = req.getHeaderNames();
            // Enumeration接口,功能由Iterator复制。
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                // 根据请求头名称获取请求头名称的值
                String headerValue = req.getHeader(headerName);
                System.out.println(headerName + " : " + headerValue);
            }
        }
    }
    

    开启服务器

    访问:http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo02

    控制台输出:

    自己根据请求头名字获取请求头

    user-agent

    获取用户访问资源链接时使用的浏览器。

    package study.request;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet("/study/request/demo02")
    public class RequestDemo02 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // 演示获取请求头数据:user-agent
            String userAgentValue = req.getHeader("user-agent");
            // 判断用户使用什么浏览器发出的请求
            if (userAgentValue.contains("Chrome")) {
                System.out.println("来自谷歌浏览器的访问!!!");
            } else if (userAgentValue.contains("Firefox")) {
                System.out.println("来自火狐浏览器的访问!!!");
            } else if (userAgentValue.contains("XXX")) {
                System.out.println("来自 XXX 浏览器的访问!!!");
            }
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
    
        }
    }
    

    谷歌浏览器访问:http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo02

    控制台输出:

    来自谷歌浏览器的访问!!!
    

    referer

    获取用户跳转到目的页面之前的那个页面的URL

    package study.request;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet("/study/request/demo02")
    public class RequestDemo02 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // 演示获取请求头数据:referer
            String refererValue = req.getHeader("referer");
            System.out.println(refererValue);
            if (refererValue.contains("/RequestAndResponse_war_exploded")) {
                System.out.println("可以正常访问");
            } else {
                System.out.println("不可以正常访问");
            }
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
    
        }
    }
    

    浏览器访问:http://localhost:8080/RequestAndResponse_war_exploded/HelloRequest02.html

    20200518144355

    点击看电影,页面跳转到:http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo02?View+Name=唐人街探案3

    控制台输出:

    http://localhost:8080/RequestAndResponse_war_exploded/HelloRequest02.html
    可以正常访问
    

    假如不是从 /RequestAndResponse_war_exploded 资源链接中跳转过来的话,那么,控制台会输出:不可以正常访问

    • 也可以更改上例中的部分内容,是的部分输出在页面上:

      // 将这部分内容修改
      System.out.println("可以正常访问");
      
      System.out.println("不可以正常访问");
      
      // 修改为
      System.out.println("可以正常访问");
      resp.setContentType("text/html;charset=utf-8");
      resp.getWriter().write("你可以看电影~~~");
      
      System.out.println("不可以正常访问");
      resp.setContentType("text/html;charset=utf-8");
      resp.getWriter().write("你不可以看电影~~~");
      
    • /RequestAndResponse_war_exploded 资源链接中跳转过来,控制台输出:

      http://localhost:8080/RequestAndResponse_war_exploded/HelloRequest02.html
      可以正常访问
      

      点击看电影,页面跳转到:http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo02?View+Name=唐人街探案3

      页面内容如下:

      20200518145956

    Request 获取请求体的数据

    步骤

    1. 获取流对象
      • BufferedReader getReader():获取字符输入流,只能操作字符数据
      • ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据
    2. 再从流对象中拿数据

    简单实现

    1. 创建一个demo.java:RequestDemo03.java

      package study.request;
      
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.BufferedReader;
      import java.io.IOException;
      
      @WebServlet("/study/request/demo03")
      public class RequestDemo03 extends HttpServlet {
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
              // 获取请求消息体
              // 1. 获取字符流
              BufferedReader reqReader = req.getReader();
              String line;
              while ((line = reqReader.readLine()) != null) {
                  System.out.println(line);
              }
          }
      }
      
    2. 创建一个html文件:login.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>用户登录</title>
      </head>
      <body>
          <form action="/RequestAndResponse_war_exploded/study/request/demo03" method="post">
              <input type="email" name="userEmail" placeholder="请输入您的邮箱"><br>
              <input type="password" name="userPassword" placeholder="请输入您的密码"><br>
              <input type="submit" value="登录">
          </form>
      </body>
      </html>
      
    3. 启动服务器,浏览器访问:http://localhost:8080/RequestAndResponse_war_exploded/login.html

      20200518155913
    4. 点击登录,页面跳转到:http://localhost:8080/RequestAndResponse_war_exploded/study/request/demo03

      控制台输出:

      userEmail=stringbug%40icloud.com&userPassword=123456
      

      浏览器页面内容:

      20200518162334

    参考文献

    1. HttpServletRequest获取客户端所有参数
    2. [JavaEE-HttpServletRequest总结](
    Good Good Write Bug, Day Day Up
  • 相关阅读:
    MainFrm.cpp
    MyView.h
    我的东软实习项目一:车牌识别之MFC----MyView.cpp
    洛谷P1055 字符串的处理-----ISBN
    跳出多重循环------设置标志量
    单链表的创建及操作
    线性表的建立及运算
    JVM--你常见的jvm 异常有哪些? 代码演示:StackOverflowError , utOfMemoryError: Java heap space , OutOfMemoryError: GC overhead limit exceeded, Direct buffer memory, Unable_to_create_new_native_Thread, Metaspace
    JVM-gcRoots 和 强引用,软引用, 弱引用, 虚引用, 代码演示和应用场景
    JUC 并发编程--08,线程池,三大方法,七大参数,4种拒绝策略,代码演示
  • 原文地址:https://www.cnblogs.com/liyihua/p/14477433.html
Copyright © 2020-2023  润新知