Spring MVC的RESTful风格写法如下:

  1. 使用@RequestMapping注解,指定HTTP请求的方法和路径,例如:
@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable long id) {
        // ...
    }
    
    @PostMapping
    public User createUser(@RequestBody User user) {
        // ...
    }
    
    @PutMapping("/{id}")
    public User updateUser(@PathVariable long id, @RequestBody User user) {
        // ...
    }
    
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable long id) {
        // ...
    }
}
  1. 使用@PathVariable注解获取URL路径中的参数,例如:
@GetMapping("/{id}")
public User getUser(@PathVariable long id) {
    // ...
}
  1. 使用@RequestParam注解获取HTTP请求的查询参数,例如:
@GetMapping
public List<User> getUsers(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int pageSize) {
    // ...
}
  1. 使用@RequestBody注解获取HTTP请求的请求体中的参数,例如:
@PostMapping
public User createUser(@RequestBody User user) {
    // ...
}
  1. 使用@ResponseStatus注解设置HTTP响应的状态码,例如:
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable long id) {
    // ...
}
  1. 使用@ResponseBody注解将返回值转换成HTTP响应体,例如:
@GetMapping("/{id}")
@ResponseBody
public User getUser(@PathVariable long id) {
    // ...
}
  1. 使用@RestController注解组合使用@ResponseBody和@Controller注解,例如:
@RestController
@RequestMapping("/users")
public class UserController {
    // ...
}
``
springmvc restful 风格写法

原文地址: http://www.cveoy.top/t/topic/g0XH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录