zoukankan      html  css  js  c++  java
  • java基础77 Http协议及Servlet中的GET、POST提交方式

    本文知识点(目录):

        1、什么是http协议
        2、查看http协议的工具
        3、http协议的内容
        4、请求方式
        5、请求头和响应头(以及获取请求头信息的方法)
        6、实体内容
        7、获取传递的请求参数
        8、附录1、2、3、4



    1、什么是http协议

        http协议:是对浏览器(客户端)和服务端之间的数据传输的格式规范

    2、查看http协议的工具

        1)使用火狐--->右击选择”查看元素”/”检查”--->网络--->点击里面你的访问页面即可显示(如下图中的index.jsp)
        2)使用谷歌--->右击选择”审查元素”/”检查”--->NetWork--->Headers
        3)使用系统自带的telnet工具(远程访问工具) (命令提示符)
            a)telnet localhost 8080     访问tomcat服务器
            b)ctrl+] 回车   可以看到回显
            c)请输入请求内容:
                  GET /MyServlet/index.jsp HTTP/1.1
                  Host: localhost:8080
            d)回车,即可查看到服务器响应的信息

    3、http协议的内容

    项目中index.jsp页面的内容

     1 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     hello world!
    25   </body>
    26 </html>

    用浏览器访问的结果 http://localhost:8080/MyServlet/index.jsp (假如不出现以下页面,可多刷新几次)

        

    请求(浏览器)---->服务器

    GET /MyServlet/index.jsp HTTP/1.1   --请求行

    Host: localhost:8080                 --请求头(多个key-value对象)

    Connection: keep-alive

    Upgrade-Insecure-Requests: 1

    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8

    Accept-Encoding: gzip, deflate, br

    Accept-Language: zh-CN,zh;q=0.9

    响应(服务器) ---->浏览器

    HTTP/1.1 200 OK

    Server: Apache-Coyote/1.1

    Set-Cookie: JSESSIONID=408491619DF5756BAAF454FC2262AAAE; Path=/MyServlet; HttpOnly

    Content-Type: text/html;charset=ISO-8859-1

    Content-Length: 613

    Date: Fri, 07 Sep 2018 09:30:59 GMT

    附:请求路径
            URL:统一资源定位符。比如:http://localhost:8080/MyServlet/index.jsp 只能定位互联网资源,是URI的子集。
            URI:统一资源标识符。比如:/MyServlet/index.jsp 用于标记任何资源,可以是本地文件系统局域网资源,也可以是互联网资源

    附:http的协议版本
        http1.0:当前浏览器客户端与服务端建立连接之后,只能发送一次请求,发送一次请求之后连接关闭
        http1.1:当前浏览器客户端与服务端建立连接之后,可以在一次连接中发送多次请求(基本上都使用1.1)

    4、请求方式

        常见的请求方式:GET,POST,HRAD,TRACE,PUT,CONECT,DELETE
        常用的请求方式:GET和POST

    <form action=”提交地址” method=”GET/POST”>
    
    </from>

    4.1、GET方式提交

        a)地址栏 (URL) 会跟上参数数据。以?开头,多个参数之间以&分割    如:
        b)GET方式提交参数,数据限制,不超过1kb。
        c)GET方式不适合提交敏感数据 (如:密码)。
        d)注意:浏览器直接访问请求,默认请求方式是get方式。

    4.2、POST方式提交

        a)参数不会跟在URI后面,而是跟在请求实体内容中。没有?开头、多个参数之间以&分割  如:
        b)post方式提交参数,数据是没有限制的
        c)适合提交敏感数据

    5、请求头和响应头

    请求头

    Accept: text/html,image/*    -- 浏览器接受的数据类型
    Accept-Charset: ISO-8859-1    -- 浏览器接受的编码格式
    Accept-Encoding: gzip,compress  --浏览器接受的数据压缩格式
    Accept-Language: en-us,zh-      --浏览器接受的语言
    Host: www.it315.org:80    --(必须的)当前请求访问的目标地址(主机:端口)
    If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT    --浏览器最后的缓存时间
    Referer: http://www.it315.org/index.jsp    -- 当前请求来自于哪里
    User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)   --浏览器类型
    Cookie:name=eric     -- 浏览器保存的cookie信息
    Connection: close/Keep-Alive   -- 浏览器跟服务器连接状态。close: 连接关闭  keep-alive:保存连接。
    Date: Tue, 11 Jul 2000 18:23:51 GMT    -- 请求发出的时间

    响应头

    Location: http://www.it315.org/index.jsp   --表示重定向的地址,该头和302的状态码一起使用。
    Server:apache tomcat   ---表示服务器的类型
    Content-Encoding: gzip   -- 表示服务器发送给浏览器的数据压缩类型
    Content-Length: 80  --表示服务器发送给浏览器的数据长度
    Content-Language: zh-cn  --表示服务器支持的语言
    Content-Type: text/html; charset=GB2312   --表示服务器发送给浏览器的数据类型及内容编码
    Last-Modified: Tue, 11 Jul 2000 18:23:51 GMT  --表示服务器资源的最后修改时间
    Refresh: 1;url=http://www.it315.org   --表示定时刷新
    Content-Disposition: attachment; filename=aaa.zip   --表示告诉浏览器以下载方式打开资源(下载文件时用到)
    Transfer-Encoding: chunked
    Set-Cookie:SS=Q0=5Lb_nQ; path=/search   --表示服务器发送给浏览器的cookie信息(会话管理用到)
    Expires: -1     --表示通知浏览器不进行缓存
    Cache-Control: no-cache
    Pragma: no-cache
    Connection: close/Keep-Alive    --表示服务器和浏览器的连接状态。close:关闭连接 keep-alive:保存连接

    5.1、获取请求方式及请求头的信息

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.util.Enumeration;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 /**
    12  * @author DSHORE / 2018-9-7
    13  *
    14  */
    15 public class MyServletOne extends HttpServlet {
    16 
    17     public void doGet(HttpServletRequest request, HttpServletResponse response)
    18             throws ServletException, IOException {
    19         //设置编码
    20         response.setContentType("text/html;charset=UTF-8");
    21         //请求行  格式:(GET /day09/index.html HTTP/1.1)    
    22         System.out.println("请求方式:"+request.getMethod());//请求方式
    23         System.out.println("URI:"+request.getRequestURI());//请求资源
    24         System.out.println("URL:"+request.getRequestURL());
    25         System.out.println("http协议版本:"+request.getProtocol());//http协议
    26         System.out.println();
    27         
    28         //请求头
    29         String host=request.getHeader("Host");//根据头名称的头得到头的内容
    30         System.out.println("请求头:"+host);
    31         Enumeration<String> enums=request.getHeaderNames();//得到所有请求头列表
    32         while(enums.hasMoreElements()){//判断是否有下一个元素
    33             String headerName=enums.nextElement();//取出下一位元素
    34             String headerValue=request.getHeader(headerName);
    35             System.out.println(headerName+":"+headerValue);
    36         }
    37     }
    38 }

    结果图

    6、实体内容

        只有POST提交的参数才会放到实体内容中,GET提交方式没有。

    6.1、HttpServletRequest对象

    HttpServletRequest对象获取请求的信息
      请求行:
            Request.getMethod();  --请求方式
            Request.getRequestURI();  --请求资源
            Request.getProtocol();  --请求http的协议版本
      请求头:
            request.getHeader(“名称”);  --根据请求名称获取请求的值
            request.getHeaderNames();   --获取所有的请求头的名称
      实体内容:
            request.getInputStream()  --获取实体内容数据

    6.2、实例

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 import java.io.PrintWriter;
     6 import java.util.Enumeration;
     7 
     8 import javax.servlet.ServletException;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 /**
    14  * @author DSHORE / 2018-9-11
    15  *
    16  */
    17 public class MyServletTwo extends HttpServlet {
    18     public void doPost(HttpServletRequest request, HttpServletResponse response)
    19             throws ServletException, IOException {
    20         //设置编码
    21         response.setContentType("text/html;charset=UTF-8");
    22         //请求行  格式:(GET /day09/index.html HTTP/1.1)    
    23         System.out.println("请求方式:"+request.getMethod());//请求方式
    24         System.out.println("URI:"+request.getRequestURI());//请求资源
    25         System.out.println("URL:"+request.getRequestURL());
    26         System.out.println("http协议版本:"+request.getProtocol());//http协议
    27         System.out.println();
    28         
    29         //请求头
    30         String host = request.getHeader("Host");//根据头名称的头得到头的内容
    31         System.out.println("请求头:"+host);
    32         Enumeration<String> enums = request.getHeaderNames();//得到所有请求头列表
    33         while(enums.hasMoreElements()){//判断是否有下一个元素
    34             String headerName = enums.nextElement();//取出下一位元素
    35             String headerValue = request.getHeader(headerName);
    36             System.out.println(headerName+":"+headerValue);
    37         }
    38         
    39         System.out.println();
    40         //获取请求头的实体内容
    41         InputStream is = request.getInputStream();//得到实体内容
    42         //读实体内容
    43         byte[] buf = new byte[1024];
    44         int length = 0;
    45         while ((length = is.read(buf)) != -1){
    46             String str = new String(buf,0,length);//把实体内容转换成字符串的形式
    47             System.out.println("实体内容:"+str);
    48         }
    49     }
    50 }

    结果图

    6.3、页面报405错误的原因及解决方法

        

    7、获取传递的请求参数

      1、GET方式:参数放在URI后面
      2、POST方式:参数放在实体内容中
          GET方式获取参数:Request.getQueryString();
          POST方式获取参数:Request.getInputStream();
    注意:但是以上两种不通用,而且获取到参数还需要进一步解析,所以需要统一方便的获取参数的方式:
    Request.getParameter(“参数名”);   根据参数名获取参数值(注意:只能获取一个参数值)

    7.1、实例

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 /**
    12  * @author DSHORE / 2018-9-11
    13  *
    14  */
    15 public class MyServletTree extends HttpServlet {
    16     public void doGet(HttpServletRequest request, HttpServletResponse response)
    17             throws ServletException, IOException {
    18         String value=request.getQueryString();//GET方式获取实体内容参数
    19         System.out.println("实体内容参数:"+value);//返回值:name=haha&password=123&sex=nv&jiguan=gd&hobit=lq&hobit=ymq&info=helloWorld&id=001
    20         
    21         String name=request.getParameter("name");
    22         String pass=request.getParameter("password");
    23         System.out.println(name+":"+pass);//返回值:haha:123
    24         String sex=request.getParameter("sex");
    25         System.out.println("性别:"+sex);//返回值:nv
    26         String jiguan=request.getParameter("jiguan");
    27         System.out.println("籍贯:"+jiguan);//返回值:gd
    28         String[] hobit=request.getParameterValues("hobit");
    29         for (String string : hobit) {
    30             System.out.println("爱好:"+string);//返回值:lq、ymq
    31         }
    32         String info=request.getParameter("info");
    33         System.out.println("个人简历:"+info);//返回值:helloWorld
    34         String id=request.getParameter("id");
    35         System.out.println("编号:"+id);//返回值:001
    36     }
    37 
    38     public void doPost(HttpServletRequest request, HttpServletResponse response)
    39             throws ServletException, IOException {
    40         doGet(request, response);//调用doGet()方法
    41         InputStream value=request.getInputStream();//POST方式获取实体内容参数
    42         byte[] buf=new byte[1024];
    43         int len=0;
    44         while((len=value.read(buf))!=-1){
    45             String str=new String(buf,0,len);
    46             System.out.println(str);
    47         }
    48         String name=request.getParameter("name");
    49         System.out.println(name);
    50     }
    51 }

    getParamter.html

     1 <!DOCTYPE html>
     2 <html>
     3   <head>
     4     <title>getParamter.html</title>
     5     
     6     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     7     <meta http-equiv="description" content="this is my page">
     8     <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     9     
    10     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    11 
    12   </head>
    13   
    14   <body>
    15     <h3>GET提交方式</h3>
    16     <form action="MyServletTree" method="get">
    17         用户名:<input type="text" name="name"/><br/>
    18         密    码:<input type="password" name="password"/><br/>
    19         <input type="radio" name="sex" value="nan"/>20         <input type="radio" name="sex" value="nv"/>21         籍贯:
    22             <select name="jiguan">
    23                 <option value="gd">广东</option>
    24                 <option value="gx">广西</option>
    25                 <option value="hb">湖北</option>
    26             </select>
    27             <br/>
    28         爱好:
    29         <input type="checkbox" name="hobit" value="lq"/>篮球
    30         <input type="checkbox" name="hobit" value="zq"/>足球
    31         <input type="checkbox" name="hobit" value="ymq"/>羽毛球</br>
    32         个人简历:
    33         <textarea rows="5" cols="10" name="info"></textarea><br/>
    34         <input type="hidden" name="id" value="001"/>
    35         <input type="submit" value="提交"/>
    36     </form>
    37   </body>
    38 </html>

    运行后的结果图(效果图)

    控台显示的结果

    附录1

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.ServletRequest;
     8 import javax.servlet.ServletResponse;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 /*
    13  * 注意:tomcat服务器首先会调用servlet的service方法,然后在service方法中根据请求方式分别调用对应的doXX方法
    14  *  (例如:如果是GET请求方式,在service方法中调用doGet方法)
    15  *
    16  * 因为最常见的请求方式是GET和POST,所有编写servlet程序,只需要覆盖doGet和doPost方法
    17  * */
    18 public class Demo2Request extends HttpServlet {
    19     @Override
    20     protected void service(HttpServletRequest req, HttpServletResponse resp)
    21             throws ServletException, IOException {
    22         System.out.println("service方法被调用");
    23         System.out.println(req.getMethod());
    24     }
    25     public void doGet(HttpServletRequest request, HttpServletResponse response)
    26             throws ServletException, IOException {
    27         System.out.println("GET方式提交");
    28     }
    29     @Override
    30     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    31             throws ServletException, IOException {
    32         System.out.println("POST方式提交");
    33     }
    34 }

    附录2

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 /*
    11  * 案例:获取浏览器的类型
    12  * */
    13 public class Demo3Request extends HttpServlet {
    14     public void doGet(HttpServletRequest request, HttpServletResponse response)
    15             throws ServletException, IOException {
    16         response.setContentType("text/html;charset=utf-8");
    17         //获取请求头
    18         String userAgen=request.getHeader("User-Agent");
    19         System.out.println(userAgen);
    20         //判断用户使用浏览器的类型
    21         if(userAgen.contains("Firefox")){
    22             System.out.println("你正在使用火狐浏览器");
    23         }else if(userAgen.contains("Chrome")){
    24             System.out.println("你正在使用谷歌浏览器");
    25         }else if (userAgen.contains("Trident")) {
    26             System.out.println("你正在使用IE浏览器");
    27         }else{
    28             System.out.println("你使用的是其他品牌的浏览器");
    29         }
    30     }
    31     public void doPost(HttpServletRequest request, HttpServletResponse response)
    32             throws ServletException, IOException {
    33     }
    34 }

    附录3

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 /*
    11  * 案例-防止非法链接(防止直接跳过原页面,即没够买VIP就直接跳到VIP页面使用)
    12  * 这里需要下载的资源
    13  * */
    14 public class Demo4Request extends HttpServlet {
    15     public void doGet(HttpServletRequest request, HttpServletResponse response)
    16             throws ServletException, IOException {
    17         response.setContentType("text/html;charset=utf-8");
    18         //得到Referer头
    19         String referer=request.getHeader("Referer");
    20         System.out.println("referer"+referer);
    21         /*
    22          * 判断非链接:
    23          * 1)直接访问的话referer=null
    24          * 2)如果当前请求不是来自与广告
    25          * */
    26         if(referer==null || !referer.contains("/day18/adv.html")){
    27             response.getWriter().write("当前是非法的链接,请回到.<a href='/day18/adv.html'>首页</a>");
    28         }else{
    29             //正确的链接
    30             response.getWriter().write("海量资源,资源正在下载");
    31         }
    32     }
    33     public void doPost(HttpServletRequest request, HttpServletResponse response)
    34             throws ServletException, IOException {
    35     }
    36 }

    附录4

    1、请求参数的编码问题

    1.1、修改post方式参数的编码
        Request.setCharacterEncoding(“utf-8”);
    1.2、修改get方式参数的编码(有多少个参数就写多少次;或者直接修改Tomcat中配置文件[即在端口号那一行代码后面加上URLEncoding=“utf-8”;],不建议这样做)
        String name=request.getParameter("name");
        String names=new String(name.getBytes(“iso8859-1”),”utf-8”);

    2、状态码:服务器处理请求的结果(状态)

    常见的状态码
        200:表示请求处理完成完美返回
        302:表示请求需要进一步细化
        404:表示客户访问的资源找不到(即找不到访问路径或者说路径错误)
        500:表示服务器资源发送错误(服务器内部错误,即代码错误)

    3、总结

    http协议:浏览器和服务器之间数据传输的格式规范
    1、http请求
        a)格式
        b)请求行
        c)请求头
        d)空行
        e)实体内容(post提交数据的实体内容)
    重点:使用HttpServletRequest对象;获取请求数据
    2、http响应
        a)格式
        b)响应行
        c)响应头
        d)空行
        e)实体内容(浏览器上看到内容)
    重点:使用HttpServletResponse对象;设置响应数据

     1 package com.shore.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 /*
    11  * 案例:定时刷新
    12  * */
    13 public class Demo3Response extends HttpServlet {    
    14     public void doGet(HttpServletRequest request, HttpServletResponse response)
    15             throws ServletException, IOException {
    16         //知识点1:设置响应实体内容编码
    17         /*response.setCharacterEncoding("utf-8");
    18         response.setContentType("text/xml");*/
    19         request.setCharacterEncoding("utf-8");
    20         response.setContentType("text/html;charset=utf-8");
    21             
    22         /*
    23          * 知识点2:定时刷新
    24          * 原理:浏览器认识Refresh头,得到Refresh之后重写请求当前资源
    25          * */
    26         response.setHeader("Refresh","1");//每隔一秒,刷新一次
    27         //隔n秒之后跳转到另一个资源
    28         response.setHeader("Refresh","3;url=/MyServletTree/Index.html");//隔3秒跳转到Index.html页面
    29         
    30         /*
    31          * 知识点3:需求跳转到index.html
    32          * 使用请求重定向:发送一个302状态码+localhost响应头
    33          * */
    34         response.setStatus(302);//发送一个302状态码
    35         response.setHeader("location","/MyServletTree/Index.html");//localhost的响应头 (页面跳转,但,不是重定向的方式)
    36         //response.sendRedirect("/MyServletTree/Index.html");//重定向(页面跳转)
    37         
    38         //知识点4:以html的格式向页面写内容
    39         response.getOutputStream().write("<html><head><title>this is title</title></head><body>中国</body></html>".getBytes());
    40         //response.getWriter().write("<html><head><title>this is title</title></head><body>love me 何</body></html>");
    41         
    42         //知识点5:下载图片
    43         response.setContentType("image/jpg");
    44         File f=new File("F://imge/1188260.jpg");
    45         //发送图片
    46         FileInputStream in=new FileInputStream(f);
    47         byte[] buf=new byte[1024];
    48         int len=0;
    49         while((len=in.read(buf))!=-1){
    50                 response.getOutputStream().write(buf,0,len);
    51         }
    52         //下载图片
    53         response.setHeader("Content-Disposition", "attachment; filename="+f.getName());    
    54     }
    55     
    56     public void doPost(HttpServletRequest request, HttpServletResponse response)
    57             throws ServletException, IOException {
    58         doGet(request, response);
    59     }
    60 }

    原创作者:DSHORE

    作者主页:http://www.cnblogs.com/dshore123/

    原文出自:https://www.cnblogs.com/dshore123/p/9599952.html

    欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

  • 相关阅读:
    System.Windows.Forms.Timer与System.Timers.Timer的区别(zz)
    30个最常用css选择器解析(zz)
    Highcharts选项配置详细说明文档(zz)
    CSS For Bar Graphs(maybe old)
    学习CSS3BUTTON(二)
    学习CSS3BUTTON(一)
    CSS CURSOR属性
    CSS3的文字阴影—text-shadow
    display:inline-block; 到底是个啥玩意?
    mysql 子查询
  • 原文地址:https://www.cnblogs.com/dshore123/p/9599952.html
Copyright © 2011-2022 走看看