ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文使用ResponseEntity实现下载文件的功能
我们进行下载该文件:
文件资源在本章资源可以找到。
我们在首页index.html进行添加如下所示(其他配置可以查看上面一篇文章:写文章-CSDN创作中心):
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <div id="app"> <h1>index.html</h1> <input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br> <input type="button" value="使用@RequestBody注解处理json格式的请求参数" @click="testRequestBody()"><br> <a th:href="@{/test/ResponseBody}">测试@ResponseBody注解响应浏览器数据</a><br> <input type="button" value="使用@ResponseBody注解响应json格式的数据" @click="testResponseBody()"> <a th:href="@{/test/down}">下载图片</a> </div> <script type="text/javascript" th:src="@{/js/vue.js}"></script> <script type="text/javascript" th:src="@{js/axios.min.js}"></script> <script type="text/javascript"> /** * axios({ * url:"", //请求路径 * method:"", //请求方式 * //以name=value&name=value的方式发送的请求参数,不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后 * 此种方式的请求参数可以通过request.getParameter()获取 * params:{}, * //以json格式发送的请求参数,请求参数会被保存到请求报文的请求体传输到服务器。 * 此种方式的请求参数不可以通过request.getParameter()获取 * 需要先来读取请求体中的数据,再通过我们当前的一些处理json的jar包,将我们当前获取的请求体中的数据转换为java对象 * data:{} * //then来处理我们当前请求处理ajax请求处理成功之后服务器响应回来的结果的 * }).then(response=>{ * console.log(response.data); * }); */ var vue=new Vue({ el: "#app", methods: { testAjax() { axios.post( "/SpringMVC/test/ajax?id=1001", {username:"admin",password:"123456"} ).then(response=>{ console.log(response.data); }); }, testRequestBody() { //get请求方式没有请求体。且axios方式有键值对,而post方法直接写参数就可以。 axios.post( "/SpringMVC/test/RequestBody/json", {username:"admin",password:"123456",age:23,gender:"男"} ).then(response=>{ console.log(response.data); }); }, testResponseBody() { //get请求方式没有请求体。且axios方式有键值对,而post方法直接写参数就可以。 axios.post( "/SpringMVC/test/ResponseBody/json" ).then(response=>{ console.log(response.data); }); } } }); </script> </body> </html>
ctrl+p进行查看:
我们在controller层里面进行设置如下所示:
package com.rgf.controller; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import java.io.FileInputStream; import java.io.IOException; /** * ResponseEntity:可以作为控制器方法的返回值,表示响应到浏览器的完整的响应报文 */ @Controller public class FileUpAndDownController { @RequestMapping("/test/down") public void testResponseEntity(HttpSession session) throws IOException{ //获取ServletContext对象