1 rest
Rest (REpresentational State Transfer) 一种网络资源的访问风格,定义了网络资源的访问格式
传统风格访问路径
http://localhost/user/get?id=1
http://localhost/deleteUser?id=1
Rest风格访问路径
http://localhost/user/1
Restful是按照Rest风格访问网络资源
优点:
隐藏资源的访问行为,通过地址无法得知做的是何种操作
书写简化
2 Rest行为约定方式
GET (查询) http://localhost/user/1 GET
POST (保存) http://localhost/user POST
PUT (更新) http://localhost/user PUT
DELETE (删除) http://localhost/user DELETE
注意:上午行为是约定方式,约定不是规范,可以打破,所以称Rest风格,而不是Rest规范
3 Restful开发入门
开启SpringMVC对Restful风格的访问支持过滤,即可通过页面表单提交PUT DELETE 请求
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<servlet-name>DispatcherServlet</servlet-name>
</filter-mapping>
页面表单使用隐藏域提交请求类型,参数名称固定位_method,必须配合提交类型method = post 使用
<form action="/user/1" method="post">
<input type="hidden" name="_method" value="PUT"/>
<input type="submit"/>
</form>
4 Restful 简化配置
Restful请求路径简化配置方式
@RestController
public class UserController {
@RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
public String restDelete(@PathVariable String id){
System.out.println("restful is running ....delete:"+id);
return "success.jsp";
}
}
等同于
@RestController
@RequestMapping("/user")
public class UserController {
@DeleteMapping("{id}")
public String restDelete(@PathVariable String id){
System.out.println("restful is running ....delete:"+id);
return "success.jsp";
}
}
5 Restful 常用注解
◆ @RestController 等同于@Controller + @ResponseBody
◆ @PathVariable 校验单个入参—不是指对象
◆ @GetMapping 查询
◆ @PostMapping 保存
◆ @PutMapping 更新
◆ @DeleteMapping 删除