前言
Restful规范是为了让接口更直观和更加的符合规范,所有的东西都可以是一种资源。
一、编写代码
RestfulController.java
package com.student.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Create by zjg on 2023/4/27
*/
@RequestMapping("/api/v1/")
@RestController
public class RestfulController {
@GetMapping("sources")
public void getSources(@RequestParam(required = false) Integer pageSize,@RequestParam(required = false) Integer pageNumber){
if(null!=pageSize&&null!=pageNumber){
System.out.println(String.format("根据分页信息pageSize:%s,pageNumber:%s,获取匹配的资源",pageSize,pageNumber));
}
System.out.println("获取所有的资源");
}
@GetMapping("sources/{id}")
public void getSourceById(@PathVariable("id") String id){
System.out.println(String.format("获取id为%s的资源",id));
}
@PostMapping("sources/{id}")
public void postSourceById(@PathVariable("id") String id){
System.out.println(String.format("新增id为%s的资源",id));
}
@PutMapping("sources/{id}")
public void putSourceById(@PathVariable("id") String id){
System.out.println(String.format("更新id为%s的资源",id));
}
@DeleteMapping("sources/{id}")
public void deleteSourceById(@PathVariable("id") String id){
System.out.println(String.format("删除id为%s的资源",id));
}
}
二、测试
三、状态码
响应码 | 响应描述 |
---|---|
200 | 请求成功 |
201 | 资源已创建 |
204 | 请求成功,但无返回内容 |
304 | 缓存有效 |
400 | 语义有误,当前请求无法被服务器理解,请求参数错误 |
401 | 当前请求需要用户认证 |
403 | 用户已认证,但权限不足 |
404 | 请求源未在服务器上被发现 |
405 | 请求方法不能被用于请求相应的资源 |
500 | 服务端内部错误 |
502 | 网关错误 |
504 | 网关超时 |
总结
v1代表版本号,升级可另起一个Controller重写接口,能通过url完成不同版本之间的接口访问。
回到顶部