ResponseEntity:
code:
/*常用*/
@GetMapping("/hello")
public ResponseEntity<String> hello(){
return new ResponseEntity<>("hello word!",HttpStatus.OK);
}
/*设置HTTP头*/
@GetMapping("/hello")
public ResponseEntity<String> hello(){
HttpHeaders headers = new HttpHeaders();
headers.add("content-type","json");
return new ResponseEntity<>("hello word!",headers,HttpStatus.OK);
}
/*设置自定义标头*/
@GetMapping("/hello")
public ResponseEntity<String> hello(){
return ResponseEntity.ok()
.header("content-type","json")
.body("hello world");
}
/*返回对象的Json列表*/
@GetMapping("/hello")
public ResponseEntity<List<Data>> getData(){
return new ResponseEntity<>(Data.findAll(),HttpStatus.FOUND);
}
@ResponseBody:
code:
@ResponseBody
public User show(){
return new User("customer");
}
@ResponseStatus:
code:
/*专注于业务*/
@ResponseStatus(HttpStatus.FOUND)
public User postUser(){
return new User("Customer");
}
本文深入探讨了使用Spring Boot框架中的ResponseEntity、@ResponseBody和@ResponseStatus注解来精细控制HTTP响应的方法。通过实例展示了如何设置HTTP状态码、自定义响应头、返回字符串和对象的JSON列表,以及如何专注于业务逻辑而简化控制器代码。
3587

被折叠的 条评论
为什么被折叠?



