概念

request:获取请求数据

response:设置响应数据

Request

request继承体系

ServletRequest——Java提供的请求对象根接口

HttpServletRequest——Java提供的对http协议封装的请求对象接口

RequestFacade——tomcat实现定义类

request获取数据

package com.itheijma.web;

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.BufferedReader;
import java.io.IOException; @WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//String method() 获取请求方式
String method = req.getMethod();
System.out.println(method);
//String getContextPath() 获取虚拟目录(项目访问路径)
String contextPath = req.getContextPath();
System.out.println(contextPath);
//StringBuffer getRequestURL() 获取URL(统一资源定位符)
StringBuffer url = req.getRequestURL();
System.out.println(url.toString());
//String getRequestURI() 获取URI(统一资源标识符)
String uri = req.getRequestURI();
System.out.println(uri);
//String getQueryString() 获取请求参数(get方式)
String queryString = req.getQueryString();
System.out.println(queryString); //------------
//获取请求头
String agent = req.getHeader("user-agent");
System.out.println(agent);
} @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); }
}

request通用的方式获取数据

package com.itheijma.web;

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.util.Map; @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
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
// 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); }
}

request请求参数中文乱码解决方法

package com.itheijma.web;

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("/req3")
public class RequestDemo3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} 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); }
}

request请求转发

请求转发(forward):一种在服务器内部的资源跳转方式。

请求转发特点:

  1. 浏览器地址栏路径不发生变化
  2. 只能转发到当前服务器的内部资源
  3. 一次请求,可以在转发的资源间使用request共享数据

    req4
package com.itheijma.web;

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("/req4")
public class RequestDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo4"); //存储数据
request.setAttribute("msg","hello"); //请求转发
request.getRequestDispatcher("/req5").forward(request,response);
}
}

req5

package com.itheijma.web;

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("/req5")
public class RequestDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo5"); //获取数据
Object msg = request.getAttribute("msg");
System.out.println(msg);
}
}

response

Response完成重定向

重定向:一种资源跳转的方式

resp1

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("/resp1")
public class ResponseDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp1..."); // // 重定向
// // 1. 设置状态码 302
// response.setStatus(302);
// // 2. 设置响应头 Location
// response.setHeader("Location","/tomcat-demo2/resp2"); // 简化方式完成重定向
response.sendRedirect("/tomcat-demo2/resp2"); }
}

resp2

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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp2...");
}
}

重定向特点:

  1. 浏览器地址栏路径发生变化
  2. 可以重定向到任意位置的资源(服务器内、外部均可)
  3. 两次请求,不能在多个资源使用request共享数据

资源路径问题(什么时候加虚拟目录)

浏览器使用:需要加虚拟目录

服务端使用:不需要加虚拟目录

动态获取虚拟目录

        //动态获取虚拟目录
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/resp2");

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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取字符输出流
PrintWriter writer = response.getWriter();
//content-type
//response.setHeader("content-type","text/html");
writer.write("你好");
writer.write("<h1>aaa</h1>"); //细节:流不需要关闭
}
}

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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 读取文件
FileInputStream fis = new FileInputStream("e://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();
}
}

pom文件导入工具类

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

一篇博客上手request和response的更多相关文章

  1. 撰写一篇博客要求讲述四则运算2的设计思想,源程序代码、运行结果截图、编程总结分析,并按照PSP0级的要求记录开发过程中的时间记录日志。

    一.撰写一篇博客要求讲述四则运算2的设计思想,源程序代码.运行结果截图.编程总结分析,并按照PSP0级的要求记录开发过程中的时间记录日志. 1.设计思想: ①创建test.jsp建立第一个前端界面,提 ...

  2. 鸿蒙内核源码分析(构建工具篇) | 顺瓜摸藤调试鸿蒙构建过程 | 百篇博客分析OpenHarmony源码 | v59.01

    百篇博客系列篇.本篇为: v59.xx 鸿蒙内核源码分析(构建工具篇) | 顺瓜摸藤调试鸿蒙构建过程 | 51.c.h.o 编译构建相关篇为: v50.xx 鸿蒙内核源码分析(编译环境篇) | 编译鸿 ...

  3. 鸿蒙内核源码分析(异常接管篇) | 社会很单纯 , 复杂的是人 | 百篇博客分析OpenHarmony源码 | v39.03

    百篇博客系列篇.本篇为: v39.xx 鸿蒙内核源码分析(异常接管篇) | 社会很单纯,复杂的是人 | 51.c.h .o 硬件架构相关篇为: v22.xx 鸿蒙内核源码分析(汇编基础篇) | CPU ...

  4. 鸿蒙内核源码分析(源码注释篇) | 鸿蒙必定成功,也必然成功 | 百篇博客分析OpenHarmony源码 | v13.02

    百篇博客系列篇.本篇为: v13.xx 鸿蒙内核源码分析(源码注释篇) | 鸿蒙必定成功,也必然成功 | 51.c.h .o 几点说明 kernel_liteos_a_note | 中文注解鸿蒙内核 ...

  5. 第一篇博客:Hello World

    2016年10月10日,双十,好日子,决定开始写第一篇博客,标题想了会,就叫Hello World 吧,哈哈^_^. 首先感谢博客园的管理们能批准我的申请,记得在14年的时候申请过一次,竟然没申请通过 ...

  6. 通通的最后一篇博客(附自制html5平面射击小游戏一枚)

    这是我最后一篇博客了,由于本人的人生规划吧,以后应该也写不出什么好的技术文章了,到现在在博客园写了2年, 今天一看,我也有了120个粉丝,好几万的浏览量,感谢大家的支持啊~~ 半年没有写博客了,由于半 ...

  7. 我的第一篇博客 ——【ToDoList】小程序开发

    我是一只即将大四的大三狗,这是我的第一篇博客,说来惭愧.今年1月份,学校放寒假的时候开始自学的IOS,放假的时候比较起劲,看了一堆Object-C的视频,然后照着中英文对照的IOS基础开发教程,做了两 ...

  8. Hello World -- 第一篇博客

    今年注定是不寻常的一年,因为技术,接触了许多大牛.通过一篇篇博文,看到了大牛们勤奋好学.孜孜不倦的精神,于是决定也开个博客,向大牛学习. 博客开了,写点什么呢?奈何肚子里墨水不多,吐出来也多是白沫,不 ...

  9. 第一篇博客 ---- 分享关于Maven使用的一些技巧

    Maven环境搭建 在官网上下载maven安装包,地址:http://maven.apache.org/download.cgi . 解压文件到电脑坐在盘符目录,如E:\apache-maven-3. ...

  10. 关于” 记一次logback传输日志到logstash根据自定义设置动态创建ElasticSearch索引” 这篇博客相关的优化采坑记录

    之前写过一篇博客是关于记录日志的简单方式的   主要就是  应用->redis->logstash->elasticsearch 整个流程的配置方法和过程的 虽然我们部分线上应用使用 ...

随机推荐

  1. NodeJS - XSS-Attribute

    参考:https://owasp-skf.gitbook.io/asvs-write-ups/cross-site-scripting-attribute-xss-attribute/kbid-3-x ...

  2. Connect to D365 CE with multi-factor Authentication using C# sharp

    Effective Feb 4, 2020 - Use of the WS-Trust (Web-Service Trust) authentication security protocol whi ...

  3. scaled logy

    library(ggplot2) set.seed(1) vals1 <- rbeta(1000, 0.5, 0.1) vals2 <- rbeta(1000, 0.25, 0.3) gg ...

  4. F. K-th Power 容斥,莫比乌斯

    F. K-th Power 传送门: 牛客:https://ac.nowcoder.com/acm/contest/34866/F cf:https://codeforces.com/group/5z ...

  5. MySql 入门——日期计算

    MySQL自带的日期函数TIMESTAMPDIFF计算两个日期相差的秒数.分钟数.小时数.天数.周数.季度数.月数.年数,当前日期增加或者减少一天.一周等等 SELECT TIMESTAMPDIFF( ...

  6. Go_day07

    Go常用包 包的本质:创建不同的文件夹,来存放程序文件 Go语言的源码复用建立再包package基础之上 main包 Go语言的入口 main()函数所在的包必须是main包 main包需要引用代码, ...

  7. Spring--AOP通知类型

    AOP通知类型 前置通知 通知类中的数据在原始数据的前面 后置通知 通知类中的数据在原始数据的后面 环绕通知 若是只是加一个注解: 我们需要这样做:加一个参数: 若是面对有返回值的方法,又有一点不同之 ...

  8. 计算机网络中各种报文、HEADER的读法

    计算机里到处都是格式,规范.比如<操作系统真象还原>里提到的"魔数" 直接出现的一个数字,只要其意义不明确,感觉很诡异,就称之为魔数. 拿elf文件头举例 ELF He ...

  9. 一文学会Flex布局

    参考: <CSS权威指南>(第四版) flex布局教程-语法篇-阮一峰 1.Flex布局是什么 FlexBox,弹性盒布局,顾名思义,就是元素具有弹性,能根据可用空间大小增减尺寸. 2.基 ...

  10. 从源码彻底理解 Prometheus/VictoriaMetrics 中的 relabel_configs/metric_relabel_configs 配置

    背景 最近接手维护了公司的指标监控系统,之后踩到坑就没站起来过.. 本次问题的起因是我们配置了一些指标的删除策略没有生效: - action: drop_metrics regex: "^e ...