栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring-Boot-20-ResponseEntity

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring-Boot-20-ResponseEntity

Spring ResponseEntity
  1. ResponseEntity处理http响应
1. ResponseEntity
  1. 标识了整个http响应:状态码、头部信息以及相应体内容
  2. 如果要使用ReponseEntity,必须在请求点返回,通常在spring rest中实现。
1.1. 内嵌接口
  1. HeadersBuilder:不能设置任何响应体属性
  2. BodyBuilder(是上面的子接口)
@GetMapping("/hello")
ResponseEntity hello() {
    return ResponseEntity.ok("Hello World!");
}
1.2. 常见相应响应
  1. BodyBuilder accepted();
  2. BodyBuilder badRequest();
  3. BodyBuilder created(java.net.URI location);
  4. HeadersBuilder noContent();
  5. HeadersBuilder notFound();
  6. BodyBuilder ok();
  7. BodyBuilder status(HttpStatus status)
  8. BodyBuilder status(int status)
1.2.1. status()的使用
@GetMapping("/age")
ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) {
    if (isInFuture(yearOfBirth)) {
        return ResponseEntity.badRequest()
            .body("Year of birth cannot be in the future");
    }

    return ResponseEntity.status(HttpStatus.OK)
        .body("Your age is " + calculateAge(yearOfBirth));
}
1.3. 简单使用
@GetMapping("/age")
ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) {
    if (isInFuture(yearOfBirth)) {
        return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK);
}
1.4. 设置Http响应头
//方式一
@GetMapping("/customHeader")
ResponseEntity customHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");
    return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK);
}
//方式二
@GetMapping("/customHeader")
ResponseEntity customHeader() {
    return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");
}
  1. .body()返回的是ResponseEntity,而并不是BodyBuilder,需要在最后进行调用。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/886086.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号