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

二、Request 继承体系

三、Request 获取请求数据
1、获取请求数据方法
(1)、请求行

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// String getMethod():获取请求方式: GETString method = req.getMethod();System.out.println(method);//GET// String getContextPath():获取虚拟目录(项目访问路径):/request-demoString contextPath = req.getContextPath();System.out.println(contextPath);// StringBuffer getRequestURL(): 获取URL(统一资源定位符):http://localhost:8080/request-demo/req1StringBuffer url = req.getRequestURL();System.out.println(url.toString());// String getRequestURI():获取URI(统一资源标识符): /request-demo/req1String uri = req.getRequestURI();System.out.println(uri);// String getQueryString():获取请求参数(GET方式): username=zhangsanString 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)、请求体

@Overrideprotected 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 {@Overrideprotected 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 lisiSystem.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);}@Overrideprotected 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 lisiSystem.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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1. 解决乱码:POST,getReader()//request.setCharacterEncoding("UTF-8");//设置字符输入流的编码//2. 获取usernameString 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);}@Overrideprotected 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 {@Overrideprotected 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);}@Overrideprotected 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 {@Overrideprotected 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);}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("resp1....");//重定向/*//1.设置响应状态码 302response.setStatus(302);//2. 设置响应头 Locationresponse.setHeader("Location","/request-demo/resp2");*/response.sendRedirect(contextPath+"/resp2");//response.sendRedirect("https://www.itcast.cn");}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("resp2....");}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("resp1....");//重定向/*//1.设置响应状态码 302response.setStatus(302);//2. 设置响应头 Locationresponse.setHeader("Location","/request-demo/resp2");*///简化方式完成重定向//动态获取虚拟目录String contextPath = request.getContextPath();response.sendRedirect(contextPath+"/resp2");//response.sendRedirect("https://www.itcast.cn");}@Overrideprotected 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 {@Overrideprotected 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>");//细节:流不需要关闭}@Overrideprotected 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 {@Overrideprotected 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();}@Overrideprotected 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>
相关文章:
RequestResponse使用
文章目录 一、Request&Response介绍二、Request 继承体系三、Request 获取请求数据1、获取请求数据方法(1)、请求行(2)、请求头(3)、请求体 2、通过方式获取请求参数3、IDEA模板创建Servlet4、请求参数…...
知名的CDN厂商CloudFlare简介
Cloudflare是一家总部位于美国的跨国科技公司,提供云端安全、性能优化以及内容交付网络(CDN)服务。通过其全球分布的服务器网络,Cloudflare帮助网站提高加载速度、保护免受恶意攻击,并提供安全可靠的云端解决方案。除此…...
C语言程序设计-谭浩强
文章目录 1 C语言2 算法3 顺序程序设计3.1 数据的表示形式3.2 输入和输出 4 选择程序结构5 循环程序结构6 数组7 函数模块化8 指针8.1 动态内存分配 9 结构类型9.1 链表9.2 共用体 union9.3 枚举 enum9.4 typedef 10 对文件的输入输出10.1 顺序读写10.2 随机读写 1 C语言 1.1 …...
将OpenCV与gdb驱动的IDE结合使用
返回:OpenCV系列文章目录(持续更新中......) 上一篇:OpenCV4.9.0开源计算机视觉库在 Linux 中安装 下一篇:将OpenCV与gcc和CMake结合使用 能力 这个漂亮的打印机可以显示元素类型、、标志is_continuous和is_subm…...
Java毕业设计-基于springboot开发的Java时间管理系统-毕业论文+答辩PPT(附源代码+演示视频)
文章目录 前言一、毕设成果演示(源代码在文末)二、毕设摘要展示1、开发说明2、需求分析3、系统功能结构 三、系统实现展示1、管理员功能模块2、用户功能模块 四、毕设内容和源代码获取总结 Java毕业设计-基于springboot开发的Java时间管理系统-毕业论文答…...
AI原生安全 亚信安全首个“人工智能安全实用手册”开放阅览
不断涌现的AI技术新应用和大模型技术革新,让我们感叹从没有像今天这样,离人工智能的未来如此之近。 追逐AI原生?企业组织基于并利用大模型技术探索和开发AI应用的无限可能,迎接生产与业务模式的全面的革新。 我们更应关心AI安全原…...
Vue3 大量赋值导致reactive响应丢失问题
问题阐述 如上图所示,我定义了响应式对象arrreactive({data:[]}),尝试将indexedDB两千条数据一口气赋值给arr.data。但事与愿违,页面上的{{}}在展示先前数组的三秒后变为空。 问题探究 vue3的响应应该与console.log有异曲同工之妙࿰…...
1236 - 二分查找
代码 #include<bits/stdc.h> using namespace std; int a[1100000]; int main() {int n,x,l,r,p,mid,i;cin>>n;for(i1;i<n;i)cin>>a[i];cin>>x;l1;rn;p-1;while(l<r){mid(rl)/2;if(a[mid]x){pmid;break;}else if(x<a[mid]) rmid-1;else if(x…...
CPP容器vector和list,priority_queue定义比较器
#include <iostream> #include <bits/stdc.h> using namespace std; struct VecCmp{bool operator()(int& a,int& b){return a>b;/*** 对于vector和list容器,这里写了>就是从大到小* 对于priority_queue容器,这里写…...
How to install PyAlink on Ubuntu 22.04
How to install PyAlink on Ubuntu 22.04 环境准备准备conda python环境创建项目虚拟环境激活虚拟环境 安装脚本细节 环境准备 准备conda python环境 关于如何安装conda环境,可以参阅我此前整理的如下文章: How to install Miniconda on ubuntu 22.04…...
Java部署运维
1.docker Docker(一):安装、命令、应用Docker(二):数据卷、Dockefile、Docker-composeDocker(三) 通过gitlab部署CICD Docker超详细教程——入门篇实战 Docker教程 2.nginx 3.keepalived 4.k8s 5.jekenis...
0-Flume(1.11.0版本)在Linux(Centos7.9版本)的安装(含Flume的安装包)
环境检查 #首先确认自己的Linux是Centos版本,运行命令 cat /etc/centos-release结果:CentOS Linux release 7.9.2009 (Core) 安装 Flume本身是由Java开发的,所以需要服务器上安装好JDK1.8(注意区分Linux还是Windows系统的JDk&a…...
cad vba 打开excel并弹窗打开指定文件
CAD vba 代码实现打开excel,并通过对话框选择xls文件,并打开此文件进行下一步操作。代码如下: excel.activeworkbook.sheets(1) excel对象下activeworkbook,再往下是sheets对象,(1)为第一个表, thisworkbook是vba代码所在的工作簿。 Opti…...
应急救援装备无人机是否必要?无人机在应急救援中的具体应用案例有哪些?
无人机(Drone)是一种能够飞行并自主控制或远程操控的无人驾驶飞行器。它们通常由航空器、控制系统、通讯链路和电源系统组成,并可以根据任务需求搭载不同类型的传感器、摄像头、货物投放装置等设备。 无人机的种类繁多,从大小、形…...
模态框被div class=modal-backdrop fade in覆盖的问题
模态框被<div class"modal-backdrop fade in">覆盖的问题 起因:在导入模态框时页面被一层灰色的标签覆盖住 F12查看后发现是一个<div class"modal-backdrop fade in"> 一开始以为是z-index的问题,但经过挨个修改后感觉…...
关于msvcp140.dll丢失的解决方法详情介绍,修复dll文件的安全注意事项
在使用电脑的过程中,是否有遇到过关于msvcp140.dll丢失的问题,遇到这样的问题你是怎么解决的,都有哪些msvcp140.dll丢失的解决方法是能够完美解决msvcp140.dll丢失问题的,今天小编将带大家去了解msvcp140.dll文件以及分析完美解决…...
AJAX-Promise
定义 Promise对象用于表示(管理)一个异步操作的最终完成(或失败)及其结果值。 好处:1)成功和失败状态,可以关联对应处理程序 2)了解axios函数内部运作机制 3)能解决回调函数地狱问题 语法&…...
[Spark SQL]Spark SQL读取Kudu,写入Hive
SparkUnit Function:用于获取Spark Session package com.example.unitlimport org.apache.spark.sql.SparkSessionobject SparkUnit {def getLocal(appName: String): SparkSession {SparkSession.builder().appName(appName).master("local[*]").getO…...
python统计分析——t分布、卡方分布、F分布
参考资料:python统计分析【托马斯】 一些常见的连续型分布和正态分布分布关系紧密。 t分布:正态分布的总体中,样本均值的分布。通常用于小样本数且真实的均值/标准差不知道的情况。 卡方分布:用于描述正态分布数据的变异程度。 F分…...
onlyoffice创建excel文档
前提 安装好onlyoffice然后尝试api开发入门 编写代码 <html> <head><meta charset"UTF-8"><meta name"viewport"content"widthdevice-width, user-scalableno, initial-scale1.0, maximum-scale1.0, minimum-scale1.0"&…...
(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)
题目:3442. 奇偶频次间的最大差值 I 思路 :哈希,时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况,哈希表这里用数组即可实现。 C版本: class Solution { public:int maxDifference(string s) {int a[26]…...
linux之kylin系统nginx的安装
一、nginx的作用 1.可做高性能的web服务器 直接处理静态资源(HTML/CSS/图片等),响应速度远超传统服务器类似apache支持高并发连接 2.反向代理服务器 隐藏后端服务器IP地址,提高安全性 3.负载均衡服务器 支持多种策略分发流量…...
ES6从入门到精通:前言
ES6简介 ES6(ECMAScript 2015)是JavaScript语言的重大更新,引入了许多新特性,包括语法糖、新数据类型、模块化支持等,显著提升了开发效率和代码可维护性。 核心知识点概览 变量声明 let 和 const 取代 var…...
使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装
以下是基于 vant-ui(适配 Vue2 版本 )实现截图中照片上传预览、删除功能,并封装成可复用组件的完整代码,包含样式和逻辑实现,可直接在 Vue2 项目中使用: 1. 封装的图片上传组件 ImageUploader.vue <te…...
第25节 Node.js 断言测试
Node.js的assert模块主要用于编写程序的单元测试时使用,通过断言可以提早发现和排查出错误。 稳定性: 5 - 锁定 这个模块可用于应用的单元测试,通过 require(assert) 可以使用这个模块。 assert.fail(actual, expected, message, operator) 使用参数…...
前端开发面试题总结-JavaScript篇(一)
文章目录 JavaScript高频问答一、作用域与闭包1.什么是闭包(Closure)?闭包有什么应用场景和潜在问题?2.解释 JavaScript 的作用域链(Scope Chain) 二、原型与继承3.原型链是什么?如何实现继承&a…...
微信小程序云开发平台MySQL的连接方式
注:微信小程序云开发平台指的是腾讯云开发 先给结论:微信小程序云开发平台的MySQL,无法通过获取数据库连接信息的方式进行连接,连接只能通过云开发的SDK连接,具体要参考官方文档: 为什么? 因为…...
JDK 17 新特性
#JDK 17 新特性 /**************** 文本块 *****************/ python/scala中早就支持,不稀奇 String json “”" { “name”: “Java”, “version”: 17 } “”"; /**************** Switch 语句 -> 表达式 *****************/ 挺好的ÿ…...
大数据学习(132)-HIve数据分析
🍋🍋大数据学习🍋🍋 🔥系列专栏: 👑哲学语录: 用力所能及,改变世界。 💖如果觉得博主的文章还不错的话,请点赞👍收藏⭐️留言Ǵ…...
企业如何增强终端安全?
在数字化转型加速的今天,企业的业务运行越来越依赖于终端设备。从员工的笔记本电脑、智能手机,到工厂里的物联网设备、智能传感器,这些终端构成了企业与外部世界连接的 “神经末梢”。然而,随着远程办公的常态化和设备接入的爆炸式…...
