Restful是什么
中文名称:表现层状态转化。用 URL 表示要操作的资源,用不同的 HTTP 请求(GET,POST,PUT,DELETE)描述对资源的操作,通过 HTTP 的状态码来判断此次对资源操作的结果,这就是 Restful风格。
其实 Restful 风格是对请求的一次解耦,提高了 url 的重用性。
状态转化:客户端通过 http 协议访问服务端资源,通过 http 协议里面定义好的四个动词:GET POST PUT DELETE 来讲资源进行状态转化。
GET 用来获取资源
POST 用来新增资源
PUT 用来更新资源
DELETE 用来删除资源
.uri中可以不用出现save、delete、update、findAll等关键字,只需要合理使用不同请求法方式即可。
传统:http://localhost:8080/user/save
REST:http://localhost:8080/user
POST 执行保存
传统:http://localhost:8080/user/delete?id=1
REST:http://localhost:8080/user/1
DELETE 执行删除
传统:http://localhost:8080/user/update?id=1
REST:http://localhost:8080/user/1
PUT 执行更新 1就是id
传统:http://localhost:8080/user/findAll
REST:http://localhost:8080/user
GET 查所有
(1)在web.xml
<!-- 配置restful风格url请求的hidden过滤器 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--AJAX发送PUT请求: form 表单只支持 GET 与 POST 请求,而 DELETE、PUT 等 method 并不支持
* PUT请求,请求体中的数据,request.getParameter("email");拿不到
* Tomcat一看是PUT不会封装请求体中的数据为map,只有POST形式的请求才封装请求体为map
* tomcat源码(略)
*
* 解决方案;
* 我们要能支持直接发送PUT之类的请求还要封装请求体中的数据
* 配置上HttpPutFormContentFilter;
* 他的作用:将请求体中的数据解析成一个map
*request被重新包装,request.getParameter()被重写,就会从自己封装的map中取数据 -->
<filter>
<filter-name>HttpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
二.@RequesetMapping 注解用指定 method 的方式来匹配 url
带参数的这种方式,需要用 @PathVariable 注解来接收
//按照员工id查询
@RequestMapping(value="/emp/{id}",method = RequestMethod.GET)
@ResponseBody
public Msg getEmp(@PathVariable("id") Integer id){
Employee employee=employeeService.getEmp(id);
return Msg.success().add("emp",employee);
}
//PathVariable用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
//url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志
//根据id修改保存员工 empId得和employee的empId对应
@RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
@ResponseBody
public Msg saveEmp(Employee employee) {
employeeService.updateEmp(employee);
System.out.println(employee);
return Msg.success();
} //可以直接拿到emloyee
/emp/1 HTTP GET : 得到 empId = 1 的 employee
/emp/1 HTTP DELETE: 删除 empId = 1 的 employee
/emp1 HTTP PUT: 更新 empId = 1 的 employee