个人博客
什么是RESTful
风格?
- 通过URL进行资源的定位,用HTTP动作(
GET、POST、DELETE、PUSH
)描述操作,完成功能。 - 遵循
RESTful
风格,可以使开发的接口通用性更好,统一规范,减少沟通、学习和开发的成本。
1、HTTP方法与CRUD动作的映射
动作 | 普通CRUD的URL | Restful的URL | Restful对应的HTTP方法 |
---|
查询 | Article?id=1 | Article/{id} | GET |
添加 | Article?title=xxx&body=xxx | Article | POST |
修改 | Article/update?id=1 | Article/{id} | PUT/PATCH |
删除 | Article/delete?id=1 | Article/{id} | DELETE |
其中PUT
和PATCH
比较相似,都是做更新操作。PUT
一般用于全部修改进行替换操作,PATCH
用于更新部分字段(资源)操作。
2、RESTful API
2.1、查询列表
1 2 3 4 5
| @RequestMapping(value = "/ArticleList", method = RequestMethod.GET) public List<Article> getArticleList() { List<Article> articleList = articleRepository.findAll(); return articleList; }
|
2.2、增加内容
1 2 3 4 5
| @RequestMapping(value = "/Article", method = RequestMethod.POST) public String addArticle(Article article) { articleRepository.save(article); return "success"; }
|
2.3、删除内容
1 2 3 4 5
| @RequestMapping(value = "/Article/{id}", method = RequestMethod.DELETE) public String deleteArticle(@PathVariable("id") long id) { articleRepository.deleteById(id); return "success"; }
|
2.4、修改内容
1 2 3 4 5
| @RequestMapping(value = "/Article/{id}", method = RequestMethod.PUT) public String updateArticle(Article model) { articleRepository.save(model); return "success"; }
|
2.5、查询内容
1 2 3 4 5
| @RequestMapping(value = "/Article/{id}", method = RequestMethod.GET) public Article findArticle(@PathVariable("id") long id) { Article article = articleRepository.findById(id); return article; }
|