REST(Representational State Transfer),表现形式状态转换。
按照REST风格访问资源时使用行为动作区分对资源进行了何种操作。
http://localhost/users | 查询全部用户信息 | GET |
http://localhost/users/1 | 查询指定用户信息 | GET |
http://localhost/users | 添加用户信息 | POST |
http://localhost/users | 修改用户信息 | PUT |
http://localhost/users/1 | 删除用户信息 | DELETE |
根据REST风格对资源进行访问称为RESTful
注意:描述模块的名称通常使用复数
步骤:
①设定http请求动作,在方法上加注释
//查询单个
@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
//查询所有
@RequestMapping(value = "/users",method = RequestMethod.GET)
@RequestMapping(value = "/users",method = RequestMethod.POST)
@RequestMapping(value = "/users",method = RequestMethod.PUT)
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
②请求的参数如有路径变量,需加上@PathVariable,路径参数和形参名称要相同
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable Integer id){
return "user delete";
}
区别:@RequestBody @RequestParam @PathVariable
- @RequestBody用于接收json数据
- @RequestParam用于接收url地址传参或表单传参
- @PathVariable用于接收路径参数。使用{参数名称}描述路径参数
应用:
- 后期开发中,发送请求参数超过1个时,以json格式为主,@RequestBody应用较广
- 如果发送非json格式数据,选用@RequestParam接收请求参数
- 采用RESTful进行开发,当参数数量较少时,例如1个,可以采用@PathVariable接收请求路径变量,通常用于传递id值
简化:
- 如果控制器类中方法都有@ResponseBody,可以提取到控制器类上写
- 如果控制器类中@RequestMapping路径一样,可以提取到控制器类上写,方法中@RequestMapping的value可以省略不写,有路径参数的直接写路径参数
//类的注解
@RequestMapping("/users")
//方法的注解
@RequestMapping(value="/{id}",method = RequestMethod.DELETE)
//简化为
@DeleteMapping("/{id}")
注解的简化:
- @RestController(类注解) = @Controller + @RequestMapping
- @GetMapping(方法注解) = @RequestMapping(method = RequestMethod.GET)
- @PostMapping (方法注解)= @RequestMapping(method = RequestMethod.POST)
- @PutMapping (方法注解)= @RequestMapping(method = RequestMethod.PUT)
- @DeleteMapping (方法注解)= @RequestMapping(method = RequestMethod.DELETE)