学习下spring的包org.springframework.http工作中常用的类
ContentDisposition
它提供了表示 HTTP 协议中的 Content-Disposition 报头的方法。 Content-Disposition 报头是指示客户端如何处理响应正文的头文件,例如是否直接显示正文,还是下载到本地文件的头文件。
直接用EasyExcel举例下载excel文件,主要是展示ContentDisposition的用法
@RequestMapping("/springframework/http")
@RestController
public class SpringFrameWorkHttpController {
@GetMapping("/download/excel")//http://localhost:8080/springframework/http/download/excel
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
String fileName = URLEncoder.encode("测试.xlsx", "UTF-8").replaceAll("\\+", "%20");
// builder方法就是帮助我们创建一个ContentDisposition 源码挺简单的,就不介绍了,并且toString就是我们想要生成的字符串
ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
.filename(fileName, StandardCharsets.UTF_8).build();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,contentDisposition.toString());
// 一般都是从数据库查数据让后生成excel进行下载
EasyExcel.write(response.getOutputStream(), EasyExcelUtil.DemoData.class)
.sheet("test").doWrite(EasyExcelUtil.getData());
}
}
工具类
public class EasyExcelUtil {
public static List<DemoData> getData() {
List<DemoData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setString("字符串" + i);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
@Getter
@Setter
@EqualsAndHashCode
public static class DemoData {
private String string;
private Date date;
private Double doubleData;
}
}
HttpEntity
向前端返回的类型,作为HTTP响应的实体,响应的内容是body,比如下面这个响应的是Hello asdasd World,responseHeaders是响应头
@GetMapping("/httentity")
public HttpEntity<String>httpEntity(){
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new HttpEntity<String>("Hello asdasd World", responseHeaders);
}
ResponseEntity
封装一个响应实体,ApiResponse是一个返回对象,它是返回体,第二个参数是响应状态码。这个一般工作中用做全局处理异常,控制项目中的各个异常处理
对比HttpEntity他没有返回前端的状态码,一般要想返回状态码用这个
@GetMapping("/responseEntity")
public ResponseEntity<ApiResponse>responseEntity(){
return new ResponseEntity<>(ApiResponse.create(200,"this is message"),HttpStatus.OK);
}
返回结果:
{
"code": 200,
"ts": 1684571122219,
"data": null,
"msg": "this is message"
}
持续更新~