zl程序教程

您现在的位置是:首页 >  后端

当前栏目

RESTful风格的应用

restful应用 风格
2023-06-13 09:11:02 时间

RESTful应用

REST-表现层状态转换,资源在网络中以某种表现形式进行状态转移

RESTfl -是基于REST理念的一套开发风格,是具体的开发规则

RESTful开发规范

  • 使用URL作为用户交互入口
  • 明确的语义规范(GET|POST|PUT|DELETE)
  • 只返回数据(JSON|XML),不包含任何展现

RESTful命名要求

RESTful基本使用

RESTful实验室

@Controller
@RequestMapping("/restful")
public class RestfulController {
    @GetMapping("/request")
    @ResponseBody
    public String doGetRequest() {
        return "{\"message\":\"返回查询结果\"}";
    }

    @PostMapping("/request")
    @ResponseBody
    public String doPostRequest() {
        return "{\"message\":\"数据新建成功\"}";
    }

    @PutMapping("/request")
    @ResponseBody
    public String doPutRequest() {
        return "{\"message\":\"数据更新成功\"}";
    }

    @DeleteMapping("/request")
    @ResponseBody
    public String doDeleteRequest() {
        return "{\"message\":\"数据删除成功\"}";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/jquery@3.3.1/dist/jquery.min.js"></script>
    <script>
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    url:"/restful/request",
                    type:"get",
                    dataType:"json",
                    success: function (json) {
                        $("#message").text(json.message);
                    },
                })
            });
        })
        ...
    </script>
</head>
<body>
<input type="button" id="btnGet" value="发送Get请求">
<input type="button" id="btnPost" value="发送Post请求">
<input type="button" id="btnPut" value="发送Put请求">
<input type="button" id="btnDelete" value="发送Delete请求">
<h2 id="message"></h2>
</body>
</html>

RestController注解与路径变量

@RestController:简化开发过程。不需要在方法上额外添加@ResponseBody

//路径变量:存储在URI中的可变的值
@PostMapping("/request/{rid}")
public String doPostRequest(@PathVariable("rid") Integer requestId) {
    return "{\"message\":\"数据新建成功\",\"id\":" + requestId + "}";
}

简单请求与非简单请求

  • 简单请求是指标准结构的HTTP请求,对应GET/POST请求
  • 非简单请求时复杂要求的HTTP请求,值PUT/DELETE、扩展标准请求
  • 两者最大区别是非简单请求发送前需要发送预检请求

非简单请求

SpringMVC需要增加一个过滤器才能接收PUT/DELETE请求

<filter>
    <filter-name>formContextFilter</filter-name>
    <filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>formContextFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

JSON序列化

返回实体对象,同时有@RestController或增加了@ResponseBody,自动的通过配置的Jackson对实体对象进行序列化

1.添加依赖

<!--核心-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.13.2</version>
</dependency>
<!--数据绑定-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>
<!--注解-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.13.3</version>
</dependency>

2.方法定义时不在返回String而是返回实例化对象

@GetMapping("/person")
// 返回实体对象,同时有@RestController或增加了@ResponseBody,自动的通过配置的Jackson对实体对象进行序列化
public Person findByPersonId(Integer id) {
    Person p = new Person();
    if (id == 1) {
        p.setName("lily");
        p.setAge(23);
    } else if (id == 2) {
        p.setName("Jack");
        p.setAge(22);
    }
    return p;
}

3.日期类型转换

在使用日期类型时添加@JsonFormat()注解进行格式化输出,要指明输出格式还有时区的偏差

跨域问题

  • 同源策略:阻止从一个域加载的脚本去获取另一个域上的资源
  • 只要协议、域名、端口有任何一个不同,都被当作是不同的域
  • 浏览器Console看到Access-Control-Allow-Orgin就代表跨域了

SpringMVC跨域访问

  • CORS是一种机制,使用额外的HTTP头通知浏览器可以访问其他域
  • URL响应头包含 Access-Control-* 指明请求允许跨域

@CrossOrigin - Controller跨域注解

//多域名跨域
@CrossOrigin(origins = "{http://localhost:8080,http://www.huazll.cn}")

<mvc:cors> - SpringMVC全局跨域配置

<mvc:cors>
    <mvc:mapping path="/restful/**" allowed-origins="http://localhost:8080,http://www.huazll.cn" max-age="3600"/>
</mvc:cors>