关于 Spring 中带的这个类 ResponseEntity 类的使用,这个类可以改变响应的 HTTP status code,无需使用 HttpServletResponse 这么麻烦。
package com.example.demo.rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 关于 Spring 中带的这个类 ResponseEntity 类的使用
*
*/
@RestController
@Slf4j
public class DemoController {
@GetMapping("/demo/test1")
public ResponseEntity<String> test1() {
ResponseEntity<String> responseEntity = new ResponseEntity<>("fuck", HttpStatus.OK);
return responseEntity;
}
@GetMapping("/demo/test2")
public ResponseEntity<String> test2() {
return ResponseEntity.ok("this is response body");
}
@GetMapping("/demo/test3")
public ResponseEntity<String> test3() {
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("my body msg:NOT_FOUND");
// return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("my body msg:TOO_MANY_REQUESTS");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("my body msg:INTERNAL_SERVER_ERROR");
}
@GetMapping("/demo/test4")
public ResponseEntity<String> test4() {
// 可以乱写,自定义一些 HTTP status code
return ResponseEntity.status(999888).body("");
}
@GetMapping("/demo/test5")
public ResponseEntity<Void> test5() {
return new ResponseEntity<>(HttpStatus.OK);
}
}