补充知识:


REST还有一个问题就是:
如访问地址 http://localhost/user 既可以表示为保存用户的路径,又可以表示添加用户信息的路径,也就是说:一个REST风格描述的资源访问路径可以代表几个不同的访问数据库资源信息的路径
因此、我们应该怎么精确的区分到底访问的是哪个路径下的资源呢:使用行为动作(请求方式)区分

思路也就如下所示:
其实也就下面要点:
设置http请求动作(也就是:method是post请求还是get还是......)
路径参数{id}
@PathVariable注解

总体代码如下所示:
ServletContainersInitConfig:

SpringMvcConfig:

UserController:
- package com.itheima.controller;
-
- import com.itheima.domain.User;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.*;
-
- @Controller
- public class UserController {
-
- //设置当前请求方法为POST,表示REST风格中的添加操作
- @RequestMapping(value = "/users/{id}",method = RequestMethod.POST)
- @ResponseBody
- public String save(@PathVariable Integer id){
- System.out.println("user save..."+id);
- return "{'module':'user save'}";
- }
-
- //设置当前请求方法为DELETE,表示REST风格中的删除操作
- //@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同
- @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
- @ResponseBody
- public String delete(@PathVariable Integer id){
- System.out.println("user delete..." + id);
- return "{'module':'user delete'}";
- }
-
- //设置当前请求方法为PUT,表示REST风格中的修改操作
- @RequestMapping(value = "/users",method = RequestMethod.PUT)
- @ResponseBody
- public String update(@RequestBody User user){ // @RequestBody注解:接收前端JSON数据
- //格式的注解(看JSON那边的笔记)
- System.out.println("user update..."+user);
- return "{'module':'user update'}";
- }
-
- //设置当前请求方法为GET,表示REST风格中的查询操作
- //@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同
- @RequestMapping(value = "/users/{id}" ,method = RequestMethod.GET)
- @ResponseBody
- public String getById(@PathVariable Integer id){
- System.out.println("user getById..."+id);
- return "{'module':'user getById'}";
- }
-
- //设置当前请求方法为GET,表示REST风格中的查询操作
- @RequestMapping(value = "/users",method = RequestMethod.GET)
- @ResponseBody
- public String getAll(){
- System.out.println("user getAll...");
- return "{'module':'user getAll'}";
- }
-
- }
前端用REST风格进行访问后端路径下的资源(就拿delete为例):


路径/books要重复的写,实际开发中会比较麻烦

因此我们在springmvc处理客户端请求的时候就处理过该重复问题:把/books路径直接提出取来,如下所示:

@ResponseBody 返回体的注解也要每个方法都要写,也是比较麻烦的,因此也可以把该注解提到类上面

简化后:(注意:如果用这种简化方式,那么就要保证每个方法都有响应给前端的返回值,因为该@ResponseBody注解就是响应给前端返回值数据的注解)


用@RestController注解简化该两个注解


然后就可以让前端进行路径请求了(以delete为例子):

