get请求:查询
post请求:增加
put请求:修改
delete请求:删除
如下列api的设计:
API设计,Controller:
1 package com.yas.controller; 2 3 import com.yas.entity.User; 4 import org.springframework.web.bind.annotation.*; 5 6 import java.util.Arrays; 7 import java.util.Date; 8 import java.util.List; 9 10 /* 11 查询:所有用户 /users 12 根据id查询用户 /users{id} 13 删除:根据id删除用户 /users{id} 14 添加:添加一个用户 /users{id} 15 修改:修改一个用户 /users{id} 16 */ 17 @RestController 18 public class MyRestController { 19 20 @GetMapping("/users") 21 public List<User> queryUsers() { 22 System.out.println("使用get方式,查询所有users"); 23 User user1 = new User(1, "张三", true, new Date()); 24 User user2 = new User(2, "李四", false, new Date()); 25 return Arrays.asList(user1, user2); 26 } 27 28 @GetMapping("/users/{id}") 29 public User queryOne(@PathVariable("id") Integer id){ 30 System.out.println("使用get方式,查询某个用户"); 31 return new User(1, "张三", true, new Date()); 32 } 33 34 @DeleteMapping("/users/{id}") 35 public String deleteOne(@PathVariable("id") Integer id){ 36 System.out.println("使用delete方式,删除某个用户"); 37 return "ok"; 38 } 39 40 @PostMapping("/users") 41 public String saveUser(@RequestBody User user){ 42 System.out.println("使用post方式,添加一个用户"); 43 return "ok"; 44 } 45 46 @PutMapping("/users") 47 public String updateUser(@RequestBody User user){ 48 System.out.println("使用put方式,修改一个用户"); 49 return "ok"; 50 } 51 }
测试用jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="https://code.jquery.com/jquery-2.1.0.min.js"></script> <script> function queryAll(){ $.ajax({ type:"get", url:"${pageContext.request.contextPath}/users", success:function (d){ console.log(d) } }); } function queryOne(){ $.ajax({ type:"get", url:"${pageContext.request.contextPath}/users/100", success:function (d){ console.log(d) } }); } function saveUser(){ var user = {name:'王五'}; var userStr = JSON.stringify(user); $.ajax({ type:"post", url:"${pageContext.request.contextPath}/users", data:userStr, contentType:"application/json", success:function (d){ console.log(d) } }); } function updateUser(){ var user = {id:3,name:'王五'}; var userStr = JSON.stringify(user); $.ajax({ type:"put", url:"${pageContext.request.contextPath}/users", data:userStr, contentType:"application/json", success:function (d){ console.log(d) } }); } function deleteOne(){ $.ajax({ type:"delete", url:"${pageContext.request.contextPath}/users/200", success:function (d){ console.log(d) } }); } </script> </head> <body> <input type="button" value="查询所有用户" onclick="queryAll()"> <input type="button" value="查询一个用户" onclick="queryOne()"><br> <input type="button" value="新增一个用户" onclick="saveUser()"><br> <input type="button" value="更新一个用户" onclick="updateUser()"><br> <input type="button" value="删除一个用户" onclick="deleteOne()"><br> </body> </html>