RequestResponse使用

news2025/6/23 3:06:09

文章目录

  • 一、Request&Response介绍
  • 二、Request 继承体系
  • 三、Request 获取请求数据
    • 1、获取请求数据方法
      • (1)、请求行
      • (2)、请求头
      • (3)、请求体
    • 2、通过方式获取请求参数
    • 3、IDEA模板创建Servlet
    • 4、请求参数中文乱码处理
  • 四、Request 请求转发
  • 五、Response 设置相应数据功能介绍
  • 六、Response 完成重定向
    • 路径问题
  • 七、Response 响应字符数据
  • 八、Response 响应字节数据

一、Request&Response介绍

在这里插入图片描述

二、Request 继承体系

在这里插入图片描述

三、Request 获取请求数据

1、获取请求数据方法

(1)、请求行

在这里插入图片描述

   @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // String getMethod():获取请求方式: GET
        String method = req.getMethod();
        System.out.println(method);//GET
        // String getContextPath():获取虚拟目录(项目访问路径):/request-demo
        String contextPath = req.getContextPath();
        System.out.println(contextPath);
        // StringBuffer getRequestURL(): 获取URL(统一资源定位符):http://localhost:8080/request-demo/req1
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());
        // String getRequestURI():获取URI(统一资源标识符): /request-demo/req1
        String uri = req.getRequestURI();
        System.out.println(uri);
        // String getQueryString():获取请求参数(GET方式): username=zhangsan
        String queryString = req.getQueryString();
        System.out.println(queryString);


        //------------
        // 获取请求头:user-agent: 浏览器的版本信息
        String agent = req.getHeader("user-agent");
        System.out.println(agent);


    }

(2)、请求头

在这里插入图片描述

// 获取请求头:user-agent: 浏览器的版本信息
        String agent = req.getHeader("user-agent");
        System.out.println(agent);

(3)、请求体

在这里插入图片描述

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取post 请求体:请求参数

        //1. 获取字符输入流
        BufferedReader br = req.getReader();
        //2. 读取数据
        String line = br.readLine();
        System.out.println(line);


    }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/request-demo/req4" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit">

</form>



</body>
</html>

2、通过方式获取请求参数

统一doGet和doPost方法内的代码
在这里插入图片描述

package com.itheima.web.request;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;

/**
 * request 通用方式获取请求参数
 */
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //GET请求逻辑
        //System.out.println("get....");

        //1. 获取所有参数的Map集合
        Map<String, String[]> map = req.getParameterMap();
        for (String key : map.keySet()) {
            // username:zhangsan lisi
            System.out.print(key+":");

            //获取值
            String[] values = map.get(key);
            for (String value : values) {
                System.out.print(value + " ");
            }

            System.out.println();
        }

        System.out.println("------------");

        //2. 根据key获取参数值,数组
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {

            System.out.println(hobby);
        }

        //3. 根据key 获取单个参数值
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username);
        System.out.println(password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //POST请求逻辑

        this.doGet(req,resp);

        /*System.out.println("post....");

        //1. 获取所有参数的Map集合
        Map<String, String[]> map = req.getParameterMap();
        for (String key : map.keySet()) {
            // username:zhangsan lisi
            System.out.print(key+":");

            //获取值
            String[] values = map.get(key);
            for (String value : values) {
                System.out.print(value + " ");
            }

            System.out.println();
        }

        System.out.println("------------");

        //2. 根据key获取参数值,数组
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {

            System.out.println(hobby);
        }

        //3. 根据key 获取单个参数值
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username);
        System.out.println(password);*/


    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/request-demo/req4" method="post">
    <input type="text" name="username"><br>
    <input type="password" name="password"><br>
    <input type="checkbox" name="hobby" value="1"> 游泳
    <input type="checkbox" name="hobby" value="2"> 爬山 <br>
    <input type="submit">

</form>



</body>
</html>

3、IDEA模板创建Servlet

在这里插入图片描述

4、请求参数中文乱码处理

在这里插入图片描述

package com.itheima.web.request;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLDemo {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String username = "张三";

        //1. URL编码
        String encode = URLEncoder.encode(username, "utf-8");
        System.out.println(encode);

        //2. URL解码
        //String decode = URLDecoder.decode(encode, "utf-8");
        String decode = URLDecoder.decode(encode, "ISO-8859-1");

        System.out.println(decode);

        //3. 转换为字节数据,编码
        byte[] bytes = decode.getBytes("ISO-8859-1");
      /*  for (byte b : bytes) {
            System.out.print(b + " ");
        }*/

        //4. 将字节数组转为字符串,解码
        String s = new String(bytes, "utf-8");

        System.out.println(s);


    }
}

package com.itheima.web.request;


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 中文乱码问题解决方案
 */
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 解决乱码:POST,getReader()
        //request.setCharacterEncoding("UTF-8");//设置字符输入流的编码

        //2. 获取username
        String username = request.getParameter("username");
        System.out.println("解决乱码前:"+username);

        //3. GET,获取参数的方式:getQueryString
        // 乱码原因:tomcat进行URL解码,默认的字符集ISO-8859-1
       /* //3.1 先对乱码数据进行编码:转为字节数组
        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        //3.2 字节数组解码
        username = new String(bytes, StandardCharsets.UTF_8);*/

        username  = new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);

        System.out.println("解决乱码后:"+username);

    }

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

在这里插入图片描述

四、Request 请求转发

在这里插入图片描述
在这里插入图片描述
demo5

package com.itheima.web.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.nio.charset.StandardCharsets;

/**
 * 请求转发
 */
@WebServlet("/req5")
public class RequestDemo5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo5...");
        System.out.println(request);
        //存储数据
        request.setAttribute("msg","hello");

        //请求转发
        request.getRequestDispatcher("/req6").forward(request,response);

    }

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

demo6

package com.itheima.web.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("/req6")
public class RequestDemo6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo6...");
        System.out.println(request);
        //获取数据
        Object msg = request.getAttribute("msg");
        System.out.println(msg);

    }

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

五、Response 设置相应数据功能介绍

在这里插入图片描述

六、Response 完成重定向

在这里插入图片描述
在这里插入图片描述
ResponseDemo1

package com.itheima.web.response;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("resp1....");

        //重定向
        /*//1.设置响应状态码 302
        response.setStatus(302);
        //2. 设置响应头 Location
        response.setHeader("Location","/request-demo/resp2");*/

        response.sendRedirect(contextPath+"/resp2");
        //response.sendRedirect("https://www.itcast.cn");
    }

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

ResponseDemo2

package com.itheima.web.response;

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("/resp2")
public class ResponseDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("resp2....");
    }

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

路径问题

在这里插入图片描述

package com.itheima.web.response;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("resp1....");

        //重定向
        /*//1.设置响应状态码 302
        response.setStatus(302);
        //2. 设置响应头 Location
        response.setHeader("Location","/request-demo/resp2");*/

        //简化方式完成重定向
        //动态获取虚拟目录
        String contextPath = request.getContextPath();

        response.sendRedirect(contextPath+"/resp2");
        //response.sendRedirect("https://www.itcast.cn");
    }

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

七、Response 响应字符数据

在这里插入图片描述
在这里插入图片描述

package com.itheima.web.response;


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.io.PrintWriter;

/**
 * 响应字符数据:设置字符数据的响应体
 */
@WebServlet("/resp3")
public class ResponseDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //1. 获取字符输出流
        PrintWriter writer = response.getWriter();
        //content-type
        //response.setHeader("content-type","text/html");

        writer.write("你好");
        writer.write("<h1>aaa</h1>");
        //细节:流不需要关闭

    }

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

八、Response 响应字节数据

在这里插入图片描述

package com.itheima.web.response;


import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应字节数据:设置字节数据的响应体
 */
@WebServlet("/resp4")
public class ResponseDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. 读取文件
        FileInputStream fis = new FileInputStream("d://a.jpg");

        //2. 获取response字节输出流
        ServletOutputStream os = response.getOutputStream();

        //3. 完成流的copy
       /* byte[] buff = new byte[1024];
        int len = 0;
        while ((len = fis.read(buff))!= -1){
            os.write(buff,0,len);
        }*/

        IOUtils.copy(fis,os);

        fis.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1524468.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

作品展示ETL

1、ETL 作业定义、作业导入、控件拖拽、执行、监控、稽核、告警、报告导出、定时设定 欧洲某国电信系统数据割接作业定义中文页面&#xff08;作业顶层&#xff0c;可切英文&#xff0c;按F1弹当前页面帮助&#xff09; 涉及文件拆分、文件到mysql、库到库、数据清洗、数据转…

verilog 从入门到看得懂---verilog 的基本语法数据和运算

笔者之前主要是使用c语言和matab 进行编程&#xff0c;从2024年年初开始接触verilog&#xff0c;通过了一周的学习&#xff0c;基本上对verilog 的语法有了基本认知。总统来说&#xff0c;verilog 的语法还是很简单的&#xff0c;主要难点是verilog是并行运行&#xff0c;并且强…

【LabVIEW FPGA入门】插值、输出线性波形

概述 NI 的可重配置 I/O (RIO) 硬件使开发人员能够创建自定义硬件&#xff0c;以在坚固耐用、高性能和模块化架构中执行许多任务&#xff0c;而无需了解低级 EDA 工具或硬件设计。使用 RIO 硬件轻松实现的此类任务之一是模拟波形生成。本教程介绍了使用 CompactRIO 硬件和 LabV…

旧华硕电脑开机非常慢 电脑开机黑屏很久才显示品牌logo导致整体开机速度非常的慢怎么办

前提条件 电池需要20&#xff05;&#xff08;就是电池没有报废&#xff09;且电脑接好电源&#xff0c;千万别断电&#xff0c;电脑会变成砖头的 解决办法 更新bios即可解决&#xff0c;去对应品牌官网下载最新的bios版本就行了 网上都是一些更新驱动啊

VS2019加QT5.14中Please assign a Qt installation in ‘Qt Project Settings‘.问题的解决

第一篇&#xff1a; 原文链接&#xff1a;https://blog.csdn.net/aoxuestudy/article/details/124312629 error:There’ no Qt version assigned to project mdi.vcxproj for configuration release/x64.Please assign a Qt installation in “Qt Project Settings”. 一、分…

数据分析 | Matplotlib

Matplotlib 是 Python 中常用的 2D 绘图库&#xff0c;它能轻松地将数据进行可视化&#xff0c;作出精美的图表。 绘制折线图&#xff1a; import matplotlib.pyplot as plt #时间 x[周一,周二,周三,周四,周五,周六,周日] #能量值 y[61,72,66,79,80,88,85] # 用来设置字体样式…

RunnerGo测试平台的安装和使用

文章适用于想RunnerGo入门的同学&#xff0c;本人主要是后端&#xff0c;这里做一个入门的学习记录。想深入适用RunnerGo的同学可以参考官网文档&#xff1a; https://wiki.runnergo.cn/docs/ 这里我测试的代码是之前搭建的一个前后端分离小demo&#xff0c;代码地址是https:/…

交流互动系统|基于springboot框架+ Mysql+Java+Tomcat的交流互动系统设计与实现(可运行源码+数据库+设计文档)

推荐阅读100套最新项目 最新ssmjava项目文档视频演示可运行源码分享 最新jspjava项目文档视频演示可运行源码分享 最新Spring Boot项目文档视频演示可运行源码分享 2024年56套包含java&#xff0c;ssm&#xff0c;springboot的平台设计与实现项目系统开发资源&#xff08;可…

【UE5】非持枪趴姿移动混合空间

项目资源文末百度网盘自取 创建角色在非持枪状态趴姿移动的动画混合空间 在BlendSpace文件夹中单击右键选择 动画(Animation) 中的混合空间(Blend Space) 选择SK_Female_Skeleton 命名为BS_NormaProne 打开BS_NormaProne 水平轴表示角色的方向&#xff0c;命名为Directi…

腾讯云服务器配置2核4G5M带宽是什么意思?

腾讯云服务器2核4G5M带宽配置是代表什么&#xff1f;代表2核CPU、4G内存、5M公网带宽&#xff0c;这是一款轻量应用服务器&#xff0c;系统盘为60GB SSD云硬盘&#xff0c;活动页面 txybk.com/go/txy 活动打开如下图&#xff1a; 腾讯云2核4G5M服务器 如上图所示&#xff0c;这…

Linux 用户及用户组管理

目录 1——添加用户&#xff08;useradd&#xff09; 2——删除用户&#xff1a;userdel 3——修改用户&#xff1a;usermod 4——记住用户操作&#xff1a;history 5——查看用户信息&#xff1a;id 6——用户切换&#xff1a;su 问题1&#xff1a;遇到当前的用户不能使…

[蓝桥杯 2021 省 A] 左孩子右兄弟

一、问题描述 P8744 [蓝桥杯 2021 省 A] 左孩子右兄弟 二、问题简析 2.1 左孩子右兄弟 首先&#xff0c;我们要了解怎么通过“左孩子右兄弟”表示法将多叉树转化为二叉树&#xff1a;对于一棵多叉树&#xff0c;一个父节点有多个子节点&#xff0c;将第一个子节点作为父节点…

警惕MKP勒索病毒,您需要知道的预防和恢复方法。

引言&#xff1a; 在网络世界中&#xff0c;.mkp勒索病毒是一股威胁不可小觑的黑暗势力。它以其毒辣的加密手段威胁着我们的数据安全。本文将深入介绍.mkp勒索病毒&#xff0c;揭示如何恢复被其加密的数据文件&#xff0c;并分享一些预防措施&#xff0c;助您在数字世界中安全…

Linux:网络相关概念的认识

文章目录 基本认知数据跨网络传输初识ip地址 端口号端口号的理解 本篇是基于前面对于网络的基本框架搭建&#xff0c;进而进行相关概念的进一步理解&#xff0c;为后续准备 基本认知 那么首先总结一下一些基本的相关结论性的信息 对于任何协议来说&#xff0c;它本身都应该拥…

Langchain-chatchat+ChatGlm3-6b部署

我的环境 台式机 内存&#xff1a;16GB 显卡&#xff1a;GTX1060-6G 1. 基础环境准备 1.1. 安装anaconda&#xff0c;创建环境python版本3.11 conda create -n chatglm3 python3.11 conda activate chatglm3 1.2. 搭建cuda环境 # 查看cuda版本&#xff0c;版本是CUDA V…

如何订阅Midjourney

Midjourney介绍 Midjourney作为目前AI绘画领域效果卓越且备受青睐的工具&#xff0c;对于新用户而言&#xff0c;可能无法享受到免费试用的机会。因此&#xff0c;为了持续利用这款软件进行绘画创作&#xff0c;用户需要购买会员资格并开通订阅服务。那么&#xff0c;关于midj…

Redis数据存储的细节

原文章地址 : 深入学习Redis&#xff08;1&#xff09;&#xff1a;Redis内存模型 - 编程迷思 - 博客园 (cnblogs.com) 1.概述 关于Redis数据存储的细节&#xff0c;涉及到内存分配器&#xff08;如jemalloc&#xff09;、简单动态字符串&#xff08;SDS&#xff09;、5种对象…

Python入门(三)

序列 序列是有顺序的数据集合。序列包含的一个数据被称为元素&#xff0c;序列可以由一个或多个元素组成&#xff0c;也是可以没有任何元素的空序列。 序列的类型 元组&#xff08;定值表&#xff09;&#xff1a;一旦建立&#xff0c;各个元素不可再更变&#xff0c;所以一…

建设IAM/IDM统一身份管理,实现系统之间的单点登录(SSO)

企业实施身份管理的现状&#xff1a; 1.身份存储分散&#xff0c;不能统一供应诸多应用系统&#xff0c;企业用户信息常常存在于多个系统&#xff0c;如HR系统有一套用户信息&#xff0c;OA系统也有一套用户信息&#xff0c;身份存储不集中&#xff0c;不能统一地为诸多应用系…

ChatGPT :确定性AI源自于确定性数据

ChatGPT 幻觉 大模型实际应用落地过程中&#xff0c;会遇到幻觉&#xff08;Hallucination&#xff09;问题。对于语言模型而言&#xff0c;当生成的文本语法正确流畅&#xff0c;但不遵循原文&#xff08;Faithfulness&#xff09;&#xff0c;或不符合事实&#xff08;Factua…