使用Spring ResponseEntity处理http响应
简介
使用Spring时,达到同一目的通常有很多方法,对处理http响应也是一样。本文我们将学习如何通过ResponseEntity设置http相应内容、状态以及头信息。
ResponseEntity
ResponspEntity标识整个http相应:状态码、头部信息以及相应体内容。因此我们可以使用其对http响应实现完整配置。
如果需要使用ResponspEntity,必须在请求点返回,通常在spring rest中实现。
ResponspEntity是通用类型,因此可以使用任意类型作为响应体:
@GetMapping("/hello") public ResponseEntity<String> hello(){ return new ResponseEntity<>("hello word!", HttpStatus.OK); }
可以通过编程方式指明响应状态,所以根据不同场景返回不同状态:
@GetMapping("/age") public ResponseEntity<String> age(@RequestParam("yearOfBirth")int yearOfBirth){ if(isInFuture(yearOfBirth)){ return new ResponseEntity<>("",HttpStatus.BAD_REQUEST); } return new ResponseEntity<>("Your age is"+calculateAge(yearOfBirth),HttpStatus.OK); }
另外还可以设置http响应头:
@GetMapping("/customHeader") public ResponseEntity<String> customHeader(){ HttpHeaders headers=new HttpHeaders(); headers.add("Custom-Header","foo"); return new ResponseEntity<>("hello word!", headers,HttpStatus.OK); }
而且,ResponseEntity提供了两个内嵌的构建器接口:HeadersBuilder和其子接口BodyBuilder。因此我们能通过ResponseEntity的静态方法直接访问。
大多数常用的http响应码,可以通过下面static方法:
BodyBuilder accepted(); BodyBuilder badRequest(); BodyBuilder created(java.net.URI location); HeadersBuilder<?> noContent(); HeadersBuilder<?> notFound(); BodyBuilder ok();
另外,可以使用BodyBuilder status(HTTPStatus status)和BodyBuilder status(int status)方法设置http状态。使用ResponseEntity BodyBuilder.body(T body)设置http响应体:
@GetMapping("all") public ResponseEntity<List> All(){ return ResponseEntity.ok().body(userService.findAll()); }
尽管ResponseEntity非常强大,但不应该过度使用。在一些简单情况下,还有其他方法能满足我们的需求,使代码更整洁。
代替方法
@ResponseBody
典型spring mvc应用,请求点通常返回html页面。有时我们仅需要实际数据,如使用ajax请求,这时我们能通过@ResponseBody注解标记请求处理方法,审批人能够处理方法结果值作为http响应体。
@ResponsoStatus
当请求点成功返回,spring提供http 200(ok)响应。如果请求点抛出异常,spring查找异常处理器,由其返回相应的http状态码。对这些方法增加@ResponseStatus注解,spring会返回自定义http状态码。
如果对你有用,记得点赞收藏,关注一波不迷路
使用Spring ResponseEntity处理http响应
原文:https://www.cnblogs.com/alongg/p/13607673.html