SpringBoot-请求方式注解

  主要是在开发过程中,如何区别各种请求类型,还有RESTful风格的了解

1.注解

1.1 @RestController

  相当于控制层类加上@Controller+方法上加@ResponseBody ,意味着当前控制层类中所有方法返还的都是JSON对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//@Controller
//相当于控制层类加上@Controller+方法上加@ResponseBody
//意味着当前控制层类中所有方法返还的都是JSON对象
@RestController
public class StudentController {

@RequestMapping(value = "/student")
// @ResponseBody
public Object student() {
Student student = new Student();
student.setName("zhangsan");
student.setId(1011);
return student;
}
}

1.2 @GetMapping查

1
2
3
4
5
//    查询数据使用
@GetMapping(value = "/queryStudentById2")
public Object queryStudentById2(){
return "Only GET Method";
}

1.3 @PostMapping增

1
2
3
4
5
6
@PostMapping(value = "/insert")
// 新增数据使用
// 该注解通常在新增数据的时候使用
public Object insert(){
return "Insert success";
}

1.4 @DeleteMapping删

1
2
3
4
5
@DeleteMapping(value = "/delete")
// 删除数据时候使用
public Object delete(){
return "delete Student";
}

1.5 @PutMapping改

1
2
3
4
5
6
//    @RequestMapping(value = "/update",method = RequestMethod.PUT)
@PutMapping(value = "/update")
// 更改数据时候使用
public Object update(){
return "update student info";
}

2.RESTful风格

localhost:8080/sutdent?id=1001&age=23

可以优化为

localhost:8080/sutdent?/1001/23

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@RestController
public class StudentController {

@RequestMapping(value = "/student/detail/{id}/{age}")
public Object student1(@PathVariable("id") Integer id,
@PathVariable("age") Integer age) {
Map<String, Object> retMap = new HashMap<>();

retMap.put("id", id);
retMap.put("age", age);

return retMap;
}

@RequestMapping(value = "/student/detail/{id}/{status}")
public Object student2(@PathVariable("id") Integer id,
@PathVariable("status") Integer status) {
Map<String, Object> retMap = new HashMap<>();

retMap.put("id", id);
retMap.put("status", status);

return retMap;
}
}
以上代码studen1和studen2出现请求模糊

使用时候需要注意增删改查的请求方式进行区分</font>

  • student1需要加@GetMapping、student2需要加@DeleteMapping

  • 修改请求路径顺序