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等关键字,只需要合理使用不同请求法方式即可。
传统:localhost:8080/user/save
REST:localhost:8080/user
POST 执行保存
传统:localhost:8080/user/delete?id=1
REST:localhost:8080/user/1
DELETE 执行删除
传统:localhost:8080/user/update?id=1
REST:localhost:8080/user/1
PUT 执行更新 1就是id
传统:localhost:8080/user/findAll
REST:localhost:8080/user
GET 查所有
(1)在l
<!-- 配置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请求,请求体中的数据Parameter("email");拿不到* Tomcat一看是PUT不会封装请求体中的数据为map,只有POST形式的请求才封装请求体为map* tomcat源码(略)** 解决方案;* 我们要能支持直接发送PUT之类的请求还要封装请求体中的数据* 配置上HttpPutFormContentFilter;* 他的作用:将请求体中的数据解析成一个map*request被重新包装Parameter()被重写,就会从自己封装的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)@ResponseBodypublic Msg getEmp(@PathVariable("id") Integer id){Employee employeeEmp(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
本文发布于:2024-01-29 03:53:50,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170647163712506.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |