RESTFul从入门到精通超全解析(全)

简介: 目录前言1. 定义2. 实战代码2.1 前期工作3. HiddenHttpMethodFilter3.1 源码3.2 实现方式3.3 细节前言RESTFul(Representational State Transfer)表现层资源状态转移。(也就是前端的视图界面和后端的控制层界面的转移)在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的1. 定义一种协议主要是形式比较方便访问一个 http 接口:http://localh

前言

RESTFul(Representational State Transfer)表现层资源状态转移。
(也就是前端的视图界面和后端的控制层界面的转移)
在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的

1. 定义

  • 一种协议
  • 主要是形式比较方便

访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1
采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

HTTP 协议里面四个常用的基本操作:

  • GET 获取资源

    • POST 新建资源
    • PUT 更新资源
    • DELETE 删除资源

具体get和post的一些区别还可参考我之前的文章
HTTP协议中 GET 和 POST的区别(全)

使用RESTFul模拟用户资源的增删改查

路径 请求方式 功能
/user GET 查询所有用户信息
/user/1 GET 根据用户id查询用户信息
/user POST 添加用户信息
/user/1 DELETE 删除用户信息
/user PUT 修改用户信息

主要的注解有:
@PathVariable 获取 url 中的数据

2. 实战代码

再这之前还要配置一些基本的配置以及依赖文件
带着大家回顾一下

2.1 前期工作

  1. 配置文件pom.xml
<!-- SpringMVC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.1</version>
</dependency>

<!-- 日志 -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

<!-- ServletAPI -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

<!-- Spring5和Thymeleaf整合包 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
  1. web.xml配置文件

配置编码过滤器以及HiddenHttpMethodFilter过滤器还有前端控制器
DispatcherServlet==主要是将前端控制器的初始化启动时间提前到服务器启动时间==

<!--配置编码过滤器-->
<filter>
    <filter-name>CharacterEncodingFilter</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>
    <init-param>
        <param-name>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<!--配置处理请求方式put和delete的HiddenHttpMethodFilter-->
<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>

<!--配置SpringMVC的前端控制器DispatcherServlet-->
<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  1. springmvc.xml的配置文件
<!--扫描组件-->
<context:component-scan base-package="com.atguigu.rest"></context:component-scan>

<!--配置Thymeleaf视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="order" value="1"/>
    <property name="characterEncoding" value="UTF-8"/>
    <property name="templateEngine">
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver">
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                    <!-- 视图前缀 -->
                    <property name="prefix" value="/WEB-INF/templates/"/>

                    <!-- 视图后缀 -->
                    <property name="suffix" value=".html"/>
                    <property name="templateMode" value="HTML5"/>
                    <property name="characterEncoding" value="UTF-8" />
                </bean>
            </property>
        </bean>
    </property>
</bean>
  1. 搭建实体类
public class Employee {

    private Integer id;
    private String lastName;

    private String email;
    //1 male, 0 female
    private Integer gender;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Employee(Integer id, String lastName, String email, Integer gender) {
        super();
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
    }

    public Employee() {
    }
}
  1. 搭建数据类dao

如果控制层面的代码要调用数据类的代码,可以新建一个类对象之后调用,但是学了spring,可以将其交给spring容器,在对象中标上注解@Autowired,在数据层面的类中标上注解@Repository

@Repository
public class EmployeeDao {

    private static Map<Integer, Employee> employees = null;

    static{
        employees = new HashMap<Integer, Employee>();

        employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
    }

    private static Integer initId = 1006;

    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }

    public Collection<Employee> getAll(){
        return employees.values();
    }

    public Employee get(Integer id){
        return employees.get(id);
    }

    public void delete(Integer id){
        employees.remove(id);
    }
}
  1. 控制层面的代码
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;
}

2.2 访问主页

访问主页可以通过控制层面的代码加上@RequestMapping的基本函数
或者可以通过注解方式进行
springmvc.xml文件中配置

<!--配置视图控制器-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>

<!--开启mvc注解驱动-->
<mvc:annotation-driven />

主页面信息

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>

2.3 实现列表功能

@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getAllEmployee(Model model){
    Collection<Employee> employeeList = employeeDao.getAll();
    model.addAttribute("employeeList", employeeList);
    return "employee_list";
}

获取页面的信息如下

<table id="dataTable" border="1" cellspacing="0" cellpadding="0" style="text-align: center;">
    <tr>
        <th colspan="5">Employee Info</th>
    </tr>
    <tr>
        <th>id</th>
        <th>lastName</th>
        <th>email</th>
        <th>gender</th>
        <th>options(<a th:href="@{/toAdd}">add</a>)</th>
    </tr>
    <tr th:each="employee : ${employeeList}">
        <td th:text="${employee.id}"></td>
        <td th:text="${employee.lastName}"></td>
        <td th:text="${employee.email}"></td>
        <td th:text="${employee.gender}"></td>
        <td>
            <a @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">delete</a>
            <a th:href="@{'/employee/'+${employee.id}}">update</a>
        </td>
    </tr>
</table>

employee : ${employeeList}遍历集合中的元素,后面是请求域

==删除功能之处理超链接路径==

通过"@{'/employee/'+${employee.id}}"这种方式进行书写或者是"@{/employee/}+${employee.id}"

2.4 实现删除功能

具体思路如下,制作一个删除方式的表单
点击超链接并且绑定一个事件(通过vue进行处理事件)

vue要放在static下,如果放在了WEB-INF的话,就会变成转发的请求
因为删除要用post的请求,而且是hidden的类型,具体名字为_method

<form id="deleteForm" method="post">
    <input type="hidden" name="_method" value="delete">
</form>

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            deleteEmployee:function (event) {
                //根据id获取表单元素
                var deleteForm = document.getElementById("deleteForm");
                //将触发点击事件的超链接的href属性赋值给表单的action
                deleteForm.action = event.target.href;
                //提交表单
                deleteForm.submit();
                //取消超链接的默认行为
                event.preventDefault();
            }
        }
    });
</script>
  • 要操作的是超链接数据,所以设置一个属性,也就是vue的容器el
  • 要操作超链接的删除事件,也就是要绑定事件 <a @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">delete</a>
  • 处理事件的属性是methods
  • 如果不设置action,就会提交到本地,所以要设置action,而且属性是event.target.href

所谓的默认行为是
不会自动跳转到该页面等
在这里插入图片描述

实现删除功能的代码为
回到的页面和之前的页面是不一样的,而且是回到上级目录。所以不可以使用转发,转发是同一个请求,应该用重定向,重定向是两个不一样的请求

转发和重定向的区别及使用方法(全)

@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
    employeeDao.delete(id);
    return "redirect:/employee";
}
  • 即使当前服务器有vue.js,也要在springmvc配置一个default-servlet的控制器,静态资源static中就会识别到

springmvc的配置dispatchersetvlet找不到就会找默认的default-servlet来处理,再找不到就会识别不到

<!--开放对静态资源的访问-->
<mvc:default-servlet-handler />

主要的dispatchersetvlet这个要加上

<!--开启mvc注解驱动-->
<mvc:annotation-driven />

此处附上vue.js的代码案例

在这里插入图片描述

2.5 实现添加功能

具体设置添加功能的跳转链接如下
这是前面的页面信息,主要是这个跳转链接主要信息如下

<th>options(<a th:href="@{/toAdd}">add</a>)</th>

具体的主页面信息不用增删一些什么东西
所以可以直接设置注解类

<mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>

跳转的显示页面信息是加上/toAdd,直接显示到employee_add.html这个页面

employee_add.html具体的页面显示信息为一个表格信息
主要的点击action事件会跳转到添加的页面信息

<form th:action="@{/employee}" method="post">
    lastName:<input type="text" name="lastName"><br>
    email:<input type="text" name="email"><br>
    gender:<input type="radio" name="gender" value="1">male
    <input type="radio" name="gender" value="0">female<br>
    <input type="submit" value="add"><br>
</form>

主要的控制层界面代码为
通过获取对象值进行传参

@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

2.6 实现回显功能

employee_update具体的页面信息

<form th:action="@{/employee}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="hidden" name="id" th:value="${employee.id}">
    lastName:<input type="text" name="lastName" th:value="${employee.lastName}"><br>
    email:<input type="text" name="email" th:value="${employee.email}"><br>
    gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
    <input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br>
    <input type="submit" value="update"><br>
</form>

具体控制层面的代码如下

@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}

在主页面的列表清单中还需要显示更新的这个选项
点击更新之后会跳转到控制层面的代码页面,具体的代码页面会回到 回显的页面信息
本身回显的页面信息,<input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br>这些都是默认为checked,是不能修改的

<a th:href="@{'/employee/'+${employee.id}}">update</a>

2.7 实现修改功能

回显功能中的最后只要修改他的页面主要信息,在进行更新提交表单就是他的修改页面信息了
主要的控制层面的代码为

@RequestMapping(value = "/employee", method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

要增加这个页面的信息
如果不增加默认的页面信息是get请求,修改不到

3. HiddenHttpMethodFilter

最后补充这个知识点

==由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?==

  • 用ajax的api来进行传参,本身http的请求中(get和post),默认方式是get,其他的htpp请求(put和delete也可以使用),但是仅只有部分浏览器支持这种传输,为了避免这种传输失误,有了如下方法
  • SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求

HiddenHttpMethodFilter 处理put和delete请求的条件:

  • 当前请求的请求方式必须为post
  • 当前请求必须传输请求参数_method

如果不设置HiddenHttpMethodFilter这个过滤,即使设置了上面的参数,默认还是会调用get的参数,而不会管method的参数

比如下面这个例子

@RequestMapping(value = "/user", method = RequestMethod.GET)
public String getAllUser(){
    System.out.println("查询所有用户信息");
    return "success";
}

@RequestMapping(value = "/user", method = RequestMethod.PUT)
public String updateUser(String username, String password){
    System.out.println("修改用户信息:"+username+","+password);
    return "success";
}

在html文件中只输出

<form th:action="@{/user}" method="put">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="修改"><br>
</form>

但是在终端中只输出了“查询所有用户信息”
说明其显示的时候还是调用了get的请求方式,而不是post的请求方式
为此需要设置其过滤器

具体其过滤器设置方式为

<!--配置HiddenHttpMethodFilter-->
<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>

3.1 源码

具体其源码可以通过点击该类进行查看
之后查看其主要的方法可以通过alt+7快捷键或者查找父类之后在找到其方法
在这里插入图片描述
主要是这个方法,因为这个方法中有filterChain
查看其源码数据

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest requestToUse = request;
        if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
            String paramValue = request.getParameter(this.methodParam);
            if (StringUtils.hasLength(paramValue)) {
                String method = paramValue.toUpperCase(Locale.ENGLISH);
                if (ALLOWED_METHODS.contains(method)) {
                    requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
                }
            }
        }

        filterChain.doFilter((ServletRequest)requestToUse, response);
    }
  • 其request为请求的数据,如果为post请求之后往下执行(右边的条件一定会成立的)
  • 获取这个参数本身系统已经有所定义

在这里插入图片描述

  • 判断是否有所长度之后将其method变量变为大写
  • 在判断ALLOWED_METHODS其是否包含method这个变量中的值往下执行,具体ALLOWED_METHODS变量中包含的method只有这三个变量
 static {
        ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    }
  • HttpMethodRequestWrapper(request, method)主要是获取method到request中,method是前面大写的那个
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }

        public String getMethod() {
            return this.method;
        }
    }

3.2 实现方式

主要的实现方式是添加过滤器的配置
以及在html页面中增加一个post的请求方式,还有name的名字以及真正value的值

<form th:action="@{/user}" method="post">
    <input type="hidden" name="_method" value="PUT">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="修改"><br>
</form>

不需要初始化设置,第一个请求是post请求,第二个传输的参数是_method

具体其过滤器设置方式为

<!--配置HiddenHttpMethodFilter-->
<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>

3.3 细节

如果有多个过滤器同时进行,将按照顺序执行过滤器

但是编码过滤器必须要在第一个,因为设置编码之前不能获取任何参数,获取了_method的请求,所以需要将其HiddenHttpMethodFilter放在编码过滤器之前

相关文章
|
1月前
|
监控 关系型数据库 MySQL
轻松入门MySQL:主键设计的智慧,构建高效数据库的三种策略解析(5)
轻松入门MySQL:主键设计的智慧,构建高效数据库的三种策略解析(5)
|
1月前
|
SQL 存储 关系型数据库
轻松入门MySQL:简明教程解析数据存储与管理(1)
轻松入门MySQL:简明教程解析数据存储与管理(1)
|
12天前
|
存储 监控 关系型数据库
InfluxDB入门:基础概念解析
【4月更文挑战第30天】InfluxDB是开源时序数据库,擅长处理实时数据,常用于监控和分析。本文介绍了其基础概念:数据库(数据容器)、测量值(类似表)、字段(数据值)、标签(元数据)、时间戳和数据点。InfluxDB特性包括高性能写入、灵活查询(InfluxQL和Flux)、可扩展性及活跃社区支持。了解这些概念有助于更好地使用InfluxDB处理时间序列数据。
|
6天前
|
Java Spring 容器
【AOP入门案例深解析】
【AOP入门案例深解析】
17 2
|
13天前
|
存储 机器学习/深度学习 算法
|
16天前
|
存储 NoSQL Redis
Redis入门到通关之数据结构解析-IntSet
Redis入门到通关之数据结构解析-IntSet
22 1
|
16天前
|
存储 NoSQL Redis
Redis入门到通关之数据结构解析-SkipList
Redis入门到通关之数据结构解析-SkipList
30 0
|
16天前
|
存储 NoSQL Redis
Redis入门到通关之数据结构解析-QuickList
Redis入门到通关之数据结构解析-QuickList
25 0
|
16天前
|
存储 NoSQL 安全
Redis入门到通关之数据结构解析-动态字符串SDS
Redis入门到通关之数据结构解析-动态字符串SDS
18 0
|
16天前
|
存储 NoSQL Java
Redis入门到通关之数据结构解析-Dict
Redis入门到通关之数据结构解析-Dict
19 2

推荐镜像

更多