【JavaWeb】 Http中的request详解

HTTP简介

概念

超文本传输协议,定义了客户端和服务器端通信时,发送和接受数据的格式。

协议特点

  • 基于TCP/IP的高级协议
  • 默认端口号是80
  • 基于请求/响应模型的:一次请求对应一次响应
  • 无状态的,每次请求之间相互独立,不能交互数据。

历史版本

1.0 : 每一次请求都会相应新的连接

1.1 : 如果两次地址一样可以复用连接

请求消息数据格式

 1.请求行

         请求方式             请求url             请求协议/版本

            GET                /login.html            HTTP/1.1

HTTP协议有7中请求方式,常用的有两种

  • GET:
  1. 请求参数在请求行中,在url后
  2. 请求的url长度有限制的
  3. 不太安全(肉眼可见)
  • POST:
  1. 请求参数在请求体中
  2. 请求的url长度没有限制的
  3. 相对安全(在请求体内)

2.请求头

请求头名称: 请求头值

常见的请求头有:

  • User-Agent:浏览器告诉服务器,浏览器自己的版本信息,这样做可以保证浏览器的兼容问题
  • Referer:http://localhost/login.html 告诉服务器,我(当前请求)从哪里来。可以用来防盗链和统计工作。

3.请求空行

空行, 用于分割POST请求的请求头和请求体。

4.请求体

请求行    POST     /login.html     HTTP/1.1
请求头    Host: localhost
         User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
         Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
         Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
         Accept-Encoding: gzip, deflate
         Connection: keep-alive
         Referer: http://search.bilibili.com
         Cookie: JSESSIONID=07DFB352A5D840658715BA1B0F6EE029
         Upgrade-Insecure-Requests: 1
空行
请求体   username=lisi

Request 详解

1. request对象和response对象的原理

       1. request和response对象是由服务器创建的。我们来使用它们

       2. request对象是来获取请求消息,response对象是来设置响应消息

扫描二维码关注公众号,回复: 10046668 查看本文章

2.request对象继承体系结构:

3. request功能:

1. 获取请求消息数据

例如: GET /day3/demo1?name=zhangsan HTTP/1.1

方法:

1. 获取请求方式 :GET

String getMethod()

2. (*)获取虚拟目录:/day3

String getContextPath()

  3. 获取Servlet路径: /demo1

String getServletPath()

4. 获取get方式请求参数:name=zhangsan

String getQueryString()

5. (*)获取请求URI:/day14/demo1

String getRequestURI(): /day14/demo1

StringBuffer getRequestURL() :http://localhost/day14/demo1

6. 获取协议及版本:HTTP/1.1

String getProtocol()

7. 获取客户机的IP地址:

String getRemoteAddr()

例子1:

@WebServlet("/requestDemo1")  //资源路径
public class RequestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求方式 :GET
        String method = request.getMethod();
        System.out.println(method);
        //2. (*)获取虚拟目录:/day3
        String contextpath = request.getContextPath();
        System.out.println(contextpath);
        //3. 获取Servlet路径: /demo1
        String servletpath = request.getServletPath();
        System.out.println(servletpath);
        //4. 获取get方式请求参数:name=zhangsan
        String querystring = request.getQueryString();
        System.out.println(querystring);
        //5. (*)获取请求URI:/day14/demo1
        String requseturi = request.getRequestURI();
        System.out.println(requseturi);
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(requestURL);
        //6. 获取协议及版本:HTTP/1.1
        String protocol = request.getProtocol();
        System.out.println(protocol);
        //7. 获取客户机的IP地址:
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
    }
}

2. 获取请求头数据

1.(常用)String getHeader(String name): 通过请求头的名称获取请求头的值

2.Enumeration<String> getHeaderNames(): 获取所有的请求头名称

@WebServlet("/requestDemo2")
public class RequestDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //演示获取请求头数据
        //1.获取请求头名称
        Enumeration<String> headerNames = request.getHeaderNames();
        //2.遍历
        while (headerNames.hasMoreElements()){
            //请求头名称
            String element = headerNames.nextElement();
            //根据名称获取请求头的值
            String value = request.getHeader(element);
            System.out.println(element+" :  "+value);
        }
    }
}

3. 获取请求体数据

请求体:只有POST请求方式会有请求体,在请求体中封装了POST请求的请求参数。

获取步骤:

1. 获取流对象

BufferedReader getReader():获取字符输入流,只能操作字符数据

ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据

2. 再从流对象中拿取数据

例子:

@WebServlet("/requestDemo5")
public class RequestDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求消息体
        //1. 获取字符流
        BufferedReader br = request.getReader();
        //2.读取数据
        String line = null;
        while ((line = br.readLine())!= null){
            System.out.println(line);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

4. 其他功能(重要):

1. 获取请求参数通用方式:不论get还是post请求方式都可以使用下列方法来获取请求参数

       1. String getParameter(String name): 根据参数名称获取参数值

       2. String[] getParameterValues(String name): 根据参数名称获取参数值的数组

       3. Enumeration<String> getParameterNames(): 获取所有请求的参数名称

       4. Map<String,String[]> getParameterMap(): 获取所有参数的map集合

例子:

@WebServlet("/requestDemo6")
public class RequestDemo6 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //post 获取请求参数
        String username = request.getParameter("username");
        System.out.println(username);
        System.out.println("----------");

        //根据参数名称获取参数值的数组
        String[] hobbies = request.getParameterValues("hobby");
        for(String hobby : hobbies){
            System.out.println(hobby);
        }
        System.out.println("----------");

        //获取所有请求的参数名称
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            System.out.println(name);
            String value = request.getParameter(name);
            System.out.println(value);
        }
        System.out.println("----------");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //  get 获取请求参数
        this.doPost(request,response);
    }
}

中文乱码问题:

get方式中:tomcat 8 已经将get方式乱码问题解决了

post方式:可能会乱码。解决方法:在获取参数前,设置request的编码

request.setCharacterEncoding("utf-8");

2. 请求转发:一种在服务器内部的资源跳转方式

1. 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)

2. 使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)

@WebServlet("/requestDemo7")
public class RequestDemo7 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo7被调用了。。");
        
        //转发到demo8资源
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestDemo8").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
@WebServlet("/requestDemo8")
public class RequestDemo8 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo8被调用了。。。");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

特点(面试):1.浏览器地址栏路径不发生变化。

                         2.只能转发到当前服务器内部资源中,不能到其他网址

                         3. 只存在一次请求,一次请求访问多个资源

3. 共享数据:

域对象:一个有作用范围的对象,可以在范围内进行共享数据

request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据。

方法:

         1. setAttribute(String name,Object obj); //存储数据

         2. Object getAttribute(String name); //通过键获取值

         3. void removeAttribute(String name); //通过键移除键值对

4.获取ServletContext

ServletContext getServletContext();

发布了169 篇原创文章 · 获赞 101 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/zzu_seu/article/details/105018749