JavaWeb

Request&Response

2022-11-17  本文已影响0人  h2coder

概述

Request对象

Request对象,用来封装请求数据的对象

Request的继承关系

1628740441008.png

Request获取数据

@WebServlet(value = "/req03")
public class Demo3Servlet extends HttpServlet {
    private static final long serialVersionUID = -556975635735989032L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request);
    }

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

获取请求行数据

请求行,包含请求方式、请求资源路径、HTTP协议以及版本号

1628748240075.png
request.getMethod();
request.getContextPath();
request.getRequestURI();
request.getRequestURL();
request.getQueryString();

获取请求头数据

1628768652535.png
//请求头数据:
//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
//Accept-Encoding: gzip, deflate, br
//Accept-Language: zh-CN,zh;q=0.9
//User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/53

System.out.println("浏览器支持的资源类型 Accept = " + req.getHeader("accept"));
System.out.println("浏览器的版本 User-Agent = " + req.getHeader("user-agent"));

获取请求体数据

1628768665185.png
ServletInputStream inputStream = request.getInputStream();
BufferedReader reader = request.getReader();

获取请求参数的通用方式

GET请求的请求参数在请求行中,拼接在资源路径中。POST请求的请求参数在请求体中。那么获取请求参数的方式就不同。

String params = request.getQueryString()
BufferedReader reader = request.getReader();

那么针对不同的请求方式,需要区分编写,实在太麻烦了,所以Request对象提供了3种获取方法。

Map<String, String[]> parameterMap = request.getParameterMap();
String[] hobbys =  getParameterValues("hobby");
String username = request.getParameter("username");

请求参数中文乱码问题

如果是POST请求,请求参数中存在中文,获取时,就会乱码。

1628829610823.png

原因:

@WebServlet(value = "/req03")
public class Demo3Servlet extends HttpServlet {
    private static final long serialVersionUID = -556975635735989032L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Tomcat 8.0 后,GET请求中文已经处理了中文乱码问题,但POST没有处理
        //重点:POST请求的参数放在请求体中,默认编码是ISO-8859-1,而不是UTF-8,中文就会乱码,所以需要重新指定
        request.setCharacterEncoding("UTF-8");

        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println("key = " + entry.getKey() + "," + "value = " + Arrays.toString(entry.getValue()));
        }
    }

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

Request请求转发

请求转发,是一种在服务器内部的资源跳转方式

1628851404283.png
request.getRequestDispatcher(path).forward(request, response);
//存数据到Request域
request.setAttribute("name", "zhang san");
//从Request域中获取数据
Object attribute = request.getAttribute("name");
//从Request域中删除数据
request.removeAttribute("name");

示例代码

/**
 * 转发前的资源
 */
@WebServlet(value = "/a")
public class Demo4Servlet extends HttpServlet {
    private static final long serialVersionUID = 5039248570478620151L;

    public static final String KEY_NAME = "name";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决POST请求参数中文乱码问题
        request.setCharacterEncoding("UTF-8");

        //请求转发的特点:
        //1、转发后,地址栏的URL地址不变
        //2、转发只有一次请求
        //3、只能转发给当前服务器的内部的资源,不能请求外部的!

        System.out.println("---------------- demo4 servlet,发起请求转发 ----------------");
        //跳转的路径
        String path = "b";

        //存数据
        request.setAttribute(KEY_NAME, "zhang san");
        System.out.println("demo4 servlet 存数据到request中...");

        request.getRequestDispatcher(path).forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
/**
 * 跳转后的资源
 */
@WebServlet(value = "/b")
public class Demo5Servlet extends HttpServlet {
    private static final long serialVersionUID = 7691480142539364773L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("---------------- demo5 servlet,收到请求 ----------------");
        System.out.println("b 资源");

        //获取传递的数据
        Object attribute = request.getAttribute(Demo4Servlet.KEY_NAME);
        System.out.println("demo5 servlet 获取到的数据:" + attribute);
    }

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

请求转发的特点

Response对象

Response对象,用来封装响应数据的对象

Response继承体系

1628857761317.png

Response响应数据

HTTP响应数据,包括三大内容,分别是响应行、响应头、响应体

设置响应行

响应行,也有三部分组成,分别是HTTP协议及其版本号、响应状态码、响应状态码的描述,对于响应行的设置,我们一般只设置响应码即可,其他的将有Tomcat帮我们自动填充上

1628858926498.png
//状态码 200 代表请求成功
response.setStatus(200);

设置响应头

响应头和请求头一样,都是由key-value键值对构成

1628859051368.png
//Content-Type响应头,代表本次请求响应的数据类型,text/html代表HTML类型的文本数据
response.setHeader("Content-Type", "text/html");

设置响应体

响应体分为字节数据和字符数据,分别对应2个方法

1628859268095.png
ServletOutputStream out = response.getOutputStream();
PrintWriter writer = response.getWriter();

Response响应中文乱码问题

想写出字符输出到响应体,返回给浏览器显示时,如果字符数据中存在中文,则会出现乱码

1628846824194.png

原因:

解决方案

 response.setContentType("text/html;charset=utf-8");

Response重定向

重定向,是一种资源跳转方式,需要服务端和客户端进行配合

1628859860279.png

场景流程

实现重定向

//方式一:设置302状态码,以及响应头location,设置目标地址
response.setStatus(302);
response.setHeader("location", url);

//方式二:使用sendRedirect()方法(推荐这种)
response.sendRedirect(url);

示例代码

/**
 * 跳转前
 */
@WebServlet(value = "/c")
public class Demo7Servlet extends HttpServlet {
    private static final long serialVersionUID = 419981648051969464L;

    public static final String KEY_NAME = "name";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("资源 c");

        //重定向的特点:
        //1、浏览器的地址栏地址改变为重定向的地址
        //2、会发起2次请求
        //3、3次请求之间,不能数据共享

        //存储数据到request
        request.setAttribute(KEY_NAME, "zhang san");

        //发起重定向

        String url = "d";

        //方式一:设置302状态码,以及响应头location,设置目标地址
        //response.setStatus(302);
        //response.setHeader("location", url);
        //方式二:使用sendRedirect()方法(推荐这种)
        response.sendRedirect(url);

        //可以重定向到服务器外的资源
        //response.sendRedirect("http://www.baidu.com");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
/**
 * 跳转后
 */
@WebServlet(value = "/d")
public class Demo8Servlet extends HttpServlet {
    private static final long serialVersionUID = 3830075411283682097L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("资源 d");

        Object attribute = request.getAttribute(Demo7Servlet.KEY_NAME);
        System.out.println("获取数据:" + attribute);
    }

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

重定向的特点

请求转发和重定向对比

1628862652700.png 1628862170296.png

Response响应字节数据

//获取响应体输出流
ServletOutputStream out = response.getOutputStream();

//读取文件
FileInputStream fis = new FileInputStream("C:\\Develop\\Code\\Java\\java_up_181\\day24-request-response\\src\\main\\webapp\\imgs\\Desert.jpg");

//写字节数据到响应体中
byte[] buf = new byte[1024 * 8];
int len;
while ((len = fis.read(buf)) != -1) {
    out.write(buf, 0, len);
}

Response响应字符数据

//获取响应体字符输出流
PrintWriter writer = response.getWriter();

//写出字符数据到响应体
writer.write("<h1>哈哈哈哈</h1>");
writer.flush();
上一篇下一篇

猜你喜欢

热点阅读