Open conchincradle opened 1 year ago
当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。
注解@RequestBody用于接收前端传递给后端的、JSON对象的字符串,这些数据位于请求体中,适合处理的数据为非Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据
@PostMapping是一个组合注解,在Spring framework 4.3作为@RequestMapping(method = RequestMethod.POST)的变体引入,它将HTTP Post请求映射到特定的处理方法上。例如,使用@PosttMapping("/testRequestBody")就等价于@RequestMapping(value ="/testRequestBody",method = RequestMethod.POST),显然,这可以精简我们的代码。
ResponseEntity 表示整个HTTP响应:状态代码,标题和正文。 因此,我们可以使用它来完全配置HTTP响应,它是一个对象,而@ResponseBody和@ResponseStatus是注解,适合于简单直接的场合。
@GetMapping
public List<PostDto> getAllPosts(){
return postService.getAllPosts();
}
Response.ok 属性返回一个布尔值,表示请求是否成功, true 对应HTTP 请求的状态码200
Spring MVC用ResponseEntity返回可实现更强大的功能 上面的ResponseEntity.ok已经包含了返回200Http响应码,我们还可以通过ResponseEntity.status(HttpStatus|int)来自定义返回的响应码。
to add new method postService Interface add new method, postServiceImpl implement the method, then write the method in controller to return
@RestController Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。
即@RestController是@ResponseBody和@Controller的组合注解。