1、RESTful 介绍
RESTful是一种软件架构风格!
REST就是指对同一个URI的资源的不同请求方式(GET,POST,PUT,DELETE)(表述)下的做出的不同的操作(查,增,改,删)
,改变的是资源的状态,即表述性状态转移
。 一个符合REST风格的URI就可以称之一个RESTful的接口
2、RESTful接口设计
示例:
3、RESTful 入门程序
代码示例:
package com.offcn.controller;
import com.offcn.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
// 模拟数据库
// Collections.synchronizedList:实现list线程安全代码(加同步代码块)
private List<User> userList= Collections.synchronizedList(new ArrayList<>());
// 1. 查询用户列表
@GetMapping("/")
public List<User> findAll(){
return userList;
}
// 2. 新增用户
@PostMapping("/")
// @RequestBody 表示请求是一个json格式的数据
public String add(@RequestBody User user){
try {
userList.add(user);
return "add-ok";
} catch (Exception e) {
e.printStackTrace();
return "add-fail";
}
}
// 3. id查询用户
@GetMapping("/{id}")
// @PathVariable(""参数符号)---》用于传递 访问参数
public User findOne(@PathVariable("id") Long id){
for(User user:userList){
// longValue:转化为原始数据类型,可以使用双等号
if(user.getId().longValue()==id.longValue()){
return user;
}
}
return null;
}
// 4. 更新用户
@PutMapping("/{id}")
public String update(@PathVariable("id") Long id,User user){
try {
for (User user1:userList){
if(user1.getId().longValue()==id.longValue()){
user1.setName(user.getName());
user1.setAge(user.getAge());
}
}
return "upadte--ok";
} catch (Exception e) {
e.printStackTrace();
return "update-fail";
}
}
// 5.根据id删除数据
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") Long id){
try {
User user=this.findOne(id);
userList.remove(user);
return "delete-ok";
} catch (Exception e) {
e.printStackTrace();
return "delete-fail";
}
}
}
4、Postman 请求格式使用
1. 普通格式(Params数据传输)
2. json格式(jaon格式数据传输)