RestFul 风格
RestFul 风格是一种和传统方式有区别的风格
传统方式操作资源 :通过不同的参数来实现不同的效果!方法单一,post 和 get
- http://127.0.0.1/item/queryItem.action?id=1 查询,GET
- http://127.0.0.1/item/saveItem.action 新增,POST
- http://127.0.0.1/item/updateItem.action 更新,POST
- http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST
使用RESTful操作资源 : 可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能
可以不同!
- http://127.0.0.1/item/1 查询,GET
- http://127.0.0.1/item 新增,POST
- http://127.0.0.1/item 更新,PUT
- http://127.0.0.1/item/1 删除,DELETE
优点:
- 资源唯一性
- 简介性
- 安全性
- 便捷性
它是一直风格,规范,而不是一种约束。
功能:
-
资源:互联网所有的事物都可以被抽象为资源
-
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
-
分别对应 添加、 删除、修改、查询。
使用方法
@Controller
public class RestFulController {
@RequestMapping(value = "/restful/{a}/{b}", method = RequestMethod.GET)
public String index(@PathVariable int a, @PathVariable int b, Model model){
int c = a+b;
model.addAttribute("msg","a+b="+c);
return "restful";
}
}
通过method = RequestMethod.GET的方式可以约束请求类型,使请求更加的安全化
@PathVariable:非表格传参时必须加上,不然无法获取路径变量。
名字不匹配时,@PathVariable(“pwd”)。
优化:我们可以用另一种方式来简化它
@GetMapping
public String index1(@PathVariable int a, @PathVariable int b, Model model){
int c = a+b;
model.addAttribute("msg","a+b="+c);
return "restful";
}
每一个方法都有相对应:还有其他方式,但是这些基本的。
@GetMapping
@PutMapping
@DeleteMapping
@PostMapping