Restful API实现

本文详细介绍了Restful API的实现方式,包括使用@RestController注解、@PathVariable和HTTP方法来区分不同操作。同时,展示了如何通过POST、GET、PUT和DELETE方法实现增删改查功能。对于RESTful接口的设计,当参数较多时,推荐使用POST方法以简化URL。代码示例中展示了如何在SpringMVC中实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<Map<String, Object>> saveArticle(@RequestBody Article article) {
        article.setUserId(1L);
        articleService.saveArticle(article);
        Map<String, Object> ret = new HashMap<>();
        ret.put("id", article.getId());
        WebResponse<Map<String, Object>> 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<Object> response = WebResponse.getSuccessResponse(null);
        return response;
    }
 
    @RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")
    public WebResponse<Object> updateArticle(@PathVariable Long id, @RequestBody Article article) {
        article.setId(id);
        articleService.updateArticle(article);
        WebResponse<Object> response = WebResponse.getSuccessResponse(null);
        return response;
    }
 
    @RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")
    public WebResponse<Article> getArticle(@PathVariable Long id) {
        Article article = articleService.getById(id);
        WebResponse<Article> response = WebResponse.getSuccessResponse(article);
        return response;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五颜六色的bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值