栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Restful API实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Restful API实现

Restful API实现

Restful API 风格的API请求与常规请求区别
(1)我们使用的是@RestController这个注解,而不是@Controller,不过这个注解同样不是Spring boot提供的,而是Spring MVC4中的提供的注解,表示一个支持Restful的控制器。

(2)这个类中有三个URL映射是相同的,即都是/restful/{id},这在@Controller标识的类中是不允许出现的。这里的可以通过method来进行区分,produces的作用是表示返回结果的类型是JSON。

(3)@PathVariable这个注解,也是Spring MVC提供的,其作用是表示该变量的值是从访问路径中获取。

Restful API设计

接口URLHTTP方法接口说明
/restfulPOST新增/保存数据
/restful/{id}GET查询数据
/restful/{id}DELETE删除数据
/restful/{id}PUT更新数据

- 注意:

对于RESTful风格的接口,当查询接口需要传入一个或者两个参数的时候,编码起来较为简单,但是当传入3个以上参数的手,要列举出url的所有可能性还是比较复杂的。所以,RESTful风格的接口传入参数比较复杂时,还是尽量使用POST方法比较简便。

具体实现代码如下

@RestController
@RequestMapping("/rest")
public class ArticleRestController {
 
    @Autowired
 private ArticleService articleService;
 
    @RequestMapping(value = "/article", method = POST, produces = "application/json")
    public WebResponse> saveArticle(@RequestBody Article article) {
        article.setUserId(1L);
        articleService.saveArticle(article);
        Map ret = new HashMap<>();
        ret.put("id", article.getId());
        WebResponse> response = WebResponse.getSuccessResponse(ret);
        return response;
    }
 
    @RequestMapping(value = "/article/{id}", method = DELETE, produces = "application/json")
    public WebResponse deleteArticle(@PathVariable Long id) {
        Article article = articleService.getById(id);
        article.setStatus(-1);
        articleService.updateArticle(article);
        WebResponse response = WebResponse.getSuccessResponse(null);
        return response;
    }
 
    @RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")
    public WebResponse updateArticle(@PathVariable Long id, @RequestBody Article article) {
        article.setId(id);
        articleService.updateArticle(article);
        WebResponse response = WebResponse.getSuccessResponse(null);
        return response;
    }
 
    @RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")
    public WebResponse getArticle(@PathVariable Long id) {
        Article article = articleService.getById(id);
        WebResponse response = WebResponse.getSuccessResponse(article);
        return response;
    }
}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号