RESTful Web 服务是一种基于 Representational State Transfer (REST) 架构风格的 Web 服务,它利用 HTTP 协议来传输数据,支持多种数据格式如 JSON 和 XML。在 Spring 框架中,通过简单配置和注解可以轻松实现 RESTful Web 服务。在本文中,我们将介绍如何创建 RESTful 控制器,使用 @RestController 注解,处理请求和响应格式,以及处理异常的最佳实践。
创建 RESTful 控制器
RESTful 控制器用于处理 HTTP 请求并返回相应的数据。Spring 提供了一套完整的注解和工具来帮助开发者快速创建 RESTful 控制器。
使用 @RestController 注解
@RestController 注解是 Spring 提供的一个方便的注解,它结合了 @Controller 和 @ResponseBody,简化了控制器的开发。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List<User> getAllUsers() {
// 返回所有用户
return userService.findAll();
}
@PostMapping
public User createUser(@RequestBody User user) {
// 创建并返回新用户
return userService.save(user);

最低0.47元/天 解锁文章
692

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



