spring-mvc使用restful开发风格

1.0 Rest

2.0 Rest行为约定方式

注意:上述行为是约定方式,约定不是规范,可以打破,所以称Rest风格,而不是Rest规范

3.0 前台发送请求

//<a href="javascript:void(0);" @click="list">GET请求发送给请求查询user列表</a>
list(){
    axios.get("user/1/5").then(resp=>{
        console.log(resp.data)
    });
}
//<a href="javascript:void(0);" @click="findById">GET请求根据id查询user信息</a>
findById(){
    axios.get("user/10").then(resp=>{
        console.log(resp.data);
    });
}

//<a href="javascript:void(0);" @click="addUser">POST请求添加用户信息</a>
addUser(){
    axios.post("user",this.user).then(resp=>{
        alert(resp.data);
    });
}
//<a href="javascript:void(0);" @click="updateUser">PUT请求修改用户信息</a>
updateUser(){
    axios.put("user",this.user).then(resp=>{
        alert(resp.data);
    });
}
//<a href="javascript:void(0);" @click="deleteUser">DELETE请求删除用户信息</a>
deleteUser(){
    axios.delete("user/10").then(resp=>{
        alert(resp.data);
    });
}

4.0 后台接收请求

/*@Controller
@ResponseBody*/
@RestController //等价于@Controller+@ResponseBody
@RequestMapping("/user")
public class UserController {

  //分页查询用户信息的方法
  //@RequestMapping(value = "/{currentPage}/{pageSize}",method = RequestMethod.GET)
  @GetMapping("/{currentPage}/{pageSize}")
  public PageInfo<User> list(@PathVariable Integer currentPage,
                             @PathVariable Integer pageSize){
    System.out.println("currentPage--->"+currentPage);
    System.out.println("pageSize--->"+pageSize);
    //此处省略500行代码
    return pageInfo;
  }
  //根据id查询User信息的方法
  //@RequestMapping(value = "/{id}",method = RequestMethod.GET)
  @GetMapping("/{id}")
  public User findById(@PathVariable Integer id){
    System.out.println("findById--->"+id);
    //此处省略500行代码
    return user;
  }
  //添加用户
  @PostMapping
  //@RequestMapping(method = RequestMethod.POST)
  public String addUser(@RequestBody User user){
    System.out.println("addUser--->"+user);
     //此处省略500行代码
    return "success";
  }

  //修改用户
  //@RequestMapping(method = RequestMethod.PUT)
  @PutMapping
  public String updateUser(@RequestBody User user){
    System.out.println("updateUser--->"+user);
    //此处省略500行代码
    return "success";
  }
  //删除
  //@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
  @DeleteMapping("/{id}")
  public String deleteUser(@PathVariable Integer id){
    System.out.println("deleteUser--->"+id);
    //此处省略500行代码
    return "success";
  }
}
上一篇:SpringMVC-01-第一个SpringMVC程序,注解开发,Restful风格等


下一篇:七、RESTFul