文章目录
前言
一、Restful是什么?
二、使用步骤
1.Resultful有哪些类型?
2.编写代码
3. 常见的状态码
前言
提示:这里可以添加本文要记录的大概内容:
restful的风格其实是一种规范,用来规范我们在写接口时的命名,用于前端与后端、项目与项目之间来传递数据。restful可以使我们的接口更加简洁、快捷高效、透明。
一、Restful是什么?
为了不同的前端和后端进行信息交互,Resultful API是一种比较流行的一种API规范。结构清晰符合标准,易于理解、扩展方便,便于前端开发者进行区分访问接口资源。
Restfule风格是一种软件架构风格,而不是标准,只是提供了一种设计原则和约束条件。
二、使用步骤
1.Resultful有哪些类型?
Get 获取资源
Put 更新资源
Patch 更新部分属性
Delete 删除资源
Post 创建资源
2.编写代码
这里我只列举出重要的代码,如果有需要全套代码的,可以公众号找我领取
UserController类
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
//注意:参数记得加注解@PathVariable,对象实体类记得加@ModelAttribute,不一样的
/*查询单条*/
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id){
System.out.println(id);
return userService.getUserById(id);
}
/*查询全部*/
@GetMapping
public List<User> getUsers(){
return userService.getUsers();
}
/*新增*/
@PostMapping
public Map insert(@ModelAttribute User user){
userService.insert(user);
return Map.of("code","0000");
}
/*删除*/
@DeleteMapping("/{id}")
public Map delete(@PathVariable Integer id){
userService.delete(id);
return Map.of("code","0000");
}
/*修改*/
@PutMapping("/{id}")
public Map update(@ModelAttribute User user,@PathVariable Integer id){
userService.update(user,id);
return Map.of("code","0000");
}
}
注意:参数记得加注解@PathVariable,对象实体类记得加@ModelAttribute,不一样的
值得注意的是,update因为涉及到原id和被修改后的id,参数有2个,在xml就不需要指明parameterType了,在UserMapper.java里指明注解即可!
UserMapper类
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
void BatchInsert(List<User> list);
int insertSelective(User record);
/* @Select("select * from t_user where id = #{id}")*/
User selectByPrimaryKey(Integer id);
/*@Select("select * from t_user")*/
List<User> selectAll();
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(@Param("record")User record, @Param("id")Integer id);
}
验证结果使用postman
亲测可用,注意如果传对象(新增修改需要用到),需要用Body里form-data属性添加key-value
3. 常见的状态码
200 200 ok 服务器成功返回用户的请求数据 。
201 create 用户创建或修改数据成功
202 Accept有一个请求进入后台排队
204 No Content 删除数据成功
400 用户发送的请求有错误,服务器没有进行新建或修改操作
401用户没有权限 用户名,密码错误
403 用户得到授权,但是访问被禁止
404 用户发出的请求是不存在的记录,服务器没有进行操作
406用户请求的格式不对
410 用户请求的资源被永久删除,不会被诶获得
500 服务器错误,用户无法进行判断是否请求成功
200 系列是成功的,400系列是客户端,500系列是服务端