使用spring ResponseEntity处理http响应

使用spring ResponseEntity处理http响应
简介
使用spring时,达到同一目的通常有很多方法,对处理http响应也是一样。本文我们学习如何通过ResponseEntity设置http相应内容、状态以及头信息。

ResponseEntity
ResponseEntity标识整个http相应:状态码、头部信息以及相应体内容。因此我们可以使用其对http响应实现完整配置。

如果需要使用ResponseEntity,必须在请求点返回,通常在spring rest中实现。ResponseEntity是通用类型,因此可以使用任意类型作为响应体:

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
1
2
3
4
可以通过编程方式指明响应状态,所以根据不同场景返回不同状态:

@GetMapping("/age")
ResponseEntity<String> 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
2
3
4
5
6
7
8
9
10
11
12
13
14
另外,还可以设置http响应头:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");

    return new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK);
}
1
2
3
4
5
6
7
8
而且, ResponseEntity提供了两个内嵌的构建器接口: HeadersBuilder 和其子接口 BodyBuilder。因此我们能通过ResponseEntity的静态方法直接访问。

最简单的情况是相应包括一个主体及http 200响应码:

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello World!");
}
1
2
3
4
大多数常用的http 响应码,可以通过下面static方法:

BodyBuilder accepted();
BodyBuilder badRequest();
BodyBuilder created(java.net.URI location);
HeadersBuilder<?> noContent();
HeadersBuilder<?> notFound();
BodyBuilder ok();
1
2
3
4
5
6
另外,可以能使用BodyBuilder status(HttpStatus status)和BodyBuilder status(int status) 方法设置http状态。使用ResponseEntity BodyBuilder.body(T body)设置http响应体:

@GetMapping("/age")
ResponseEntity<String> 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
2
3
4
5
6
7
8
9
10
也可以自定义头信息:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");
}
1
2
3
4
5
6
因为BodyBuilder.body()返回ResponseEntity 而不是 BodyBuilder,需要最后调用。注意使用HeaderBuilder 不能设置任何响应体属性。

尽管ResponseEntity非常强大,但不应该过度使用。在一些简单情况下,还有其他方法能满足我们的需求,使代码更整洁。

替代方法
@ResponseBody
典型spring mvc应用,请求点通常返回html页面。有时我们仅需要实际数据,如使用ajax请求。这时我们能通过@ResponseBody注解标记请求处理方法,审批人能够处理方法结果值作为http响应体。

@ResponseStatus
当请求点成功返回,spring提供http 200(ok)相应。如果请求点抛出异常,spring查找异常处理器,由其返回相应的http状态码。对这些方法增加@ResponseStatus注解,spring会返回自定义http状态码。

直接操作相应
Spring 也允许我们直接 javax.servlet.http.HttpServletResponse 对象;只需要申明其作为方法参数:

@GetMapping("/manual")
void manual(HttpServletResponse response) throws IOException {
    response.setHeader("Custom-Header", "foo");
    response.setStatus(200);
    response.getWriter().println("Hello World!");
}
1
2
3
4
5
6
但需要说明,既然spring已经提供底层实现的抽象和附件功能,我们不建议直接操作response。

总结
本文我们介绍了spring提供多种方式处理http响应,以及各自的优缺点,希望对你有帮助。
 

使用ResponseEntity自定义Headers的方法如下: 首先,创建一个HttpHeaders对象来设置自定义的Headers。可以使用add()方法来添加具体的Header键值对。例如,可以使用set()方法来设置一个键值对。 然后,创建一个ResponseEntity对象并将要返回的响应体和自定义的Headers传入。可以使用ok()方法来创建一个成功的ResponseEntity对象。 最后,在Controller方法中,将ResponseEntity对象作为返回值返回即可。 下面是一个示例代: ```java import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping("/customHeaders") public ResponseEntity<String> getResponseWithCustomHeaders() { // 创建自定义的Headers HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "Custom Value"); headers.set("Another-Header", "Another Value"); // 创建ResponseEntity对象并设置自定义Headers ResponseEntity<String> responseEntity = ResponseEntity.ok() .headers(headers) .body("Response Body"); return responseEntity; } } ``` 在上述示例中,通过访问`/customHeaders`路径,将返回一个带有自定义Headers的ResponseEntity对象。其中,自定义Headers包括"Custom-Header"和"Another-Header"两个键值对。 请注意,在使用ResponseEntity时,需要在Controller方法中返回ResponseEntity对象,而不是直接返回响应体内容。通过设置ResponseEntity对象的headers属性来设置自定义Headers。在Spring框架中,可以使用ResponseEntity对象来设置响应头信息。 : 需要注意的是,在使用ResponseEntity时,需要在Controller方法中返回ResponseEntity对象,而不是直接返回响应体内容。 : 在Spring框架中,可以使用ResponseEntity对象来设置响应头信息。可以通过以下代设置响应头:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值