RESTful开发风格

1.REST与RESTful
  • REST-表现层状态转换,资源在网络中以某种表现形式进行
  • RESTful是基于REST理念的一套开发风格,是具体的开发规则
2.RESTful开发规范
  • 使用URL作为用户交互入口
  • 明确的语义规范(GET|POST|PUT|DELETE)
  • 只返回数据(JSON|XML)不包含任何展现
3.RESTful命名要求
URL说明修改建议
GET /articles?au=lily正确用法
GET /a/1URL必须具有语义GET /student/1
POST /createArticle/1URL必须使用名词POST /article/1
GET /articles/author/1URL扁平化,不超两级GET /articles/author?id=1
DELETE /articles/1URL名词区分单复数GET /articles?au=lily
DELETE /article/1
4.RESTful实验室
package com.learn.restful.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/restful")
public class RestfulController {
    @GetMapping("/request")
    @ResponseBody
    public String doGetRequest(){
        return "{\"message\":\"返回查询结果\"}";
    }

    @PostMapping("/request")
    @ResponseBody
    public String doPostRequest(){
        return "{\"message\":\"数据新建成功\"}";
    }

    @PutMapping("/request")
    @ResponseBody
    public String doPutRequest(){
        return "{\"message\":\"数据更新成功\"}";
    }

    @DeleteMapping("/request")
    @ResponseBody
    public String doDeleteRequest(){
        return "{\"message\":\"数据删除成功\"}";
    }
}
5.RestController注解
  • @RestController 注解 - 默认当前方法返回的都是需要返回数据,而非页面的跳转
    • 优势,不用写@ResponseBody,用于简化开发
6.路径变量
  • 存放在URI中可变的数值叫路径变量
    • 路径变量形如 - /request/{rid}
 // POST /article/1
    // POST /restful/request/100
    @PostMapping("/request/{rid}")
    public String doPostRequest(@PathVariable("rid") Integer requestId){
        return "{\"message\":\"数据新建成功\",\"id\":" + requestId + "}";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值