当前位置: 首页 > news >正文

【springmvc】报文信息转换器

HttpMessageConverter

HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文

HttpMessageConverter提供了两个注解和两个类型:
@RequestBody,
@ResponseBody,
RequestEntity,
ResponseEntity

1、@RequestBody

@RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值

<form th:action="@{/testRequestBody}" method="post">用户名:<input type="text" name="username"><br>密码:<input type="password" name="password"><br><input type="submit">
</form>
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){System.out.println("requestBody:"+requestBody);return "success";
}

输出结果:

requestBody:username=admin&password=123456

2、RequestEntity

RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息

@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){System.out.println("requestHeader:"+requestEntity.getHeaders());System.out.println("requestBody:"+requestEntity.getBody());return "success";
}

输出结果:
requestHeader:[host:“localhost:8080”, connection:“keep-alive”, content-length:“27”, cache-control:“max-age=0”, sec-ch-ua:“” Not A;Brand";v=“99”, “Chromium”;v=“90”, “Google Chrome”;v=“90"”, sec-ch-ua-mobile:“?0”, upgrade-insecure-requests:“1”, origin:“http://localhost:8080”, user-agent:“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36”]
requestBody:username=admin&password=123

3、@ResponseBody

原始方式
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XoUhE310-1678072241921)(Pasted%20image%2020220615163138.png)]

@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器

@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){return "hello,success";
}

结果:浏览器页面显示hello,success

4、SpringMVC处理json

@ResponseBody处理json的步骤:

a>导入jackson的依赖

<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.1</version>
</dependency>

b>在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串

<mvc:annotation-driven />

c>在处理器方法上使用@ResponseBody注解进行标识

d>将Java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串

@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){return new User(1001,"admin","123456",23,"男");
}

浏览器的页面中展示的结果:

{“id”:1001,“username”:“admin”,“password”:“123456”,“age”:23,“sex”:“男”}

5、SpringMVC处理ajax

a>请求超链接:

<div id="app"><a th:href="@{/testAjax}" @click="testAjax">testAjax</a><br>
</div>

b>通过vue和axios处理点击事件:

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript">var vue = new Vue({el:"#app",methods:{testAjax:function (event) {axios({method:"post",url:event.target.href,params:{username:"admin",password:"123456"}}).then(function (response) {alert(response.data);});event.preventDefault();}}});
</script>

c>控制器方法:

@RequestMapping("/testAjax")
@ResponseBody
public String testAjax(String username, String password){System.out.println("username:"+username+",password:"+password);return "hello,ajax";
}

6、@RestController注解

@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解

7、ResponseEntity

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

九、文件上传和下载

1、文件下载

使用ResponseEntity实现下载文件的功能

@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {//获取ServletContext对象ServletContext servletContext = session.getServletContext();//获取服务器中文件的真实路径String realPath = servletContext.getRealPath("/static/img/1.jpg");//创建输入流InputStream is = new FileInputStream(realPath);//创建字节数组byte[] bytes = new byte[is.available()];//将流读到字节数组中is.read(bytes);//创建HttpHeaders对象设置响应头信息MultiValueMap<String, String> headers = new HttpHeaders();//设置要下载方式以及下载文件的名字headers.add("Content-Disposition", "attachment;filename=1.jpg");//设置响应状态码HttpStatus statusCode = HttpStatus.OK;//创建ResponseEntity对象ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);//关闭输入流is.close();return responseEntity;
}

2、文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”

SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息

上传步骤:

a>添加依赖:

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version>
</dependency>

b>在SpringMVC的配置文件中添加配置:

<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

c>控制器方法:

@RequestMapping("/testUp")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {//获取上传的文件的文件名String fileName = photo.getOriginalFilename();//处理文件重名问题String hzName = fileName.substring(fileName.lastIndexOf("."));fileName = UUID.randomUUID().toString() + hzName;//获取服务器中photo目录的路径ServletContext servletContext = session.getServletContext();String photoPath = servletContext.getRealPath("photo");File file = new File(photoPath);if(!file.exists()){file.mkdir();}String finalPath = photoPath + File.separator + fileName;//实现上传功能photo.transferTo(new File(finalPath));return "success";
}
<form th:action="@{/upFile}" method="post" enctype="multipart/form-data">  上传文件: <input type="file" name="photo"><br/>  <input type="submit" value="上传">  
</form>
http://www.lryc.cn/news/32375.html

相关文章:

  • 3.5知识点复习
  • 湖南中创教育PMP分享项目经理有哪些优势?
  • LeetCode:27. 移除元素
  • 麻雀算法SSA优化LSTM长短期记忆网络实现分类算法
  • 哈希表题目:数组中的 k-diff 数对
  • SAP ERP系统PP模块计划策略2050详解
  • TIA博途中将硬件目录更改为中文的具体方法演示
  • 【多线程操作】线程池模拟实现
  • HBase---Hbase安装(单机版)
  • 启动项管理工具Autoruns使用实验(20)
  • BFD单臂回声实验详解
  • 详解JAVA类加载器
  • 记录一些常用C标准库函数,以及Linux系统调用函数的作用(不断更新)
  • RK3568平台开发系列讲解(显示篇)DRM的atomic接口
  • 2022年MathorCup数学建模C题自动泊车问题解题全过程文档加程序
  • 【需求响应】基于数据驱动的需求响应优化及预测研究(Matlab代码实现)
  • Bellman-ford和SPFA算法
  • 假如你知道这样的MySQL
  • SpringBoot笔记(一)入门使用
  • C++20 协程体验
  • 这三个小事你做HIGG FEM时要知道
  • .net6 wpf程序一个内存不断增长问题的解决方法
  • NICEGUI---ROS开发之中常用的GUI工具
  • 高盐废水除钙镁的技术解析
  • 回文日期门牌制作
  • 基于半车悬架的轴距预瞄与轴间预瞄仿真对比
  • Linux开发 安装JDK8、p4
  • 基于 x86 SoC 的车辆智能驾驶舱和ADAS设计(一)
  • 类模板函数模板
  • Leetcode DAY 56: 两个字符串的删除操作 and 编辑距离