RESTful ->
增:post
删:delete
改: put
查: get
RESTful 资源路径,一般以 s 复数结尾
以下是代码示例:
package com.example.springboot.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class Hello {
@RequestMapping("/hellos")//设置浏览器访问路径
public String hello(){
System.out.println("完成查询操作");
return "模拟返回查询结果";
}
@RequestMapping(value = "/hellos",method = RequestMethod.POST)
public void post(){
System.out.println("完成新增操作");
}
@RequestMapping(value = "/hellos/{id}",method = RequestMethod.PUT)
public void updateByID(@PathVariable Integer id){
System.out.println("根据id修改记录,当前id为:"+id);
}
@RequestMapping(value = "/hellos/{id}",method = RequestMethod.DELETE)
public void deleteByID(@PathVariable Integer id){
System.out.println("根据id删除记录,当前id为:"+id);
}
}
使用 postman 发送对应请求
四个请求分别是:
get: localhost:8080/hellos
post: localhost:8080/hellos
put: localhost:8080/hellos/1
delete: localhost:8080/hellos/1
四个请求都发送后,运行结果:
2024-09-07T22:22:14.577+08:00 INFO 7396 --- [springboot] [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-09-07T22:22:14.578+08:00 INFO 7396 --- [springboot] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2024-09-07T22:22:14.581+08:00 INFO 7396 --- [springboot] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
完成查询操作
完成新增操作
根据id修改记录,当前id为:1
根据id删除记录,当前id为:1
对应大量重复的注解,我们可以对其进行改造,使其可读性更好
package com.example.springboot.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/hellos")//改造1
public class Hello {
@GetMapping//改造1
public String hello(){
System.out.println("完成查询操作");
return "模拟返回查询结果";
}
@PostMapping//改造2
public void post(){
System.out.println("完成新增操作");
}
@PutMapping("/{id}")//改造3
public void updateByID(@PathVariable Integer id){
System.out.println("根据id修改记录,当前id为:"+id);
}
@DeleteMapping("/{id}")//改造4
public void deleteByID(@PathVariable Integer id){
System.out.println("根据id删除记录,当前id为:"+id);
}
}