D27-Request

一、http协议

1.1 http协议的基本概念

超文本传输协议(HTTP): 是互联网上应用最为广泛的一种网络协议。

1.1.1 http的作用

互联网的数据传输底层依赖tcp协议,http协议在tcp协议之上,它规范了传输数据的内容和格式。
在这里插入图片描述

1.2 请求信息的组成部分

在这里插入图片描述
浏览器的请求方式: get和post

1.2.2 请求行

  1. 请求行介绍

在这里插入图片描述
在这里插入图片描述
请求方式:

  • get:请求参数会在地址栏上显示,提交数据量受限,不安全。
  • post:请求参数不会再地址栏上显示,提交数据量不受限制,相对安全。

在地址栏中直接输入请求资源–get请求
超链接发送的请求是–get请求
location.href = 路径—get请求
form表单默认请求方式 – get请求
form表单上的method = post;

1.2.3 请求头:约束请求参数的类型和格式

格式: key/values的格式(values可以为多个值的)
常见的请求头

名称说明
Accept支持数据类型
Accept-Charset字符集
Accept-Encoding支持压缩
Accept-Language语言环境
Host访问主机
If-Modified-Since缓存文件的最后修改时间
Referer※来自哪个页面,防盗链
User-Agent※用户代理
Cookie※
Connectionclose/Keep-Alive --链接状态

两个比较重要的头:
Referer: http://localhost:8080/day03_web01/ ----上一次请求的地址
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 --------当前用户的系统和浏览器版本

1.2.4 请求体

请求体内容: 注意:get请求没有请求体,post请求有请求体。

二、 request对象获取请求信息

2.1 request对象的基本概念

2.1.1 什么是HttpServletRequest?

HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求中的所有信息都封装在这个对象中,开发人员通过这个对象的方法,可以获得客户这些信息。

  • 通过Request对象进行的常用操作:
    获取客户机信息
    获取请求头信息
    获取请求参数
    利用请求域传递对象

2.2 request获取请求行信息

2.2.1 请求行的组成元素(通过request获取请求行数据)

请求行的内容:请求方式,请求路径,协议版本

2.2.2 API介绍

  • String getMethod():获取请求方式的类型

  • String getRequestURI():获取请求行中的资源名部分

  • StringBuffer getRequestURL():获取客户端发出请求完整URL
    注: URI:统一资源标识符,用来标识一个资源。
    URL:统一资源定位符,是一种具体的URL。可以用来标识一个资源,并且指明了如何定位一个资源。

  • String getProtocol():获取当前协议的名称和版本。

  • String getRemoteAddr():获取IP地址。

  • int getlocalPort():获取端口号。

  • String getRequestURI(): 获取请求资源(不带get请求的参数)

  • String getQueryString(): 获取get请求参数以一个字符串返回get请求的参数

2.2.3 使用步骤

  1. 创建DemoServlet
  2. 在DemoServlet中的doGet或者doPost方法的参数列表,已经包含了request对象,调用方法即可。
  3. 将数据打印在控制台。
    代码:
package com.itheima.a_row;

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(name = "RowServlet",urlPatterns = "/row")
public class RowServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求方式
        String method = request.getMethod();
        System.out.println("method请求方式:"+method);

        //获取项目路径
        String contextPath = request.getContextPath();
        System.out.println("项目路径:"+contextPath);

        //获取请求者ip
        String remoteAddr = request.getRemoteAddr();
        System.out.println("获取ip地址:"+remoteAddr);
        //获取端口号
        int localPort = request.getLocalPort();
        System.out.println("获取端口号:"+localPort);
        System.out.println("-----------------");
        //了解的方法
        //获取请求资源,不带get请求的参数
        String requestURI = request.getRequestURI();
        System.out.println("获取请求资源:"+requestURI);
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("获取URL:"+requestURL);

        //获取get请求参数以一个字符串返回get请求的参数
        String queryString = request.getQueryString();
        System.out.println("获取get字符串:"+queryString);

        //获取协议和版本
        String protocol = request.getProtocol();
        System.out.println("获取版本和协议:"+protocol);

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

输出结果!

2.3 request请求头信息

2.3.1 获取请求头信息的常用方法

API介绍:

  • String getHeader(String name):以String的形式返回指定请求头的值。
  • Enumeration getHeaderNames():返回请求包含的所有头名称和枚举。
    常用的请求头:
  • user-agent :用户代理
  • referer:页面的来源,防盗链

2.3.1使用步骤

  1. 创建DemoServlet2
  2. 在DemoServlet2中的doGet或者doPost方法的参数列表,已经包含了request对象。因此,调用方法即可
  3. 将结果打印在控制台!

代码

@WebServlet(name = "HeaderServlet",urlPatterns = "/header")
public class HeaderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求 头信息
        //获取user - agent的值
        String header = request.getHeader("user-agent");
        System.out.println("user-agent头信息:"+header);
        //获取防盗链信息
        String referer = request.getHeader("referer");
        System.out.println("防盗链信息:"+referer);

        //了解
        //获取请求携带的所有头名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            System.out.println("头名称:"+headerNames.nextElement());
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

结果:
请求头代码结果

2.4 案例:获取防盗链

@WebServlet(name = "AnliServlet", urlPatterns = "/download")
public class AnliServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决响应信息乱码问题(设置响应文件的mime类型)
        response.setContentType("text/html;charset=utf-8");
        //1.编写downloadServlet
        //2.获取防盗链信息
        String referer = request.getHeader("referer");
        System.out.println("防盗链信息:"+referer);
        //3.判断防盗链
        if(referer!=null){
            if (referer.endsWith("download.html")){
                System.out.println("允许下载!");
                response.getWriter().print("success 允许下载!");
            }else {
                System.out.println("不允许下载!");
                response.getWriter().print("false 不允许下载!");
            }
        }else {
            System.out.println("不予许下载!");
        }
    }

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

结果:
防盗链案例结果

2.5 请求体:获取请求参数

2.5.1 API介绍

  • String getParameter(String name): 根据表单的name属性,获取对应的值。
  • String[ ] getParameterValues(String name): 获取name相同的所有value ,例如复选框
  • Map getParameterMap(): 参数名作为key。参数值作为value,封装到map中。

2.5.2 使用步骤

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>params</title>
</head>
<body>
<h1>操作请求参数</h1>
<form action="params.html" method="get">
    用户名:<input type="text" name="username" value="tom"><br>
    密码  :<input type="password" name="password" value="123"><br>
   爱好:
    <input type="checkbox" name="hobby" value="smoke"> 抽烟
    <input type="checkbox" name="hobby" value="drink"> 喝酒
    <input type="checkbox" name="hobby" value="makefair"> 烫头
    <input type="checkbox" name="hobby" value="coding"> 敲代码
    <br>
    <input type="submit" value="get提交">
</form>
<hr>
<form action="params.html" method="post">
    用户名:<input type="text" name="username" value="tom"><br>
    密码  :<input type="password" name="password" value="123"><br>
    爱好:
    <input type="checkbox" name="hobby" value="smoke"> 抽烟
    <input type="checkbox" name="hobby" value="drink"> 喝酒
    <input type="checkbox" name="hobby" value="makefair"> 烫头
    <input type="checkbox" name="hobby" value="coding"> 敲代码
    <br>
    <input type="submit" value="post提交">
</form>
</body>
</html>

代码:

@WebServlet(name = "ParamsServlet", urlPatterns = "/params")
public class ParamsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置request对象的编码格式
        request.setCharacterEncoding("utf-8");
        //操作请求参数
        //注意事项
        String username1 = request.getParameter("username1");
        System.out.println("username1:"+username1);

        //获取用户信息
        String username = request.getParameter("username");
        System.out.println("username:"+username);

        //获取密码值
        String password = request.getParameter("password");
        System.out.println("password:"+password);

        //获取爱好值
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbies));

        //获取请求携带的所有参数信息,并封装到map中
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()){
            System.out.println(key +":"+Arrays.toString(parameterMap.get(key)));
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

2.6 乱码的解决

2.6.1 API

void setCharacterEncoding(String env): 设置请求体的编码
代码:

 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) thro
ServletException, IOException {
        
        //处理post请求乱码
        request.setCharacterEncoding("utf‐8");
        String username = request.getParameter("username");
        System.out.println(username);
    }
}

2.7 request域对象

2.7.1 什么是域对象?

  • 域对象是一个容器,这种容器主要用于servlet与servlet之间的数据传输使用的。

2.7.2 API介绍

  • void setAttribute(String name,Object o): 设置数据到域中。
  • Object getAttribute(String name): 从域中获取数据
  • void removeAttribute(String name): 从域中移除数据。

代码:

@WebServlet(name = "ScopeServlet",urlPatterns = "/scope")
public class ScopeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
        doGet(request, response);
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
        //存入数据
        request.setAttribute("name","张三");
        //获取数据
        String name1 = (String) request.getAttribute("name");
        System.out.println(name1);
        //移除数据
        request.removeAttribute("name");
        String name2 = (String) request.getAttribute("name");
        System.out.println(name2);
    }
}

2.8 案例:请求转发

2.8.1 API介绍

  • RequestDispatcher getRequestDispatcher(String path): 获取请求转发器(request对象方法)
  • void forward((ServletRequest request, ServletResponse response): 将请求转发到令一个资源上。

MyServlet

@WebServlet(name = "MyServlet", urlPatterns = "/my")
public class MyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("班长曰: 帅哥,借我钱!");
        System.out.println("我曰: 借多少?");
        System.out.println("班长曰: 自己获取!");
        String money = request.getParameter("money");
        System.out.println(money);
        System.out.println("我曰: 我没有零钱,稍等...");
        // 设置共享数据
        request.setAttribute("msg","<<班长>>");
        // 请求转发
        // 请求转发的路径为:项目内部路径
        request.getRequestDispatcher("jiji").forward(request,response);

    }

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

JijiServlet

@WebServlet(name = "JijiServlet", urlPatterns = "/jiji")
public class JijiServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("-----------------");
        Object msg = request.getAttribute("msg");
        System.out.println("我曰: 班主任," + msg + "没钱吃饭了,你去给他送点钱.");
        System.out.println("班主任曰:送多少?");
        System.out.println("我曰:自己获取");
        String money = request.getParameter("money");
        System.out.println(money);

        request.setAttribute("msg", "hahahah");//修改
        Object msg1 = request.getAttribute("msg");
        System.out.println("msg1" + msg1);

        request.removeAttribute("msg");//删除
        Object msg2 = request.getAttribute("msg");
        System.out.println("msg2:" + msg2);

        response.getWriter().print("success!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值