SpringMVC 06 -RESTFul风格接口设计

1 REST开发风格

Representational State Transfer简称:REST 直接翻译:表现层状态转移

是一种开发风格,遵从此风格开发软件,符合REST风格,则RESTFUL。

RESTful架构:

  • 每一个URI代表一种资源
  • 客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层状态转化"

1.1 路径

访问标识资源
http://localhost:8989/xxx/users所有用户
http://localhost:8989/xxx/users/1用户1
http://localhost:8989/xxx/users/1/orders用户1的所有订单

1.2 HTTP动词

  • GET(SELECT):从服务器取出资源(一项或多项)。
  • POST(CREATE):在服务器新建一个资源。
  • PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
  • PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
  • DELETE(DELETE):从服务器删除资源。
请求方式标识意图
GEThttp://localhost:8989/xxx/users查询所有用户
POSThttp://localhost:8989/xxx/users在所有用户中增加一个
PUThttp://localhost:8989/xxx/users在所有用户中修改一个
DELETEhttp://localhost:8989/xxx/users/1删除用户1
GEThttp://localhost:8989/xxx/users/1查询用户1
GEThttp://localhost:8989/xxx/users/1/orders查询用户1的所有订单
POSThttp://localhost:8989/xxx/users/1/orders在用户1的所有订单中增加一个

1.3 过滤信息

  • ?limit=10:指定返回记录的数量
  • ?offset=10:指定返回记录的开始位置。
  • ?page=2&limit=100:指定第几页,以及每页的记录数。
  • ?sortby=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序。
  • ?animal_type_id=1:指定筛选条件

1.4 返回结果

  • GET /collection:返回资源对象的列表(数组)
  • GET /collection/resource:返回单个资源对象
  • POST /collection:返回新生成的资源对象
  • PUT /collection/resource:返回完整的资源对象
  • PATCH /collection/resource:返回完整的资源对象
  • DELETE /collection/resource:返回一个空文档

2 定义Rest风格的 Controller

@RequestMapping(value = “/users”,method = RequestMethod.GET)

等价

@GetMapping(“/users”)

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping
    public DataResult getAll(Integer pageNum,Integer limit){
        System.out.println("查询所有user"+"...."+pageNum+"..."+limit);
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            userList.add(new User("张三"+i,"123","1234"+i,30+i));
        }
        return new DataResult(200,"查询成功",userList);
    }
    @GetMapping("/{id}")
    public DataResult getOne(@PathVariable Integer id){
        User user = new User("张三","123","1234",30);
        System.out.println("查询指定id");
        return new DataResult(200,"查询成功",user);
    }

    @PostMapping
    public DataResult addUser(@RequestBody User user){
        System.out.println("增加..."+user);
        return new DataResult(200,"添加成功");
    }

    @DeleteMapping("/{id}")
    public DataResult deleteUser(@PathVariable Integer id){
        System.out.println("删除"+id);
        return new DataResult(200,"删除成功");
    }
    @PutMapping("/{id}")
    public DataResult updateUser(@RequestBody User user){
        System.out.println("修改..."+user.getId());
        System.out.println(user);
        return new DataResult(200,"修改成功");
    }
}

3 前端使用Ajax请求实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--  引入jQuery库  -->
    <script src="/js/jquery-3.4.1.min.js"></script>
</head>
<body>
    <button onclick="sendGet()">GET请求</button>
    <button onclick="sendGetByID()">GET请求指定id</button>
    <button onclick="sendPOST()">POST请求</button>
    <button onclick="sendPUT()">PUT请求</button>
    <button onclick="sendDELETE()">DELETE请求</button>
    <script>
        function sendGet(){
            $.ajax({
                url:'/users',
                data:{
                    pageNum:3,
                    limit:10
                },
                method:"GET",
                hello:function(res){
                    console.log(res);
                }
            })
        }
        function sendGetByID(){
            var id = 10;
            $.ajax({
                url:`/users/${id}`,
                method:"GET",
                hello:function(res){
                    console.log(res);
                }
            })
        }
        function sendPOST(){
            var user = {username:"张三",password:"123",phoneNum:"110001",age:30};
            $.ajax({
                url:`/users`,
                method:"POST",
                data:JSON.stringify(user),
                contentType:"application/json",
                hello:function(res){
                    console.log(res);
                }
            })
        }

        function sendPUT(){
            var user = {username:"张三123",password:"456",phoneNum:"111101",age:20};
            var id = 100;
            $.ajax({
                url:`/users/${id}`,
                method:"PUT",
                data:JSON.stringify(user),
                contentType:"application/json",
                hello:function(res){
                    console.log(res);
                }
            })
        }
        function sendDELETE(){
            var id = 100;
            $.ajax({
                url:`/users/${id}`,
                method:"DELETE",
                hello:function(res){
                    console.log(res);
                }
            })
        }
    </script>
</body>
</html>

向后端提交数据必须设置请求类型为 contentType:"application/json"

4 配置put请求过滤器(可省)

如果是低版本的SpringMVC(5.1之前),是不支持PUT、DELETE请求的,需要配置过滤器,当前版本无需配置

HttpPutFormContentFilter过滤器配置

<filter>
    <filter-name>httpPutFormContentFilter</filter-name>
    <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>httpPutFormContentFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

5 前端使用表单实现Put和delete

表单默认只支持GET、POST请求,如果使用其他的请求方式,那么都会默认当做是GET请求

配置HiddenHttpMethodFilter过滤器实现Put和delete请求

<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

前端表单中有两个要求:

  • 请求方式必须为post:method="post"

  • 在表单中添加隐藏域:name="_method" value="delete|put"

<form action="请求路径" method="post">
    <input type="hidden" name="_method" value="delete">
    <!--其他表单提交信息....-->
    <input type="submit" value="测试put和delete">
</form>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yinying293

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

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

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

打赏作者

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

抵扣说明:

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

余额充值