关于restful风格的URl请求

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值