Java框架(七)-- RESTful风格的应用

RESTful风格的应用

一、RESTful开发风格

1、传统Web应用

在这里插入图片描述

2、REST与RESTful

REST - 表现层状态转换,资源在网络中以某种表现形式进行状态转换。
RESTful是基于REST理念的一套开发风格,是具体的开发规则。

3、RESTful传输数据

在这里插入图片描述

4、RESTful开发规范

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

5、RESTful命名要求

在这里插入图片描述

二、开发RESTful Web应用

打开IDEA,新建maven web工程,引入SpringMVC依赖
在这里插入图片描述
在web.xml配置SpringMVC

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <!--
            DispatcherServlet是Spring MVC最核心的对象
            DispatcherServlet用于拦截Http请求,
            并根据请求的URL调用与之对应的Controller方法,来完成Http请求的处理
        -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!--
            在Web应用启动时自动创建Spring IOC容器,
            并初始化DispatcherServlet
            如果不加load-on-startup配置,在第一次访问URL时创建容器和初始化
        -->
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--"/"代表拦截所有请求-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>characterFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

在resources目录下创建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.ql.restful"/>
    <!--启用Spring MVC的注解开发模式-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!--response.setContentType("text/html;charset=utf-8")-->
                        <value>text/html;charset=utf-8</value>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--将图片/JS/CSS等静态资源排除在外,可提高执行效率-->
    <mvc:default-servlet-handler/>
</beans>

在com.ql.restful.controller包下创建RestfulController.java类

package com.ql.restful.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

启动项目,在浏览器地址栏中输入http://localhost:8080/restful/request
在这里插入图片描述

三、实现RESTful实验室

在webapp目录下引入jquery-3.6.0.min.js,并在该目录创建client.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RESTful实验室</title>
    <script src="jquery-3.6.0.min.js"></script>
    <script>
        $(function (){
            $("#btnGet").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"get",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })
            $("#btnPost").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"post",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })
            $("#btnPut").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"put",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })
            $("#btnDelete").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"delete",
                    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请求">
    <h1 id="message"></h1>
</body>
</html>

修改RestfulController

package com.ql.restful.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@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\":\"数据删除成功\"}";
    }

}

运行项目测试
在这里插入图片描述

四、RestController注解与路径变量

@RestController在Controller类上添加,替换@Controller注解,让每个方法放回json数据,方法上无需再用@ResponseBody注解。
修改RestfulController,使用RestController注解与路径变量

package com.ql.restful.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

    @PostMapping("request/{rid}")
//    @ResponseBody
    public String doPostRequest(@PathVariable("rid") Integer requestId){
        return "{\"message\":\"数据新建成功\",\"id\":"+requestId+"}";
    }

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

    @DeleteMapping("request")
//    @ResponseBody
    public String doDeleteRequest(){
        return "{\"message\":\"数据删除成功\"}";
    }

}

再修改client.html中post请求部分

            $("#btnPost").click(function (){
                $.ajax({
                    url:"/restful/request/100",
                    type:"post",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message+":"+json.id);
                    }
                })
            })

运行测试
在这里插入图片描述

五、简单请求与非简单请求

简单请求是指标准结构的HTTP请求,对应GET/POST请求。
非简单请求是复杂要求的HTTP请求,指PUT/DELETE、扩展标准请求。
两者最大区别是非简单请求发送前需要发送预检请求
在这里插入图片描述
我们修改client.html的post和put请求js部分

            $("#btnPost").click(function (){
                $.ajax({
                    url:"/restful/request/100",
                    type:"post",
                    data:"name=lily&age=23",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message+":"+json.id);
                    }
                })
            })
            $("#btnPut").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"put",
                    data:"name=lily&age=23",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })

在com.ql.restful.entity包下创建Person实体类

package com.ql.restful.entity;

public class Person {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

然后修改RestfulController

package com.ql.restful.controller;

import com.ql.restful.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

    @PostMapping("request/{rid}")
//    @ResponseBody
    public String doPostRequest(@PathVariable("rid") Integer requestId, Person person){
        System.out.println(person.getName()+":"+person.getAge());
        return "{\"message\":\"数据新建成功\",\"id\":"+requestId+"}";
    }

    @PutMapping("request")
//    @ResponseBody
    public String doPutRequest(Person person){
        System.out.println(person.getName()+":"+person.getAge());
        return "{\"message\":\"数据更新成功\"}";
    }

    @DeleteMapping("request")
//    @ResponseBody
    public String doDeleteRequest(){
        return "{\"message\":\"数据删除成功\"}";
    }

}

运行依次测试post、put请求
在这里插入图片描述
发现put请求并没能接收到参数。
SpringMVC最早的时候是对网页服务的,默认网页表单提交时只支持简单请求(get、post请求)。随着技术的演进,也需要考虑put、delete请求,SpringMVC提供了额外的表单内容过滤器,来对put、delete请求额外处理。

在web.xml文件中添加FormContentFilter过滤器配置

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

然后重启项目再测试
在这里插入图片描述
post和put请求都能接收到参数了。

六、JSON序列化

打开项目pom.xml引入jackson依赖(注意使用2.10.x以上版本,2.x < 2.9.10.8版本存在反序列化漏洞)

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.6</version>
        </dependency>

SpringMVC非常的智能,它会检测当前类路径一旦存在jackson相关包,会自动提供JSON序列化服务,不需要额外配置。
然后打开com.ql.restful.controller包下RestfulController类添加方法

    @GetMapping("/person")
    public Person findByPersonId(Integer id){
        Person person = new Person();
        if(id==1){
            person.setName("lily");
            person.setAge(23);
        }else if(id==2){
            person.setName("smith");
            person.setAge(22);
        }
        return person;
    }

    @GetMapping("/persons")
    public List<Person> findPersons(){
        List list = new ArrayList();
        Person person1 = new Person();
        person1.setName("lily");
        person1.setAge(23);
        list.add(person1);
        Person person2 = new Person();
        person2.setName("smith");
        person2.setAge(22);
        list.add(person2);
        return list;
    }

当方法返回实体对象或集合,且有@ResponseBody注解时,SpringMVC会自动通过jackson对实体对象或集合进行序列化输出。
运行项目,在浏览器地址栏中输入http://localhost:8080/restful/person?id=1
在这里插入图片描述
在浏览器地址栏中输入http://localhost:8080/restful/persons
在这里插入图片描述
修改src/main/webapp/client.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RESTful实验室</title>
    <script src="jquery-3.6.0.min.js"></script>
    <script>
        $(function (){
            $("#btnGet").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"get",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })
            $("#btnPost").click(function (){
                $.ajax({
                    url:"/restful/request/100",
                    type:"post",
                    data:"name=lily&age=23",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message+":"+json.id);
                    }
                })
            })
            $("#btnPut").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"put",
                    data:"name=lily&age=23",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })
            $("#btnDelete").click(function (){
                $.ajax({
                    url:"/restful/request",
                    type:"delete",
                    dataType:"json",
                    success:function (json){
                        $("#message").text(json.message);
                    }
                })
            })

            $("#btnPersons").click(function (){
                $.ajax({
                    url:"/restful/persons",
                    type: "get",
                    dataType: "json",
                    success: function (json){
                        for(let i=0; i<json.length; i++){
                            $("#divPersons").append("<h2>"+json[i].name+"-"+json[i].age+"</h2>");
                        }
                    }
                })
            })
        })
    </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请求">
    <h1 id="message"></h1>
    <hr/>
    <input type="button" id="btnPersons" value="查询所有人员">
    <div id="divPersons"></div>
</body>
</html>

运行工程,点击查询所有人员测试
在这里插入图片描述
jackson对时间格式默认支持的不是特别理想。

在Person实体类中添加时间格式属性

package com.ql.restful.entity;

import java.util.Date;

public class Person {
    private String name;
    private Integer age;
    private Date birthday;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

然后修改RestfulController中的findPersons方法

    @GetMapping("/persons")
    public List<Person> findPersons(){
        List list = new ArrayList();
        Person person1 = new Person();
        person1.setName("lily");
        person1.setAge(23);
        person1.setBirthday(new Date());
        list.add(person1);
        Person person2 = new Person();
        person2.setName("smith");
        person2.setAge(22);
        person2.setBirthday(new Date());
        list.add(person2);
        return list;
    }

修改src/main/webapp/client.html中的查询所有人员按钮点击事件js

            $("#btnPersons").click(function (){
                $.ajax({
                    url:"/restful/persons",
                    type: "get",
                    dataType: "json",
                    success: function (json){
                        for(let i=0; i<json.length; i++){
                            $("#divPersons").append("<h2>"+json[i].name+"-"+json[i].age+"-"+json[i].birthday+"</h2>");
                        }
                    }
                })
            })

再次运行工程测试
在这里插入图片描述
得知默认展示为时间戳,为了解决这个问题,jackson提出相应注解,修改Person实体类

package com.ql.restful.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class Person {
    private String name;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date birthday;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

重新运行工程,时间显式正常
在这里插入图片描述

七、浏览器的跨域访问

1、浏览器的同源策略

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

2、同源策略示例

在这里插入图片描述

3、HTML中允许跨域的标签

<img> - 显式远程图片
<script> - 加载远程JS
<link> - 加载远程CSS

八、SpringMVC跨域访问

1、CORS跨域资源访问

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

2、SpringMVC解决跨域访问

@CrossOrigin - Controller跨域注解。
<mvc:cors> - SpringMVC全局跨域配置

把之前编写好的restful工程再复制一份
在这里插入图片描述
用IDEA打开新的工程(File->open)
在这里插入图片描述
修改设置,依次点击File-> Project Structure发现已经报红了在这里插入图片描述
点击Facets,点击+号,选择web,然后点击OK
在这里插入图片描述
在这里插入图片描述
然后重新配置下相关配置
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
然后修改端口
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
然后修改这个工程的src/main/webapp/client.html的查询所有人员按钮事件js

            $("#btnPersons").click(function (){
                $.ajax({
                    url:"http://localhost:8080/restful/persons",
                    type: "get",
                    dataType: "json",
                    success: function (json){
                        for(let i=0; i<json.length; i++){
                            $("#divPersons").append("<h2>"+json[i].name+"-"+json[i].age+"-"+json[i].birthday+"</h2>");
                        }
                    }
                })
            })

然后restfull和restfull_8081两个项目都跑起来,浏览器地址栏输入http://localhost:8081/client.html点击查询所有人员,发生了跨域访问问题。
在这里插入图片描述
修改restfull项目的RestfulController,添加注解

@RestController
@RequestMapping("/restful")
@CrossOrigin(origins = {"http://localhost:8081","http://localhost:8082"},maxAge=3600)
//maxAge=3600 为预检请求结果缓存起来,设置时间内同样的请求不再需要预检请求处理,直接发送实际请求
//@CrossOrigin(origins = {"*"}) //*表示所有地址都能访问,有重大安全隐患,不建议使用
public class RestfulController {
...

然后重启应用,再次测试不再报错
在这里插入图片描述
再看看请求相应,Sec-Fetch-Mode: cors标识为跨域访问
在这里插入图片描述
允许访问标识为
在这里插入图片描述

3、CORS全局配置

修改restfull项目的applicationContext.xml

    <mvc:cors>
        <mvc:mapping path="/restful/**"
             allowed-origins="http://localhost:8081,http://localhost:8082"
             max-age="3600"/>
    </mvc:cors>

然后注掉@CrossOrigin注解

@RestController
@RequestMapping("/restful")
//@CrossOrigin(origins = {"http://localhost:8081","http://localhost:8082"},maxAge=3600)
//maxAge=3600 为预检请求结果缓存起来,设置时间内同样的请求不再需要预检请求处理,直接发送实际请求
//@CrossOrigin(origins = {"*"}) //*表示所有地址都能访问,有重大安全隐患,不建议使用
public class RestfulController {
...

重新启动项目,测试也能正常访问
在这里插入图片描述
全局和注解同时配置,以注解为准。

CORS跨域资源访问只是在浏览器中的安全策略,使用小程序或APP的话这些安全策略不再生效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值