📅  最后修改于: 2023-12-03 15:01:31.994000             🧑  作者: Mango
Java ResponseEntity
is a class used to represent HTTP response entities. It allows programmers to build responses that include both a response body and HTTP headers, as well as the HTTP status code.
To use the ResponseEntity
class, start by creating an instance of the class and specifying the expected response type. Here's an example that returns a plain text response:
@GetMapping(value = "/api/hello")
public ResponseEntity<String> sayHello() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
To return a JSON response, use the ResponseEntity
class along with the @ResponseBody
annotation:
@GetMapping(value = "/api/person/{id}")
@ResponseBody
public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
Person person = personService.getPersonById(id);
if (person == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(person, HttpStatus.OK);
}
To add additional HTTP headers to the response, add them to an instance of the HttpHeaders
class and pass the headers to the ResponseEntity
constructor:
@GetMapping(value = "/api/person/{id}")
@ResponseBody
public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(CacheControl.noCache());
Person person = personService.getPersonById(id);
if (person == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(person, headers, HttpStatus.OK);
}
ResponseEntity
is a powerful tool for building custom HTTP responses in Java, allowing programmers to easily specify the response body, HTTP headers, and status code. Its flexibility makes it a useful tool for any Java-based web application.