【SpringMVC】RESTful接口开发

在这里插入图片描述
SpringMVC 除了支持JSON数据交互外,还支持RESTful风格的编程

RESTful概述

Restful(Representational State Transfer)风格的API是一种软件架构风格,是Roy Fielding博士在2000年他的博士论文中提出,之后REST就基本上迅速取代了复杂而笨重的SOAP,成为Web API的标准了。

RESTful架构的主要原则

  • 网络上的所有事物都被抽象为资源

  • 每个资源都有一个唯一的资源标识符

  • 同一个资源具有多种表现形式(xml,json等)

  • 对资源的各种操作不会改变资源标识符

  • 所有的操作都是无状态的

  • 符合REST原则的架构方式即可称为RESTful


      在RESTful接口中,推荐所有的方法都是返回JSON,没有返回页面的(ModelAndView),因此,所有的方法上都需要添加@ResponseBody注解。一个替代的简化方案,是使用 @RestController 代替@Controller@RestController实际上是一个组合注解,是@Controller@ResponseBody的组合:

    扫描二维码关注公众号,回复: 11535762 查看本文章
@Controller
@ResponseBody
@RequestMapping("/json")
public class JSONControl {
 //......
}
@RestController
@RequestMapping("/json")
public class JSONControl {
 //......
}

RESTful接口示例

@RestController
@RequestMapping("/json")
public class JSONControl {
    @Autowired
    UserService userService;

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Integer id) {

        return userService.getUserById(id);
    }
    @DeleteMapping("/user/{id}")
    public void deleteUserById(@PathVariable Integer id) {
        //......
    }

    @PostMapping("/user")
    public void addUser(@RequestBody User user) {
        //......
    }
}

猜你喜欢

转载自blog.csdn.net/huweiliyi/article/details/107812362
今日推荐