版权声明:本文为博主ExcelMann的原创文章,未经博主允许不得转载。
4、RestFul风格
作者:ExcelMann,转载需注明。
概念:
RestFul就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这种风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制;
传统方式操作资源:通过不同的参数来实现不同的效果!(下面四个url,分别是查询、增加、更新、删除)
- localhost://8080/item/queryItem.action?id=1
- localhost://8080/item/addItem.action
- localhost://8080/item/updateItem.action
- localhost://8080/item/deleteItem.action?id=1
使用RestFul风格操作资源:可以通过不同的请求方式来实现不同的效果!请求地址是一样的,但是功能可以不同,达到url的复用。
- localhost://8080/item/1 查询,Get
- localhost://8080/item 新增,Post
- localhost://8080/item 更新,Put
- localhost://8080/item/1 删除,Delete
RestFul风格的两种实现:
(对于参数,都要使用@PathVariable
注解)
-
@RequestMapping(value = "/restFul/{a}/{b}",method = RequestMethod.GET) public String testRestFul(@PathVariable int a,@PathVariable int b,Model model){ int result = a+b; model.addAttribute("msg","结果为"+result); return "test"; }
-
@GetMapping("/restFul/{a}/{b}") public String testRestFul(@PathVariable int a,@PathVariable int b,Model model){ int result = a+b; model.addAttribute("msg","结果为"+result); return "test"; }
不同请求方式的RestFul注解:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
使用RestFul路径变量的好处:
- 使得路径变量变得更加简洁;
- 获得参数更加方便,框架会自动进行类型转换;
- 可复用URL;
- 安全性:隐藏了路径变量的变量名;