REST风格的URL及其实现

1 REST概述

REST:即Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。

①资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。
它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的URI。获取这个资源,访问它的URI就可以,因此URI即为每一个资源的独一无二的识别符。

②表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文本可以用txt格式表现,也可以用HTML格式、XML格式、JSON格式表现,甚至可以采用二进制格式。

③状态转化(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“状态转化”(State Transfer)而这种转化是建立在表现层之上的,所以就是“表现层状态转化”。

④具体说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源。

REST风格的URL与传统URL的区别

比如说有一个User类,编写了一个UserController对其进行操作,其中有save()、update()、findById(Integer id)、findAll()、delete(Integer id)……方法

原来方式的URL						restful风格URL
UserController						UserController

path="/user/save"					path="/user"			post请求
save(){}							save(){}

path="/user/update"					path="/user"			put请求
update(){}							update(){}

path="/user/findById?id=xxx"		 path="/user/{id}"	      get请求
findById(Integer id){}				findById(Integer id){}

path="/user/findAll"				path="/user"			get请求
findAll(){}						    findAll(){}

path="/user/delete?id=xxx"		     path="/user/{id}"	      delete请求
delete(Integer id){}				delete(Integer id){}

restful风格的URL特点为所有请求的路径都一样,比如说上面四个方法,它的请求路径都是localhost:8080/user,它根据请求路径和请求方式(POST、GET、DELETE、PUT)执行不同的方法。如有一个url为localhost:8080/user的请求:

  • 若请求方式为post:则执行save(){}
  • 若请求方式为put:则执行update(){}
  • 若请求方式为delete:则执行delete(Integer id){}
  • 若请求方式为get,这时候有两个方法可供选择,此时再根据url中的占位符执行不同的方法
    • localhost:8080/user/100:则执行findById(Integer id){}
    • localhost:8080/user:则执行findAll(){}

2 REST风格的实现

项目源码 92le

2.1 Spring MVC实现

浏览器 form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,Spring3.0添加了一个过滤器HiddenHttpMethodFilter,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE请求。

1、先在web.xml中配置过滤器HiddenHttpMethodFilter

  <!--为REST风格的实现配置过滤器-->
  <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>

2、程序代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="user/1000">测试springmvc GET请求</a>

<form action="user" method="POST">
    <input type="submit" value="测试springmvc post请求"/>
</form>

<form action="user" method="POST">
    <%--注意:表单中需添加 type="hidden" name="_method" value="xxx" 其中type、name属性的值都是固定的,value属性的值根据需要设置--%>
    <input type="hidden" name="_method" value="PUT"/>
    <input type="submit" value="测试springmvc put请求"/>
</form>

<form action="user/2000" method="POST">
    <input type="hidden" name="_method" value="DELETE"/>
    <input type="submit" value="测试springmvc delete请求"/>
</form>

</body>
</html>
@Controller
public class TestController1 {

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String testFind(@PathVariable("id") Integer uid) {
        System.out.println("测试get请求。id值为:" + uid);
        return "success";
    }
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public String testDelete(@PathVariable("id") Integer uid) {
        System.out.println("测试delete请求。id值为:" + uid);
        return "success";
    }
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String testInsert() {
        System.out.println("测试post请求");
        return "success";
    }
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public String testUpdate() {
        System.out.println("测试put请求");
        return "success";
    }
}
<%--注意:需添加 isErrorPage="true"--%>
    
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
你好,欢迎访问!
</body>
</html>

在这里插入图片描述

2.2 AJAX实现

相较于Spring MVC方式,使用AJAX方式实现不需要配置过滤器HiddenHttpMethodFilter

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script>
        function testInsert() {
            $.ajax({
                url:"ajax",
                type: "POST",
                data: {"id":"100", "username":"jack"},
                success:function () {
                    alert("测试post成功")
                }
            });
        }
        function testFind() {
            $.ajax({
                url:"ajax/99",
                type: "GET",
                success:function () {
                    alert("测试get成功")
                }
            });
        }
        function testDelete() {
            $.ajax({
                url:"ajax/88",
                type: "DELETE",
                success:function () {
                    alert("测试delete成功")
                }
            });
        }
        function testUpdate() {
            $.ajax({
                url:"ajax",
                type: "PUT",
                success:function () {
                    alert("测试put成功")
                }
            });
        }
    </script>

 </head>
<body>
<h2>Hello World!</h2>

<input type="button" value="测试ajax post请求" onclick="testInsert()"/>
<input type="button" value="测试ajax get请求" onclick="testFind()"/>
<input type="button" value="测试ajax delete请求" onclick="testDelete()"/>
<input type="button" value="测试ajax put请求" onclick="testUpdate()"/>

</body>
</html>

@Controller
public class AjaxController {
    @RequestMapping(value = "/ajax/{id}", method = RequestMethod.DELETE)
    public String testDelete(@PathVariable("id") Integer uid) {
        System.out.println("测试delete请求。id值为:" + uid);
        return "success";
    }
    @RequestMapping(value = "/ajax/{id}", method = RequestMethod.GET)
    public String testFind(@PathVariable("id") Integer uid) {
        System.out.println("测试get请求。id值为:" + uid);
        return "success";
    }
    @RequestMapping(value = "/ajax", method = RequestMethod.POST)
    public String testInsert(@RequestBody String body) {
        System.out.println("测试post请求。用户信息为:" + body);
        return "success";
    }
    @RequestMapping(value = "/ajax", method = RequestMethod.PUT)
    public String testUpdate() {
        System.out.println("测试put请求");
        return "success";
    }
}

在这里插入图片描述

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值