参考文档
ResponseEntity和@ResponseBody以及@ResponseStatus区别:https://www.jdon.com/springboot/responseentity.html
常用构造方法
构造方法-1
public ResponseEntity(HttpStatus status) { this((Object)null, (MultiValueMap)null, (HttpStatus)status); }
使用示例
@RequestMapping("/hello")
public ResponseEntity<String> jsonDemo1(String name) throws IOException {
return new ResponseEntity<>(HttpStatus.OK);
}
构造方法-2
接收一个泛型参数和HttpStatus参数,直接返回信息
public ResponseEntity(@Nullable T body, HttpStatus status) { this(body, (MultiValueMap)null, (HttpStatus)status); }
使用示例
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
构造方法-3
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) { this((Object)null, headers, (HttpStatus)status); }
使用示例
@RequestMapping("/hello")
public ResponseEntity<String> jsonDemo1(String name) throws IOException {
HttpHeaders headers = new HttpHeaders();
// 添加一个自定义的head头Custom-Header
headers.add("Custom-Header", "foo");
return new ResponseEntity<>(headers, HttpStatus.OK);
}
构造方法-4
接收一个泛型参数、head头、HttpStatus参数,直接返回信息
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) { super(body, headers); Assert.notNull(status, "HttpStatus must not be null"); this.status = status; }
使用示例
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
// 添加一个自定义的head头Custom-Header
headers.add("Custom-Header", "foo");
return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK);
}
构造方法-5(同构造方法-4)
private ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, Object status) { super(body, headers); Assert.notNull(status, "HttpStatus must not be null"); this.status = status; }
常用链式调用
@RequestMapping("/hello")
public ResponseEntity<String> jsonDemo1(String name) throws IOException {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set");
}