一般访问风格:http://localhost:8080/index?id=1&sex=0
RESTful:http://localhost:8080/index/1/0
使用RESTful常用注解:
- @PathVariable:url中数据注解
- @GetMapping(查),@PostMapping(增),@PutMapping(改),@DeleteMapping(删)
- 创建一个springboot项目, 并创建实体类Student
public class Student {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
- 创建一个Controller测试类
@RestController
public class StudentController {
// 常规请求方式
@RequestMapping("/student")
public Object student(Integer id, Integer age) {
Student student = new Student();
student.setId(id);
student.setAge(age);
return student;
}
// RESTful请求方式
@RequestMapping("/student/detail/{id}/{age}")
public Object student1(@PathVariable("id") Integer id,
@PathVariable("age") Integer age) {
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("age", age);
return map;
}
// RESTful请求方式
@RequestMapping("/student/detail/{id}/{age}")
public Object student2(@PathVariable("id") Integer id,
@PathVariable("status") Integer status) {
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("status", status);
return map;
}
}
以上代码student1和student2会出现请求路径迷糊的错误
通常在RESTful风格中方法的请求方式会按增删改查的请求方式来区分
可以@RequestMapping
l改为@DeleteMapping
RESTful风格中一般不要出现动词