• 7 RESTful


    7、RESTful

    7.1、RESTful简介

    REST:Representational State Transfer,表现层资源状态转移。

    ①资源

    资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。

    ②资源的表述

    资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。

    ③状态转移

    状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的。


    7.2、RESTful的实现

    具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。

    它们分别对应四种基本操作
    GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE用来删除资源。

    REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。

    操作传统方式REST风格
    查询操作getUserById?id=1user/1–>get请求方式
    保存操作saveUseruser–>post请求方式
    删除操作deleteUser?id=1user/1–>delete请求方式
    更新操作updateUseruser–>put请求方式

    7.3、HiddenHttpMethodFilter

    由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?
    SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求
    HiddenHttpMethodFilter 处理putdelete请求的条件:

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

    满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数_method的值才是最终的请求方式

    <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filterclass>
    </filter>
    <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8


    目前为止,SpringMVC中提供了两个过滤器:CharacterEncodingFilter和HiddenHttpMethodFilter
    在web.xml中注册时,必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter
    原因

    • 在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字符集的
    • request.setCharacterEncoding(encoding) 方法要求前面不能有任何获取请求参数的操作
    • 而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作:
    • String paramValue = request.getParameter(this.methodParam);

    RESTful之测试查询功能

    web.xml

    
    <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_4_0.xsd"
             version="4.0">
    
        
        <filter>
            <filter-name>CharacterEncodingFilterfilter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
            <init-param>
                <param-name>forceEncodingparam-name>
                <param-value>trueparam-value>
            init-param>
        filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/url-pattern>
    filter-mapping>
    
        
        
        <servlet>
            <servlet-name>SpringMVCservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:springmvc.xmlparam-value>
            init-param>
            <load-on-startup>1load-on-startup>
        servlet>
        <servlet-mapping>
            <servlet-name>SpringMVCservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    springmvc.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mvv="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    
        
        <context:component-scan base-package="com.gao.controller"/>
        
        <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>
    
        
        <mvc:view-controller path="/" view-name="index">mvc:view-controller>
    
    
    
        
        <mvc:default-servlet-handler/>
        
        <mvc:annotation-driven>
            <mvc:message-converters>
                
                <bean
                        class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="defaultCharset" value="UTF-8" />
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/htmlvalue>
                            <value>application/jsonvalue>
                        list>
                    property>
                bean>
            mvc:message-converters>
        mvc:annotation-driven>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    RestfulController:

    package com.gao.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    /**
     * @Projectname SSM
     * @Filename RestfulController
     * @Author an
     * @Data 2022/8/5 9:42
     * @Description
     * 查询所有的用户信息--->/user--->get
     * 根据id查询用户信息--->/user/1--->get
     * 新增用户信息--->/user--->post
     * 删除用户信息--->/user/1--->delete
     * 更新用户信息--->/user--->put
     */
    @Controller
    public class RestfulController {
    
        @RequestMapping(value = "/user",method = RequestMethod.GET)
        public String getAllUser(){
            System.out.println("查询所有的用户信息--->/user--->get");
            return "success";
        }
    
        @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
        public String getUserById(@PathVariable("id") Integer id){
            System.out.println("根据id查询用户信息--->/user/"+id+"--->get");
            return "success";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    index.html

    <h1>index.html</h1>
    <a th:href="@{/user}">查询所有用户信息</a><br>
    <a th:href="@{/user/1}">查询用户信息1</a><br>
    
    • 1
    • 2
    • 3

    RESTful之处理post请求

    <form th:action="@{/user}" method="post">
        <input type="submit" value="添加用户信息">
    form>
    
    • 1
    • 2
    • 3
        @RequestMapping(value = "/user",method = RequestMethod.POST)
        public  String insertUser(){
            System.out.println("新增用户信息--->/user--->post");
            return "success";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    RESTful使用HiddenHttpMethodFilter处理put和delete请求

    web.xml

        
        <filter>
            <filter-name>HiddenHttpMethodFilterfilter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
        filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilterfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    put请求
    <form th:action="@{/user}" method="post">
        <input type="hidden" name="_method" value="put">
        <input type="submit" value="修改用户信息">
    form>
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

        @RequestMapping(value = "/user",method = RequestMethod.PUT)
        public  String iupdateUser(){
            System.out.println("更新用户信息--->/user--->put");
            return "success";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    delete请求

    <form th:action="@{/user/1}" method="post">
        <input type="hidden" name="_method" value="delete">
        <input type="submit" value="删除用户信息">
    form>
    
    • 1
    • 2
    • 3
    • 4
        @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
        public String deleteUserById(@PathVariable("id") Integer id){
            System.out.println("删除用户信息--->/user/"+id+"--->delete");
            return "success";
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    改进

    //    @RequestMapping(value = "/user",method = RequestMethod.GET)
        @GetMapping("/user")
        public String getAllUser(){
            System.out.println("查询所有的用户信息--->/user--->get");
            return "success";
        }
    
    //    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
        @GetMapping("/user/{id}")
        public String getUserById(@PathVariable("id") Integer id){
            System.out.println("根据id查询用户信息--->/user/"+id+"--->get");
            return "success";
        }
    
    //    @RequestMapping(value = "/user",method = RequestMethod.POST)
        @PostMapping("/user")
        public  String insertUser(){
            System.out.println("新增用户信息--->/user--->post");
            return "success";
        }
    
    //    @RequestMapping(value = "/user",method = RequestMethod.PUT)
        @PutMapping("/user")
        public  String iupdateUser(){
            System.out.println("更新用户信息--->/user--->put");
            return "success";
        }
    
    
    //    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
        @DeleteMapping("/user/{id}")
        public String deleteUserById(@PathVariable("id") Integer id){
            System.out.println("删除用户信息--->/user/"+id+"--->delete");
            return "success";
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    Android基础一:Android UI基础容器
    【Python】-- 文件的读写操作
    buuctf web [极客大挑战 2019]BabySQL
    有关<Python>的文件操作(上课笔记)
    学习ASP.NET Core Blazor编程系列十三——路由(完)
    SqlServer 数据库占用磁盘空间过大的解决方式
    ArcGIS QGIS学习二:图层如何只显示需要的部分几何面数据(附最新坐标边界下载全国省市区县乡镇)
    pytest框架中pytest.ini配置文件
    Redis高可用之持久化
    大数据时代下统计数据质量的影响因素
  • 原文地址:https://blog.csdn.net/qq_44774198/article/details/126170958