目录
  • restful风格
  • springboot中的使用
    • 1.创建html表单页面
    • 2.在yml配置文件中开启rest表单支持
    • 3.编写controller层及对应映射处理
    • 4.启动服务,逐个访问
  • 总结 

    restful风格

    Rest风格支持(使用HTTP请求方式动词来表示对资源的操作)

    • 以前:/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户
    • 现在: /user GET-获取用户 DELETE-删除用户 PUT-修改用户 POST-保存用户

    springboot中的使用

    1.创建html表单页面

    因为html表单只支持发送get和post请求,所以当发送delete,put请求时,需要设定一个隐藏域,其name值必须为_method,value值为表单的请求方式(且delete,put的表单的method为post请求)。

    用法: 表单method=post,隐藏域<input type="hidden" name="_method" value="PUT|DELETE">

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>首页</title>
    </head>
    <body>
        <form action="/user" method="get">
            <input type="submit" value="GET提交">
        </form>
        <hr>
        <form action="/user" method="post">
            <input type="submit" value="POST提交">
        </form>
        <hr>
        <form action="/user" method="post">
            <input type="hidden" name="_method" value="DELETE"><br>
            <input type="submit" value="DELETE提交">
        </form>
        <hr>
        <form action="/user" method="post">
            <input type="hidden" name="_method" value="PUT"><br>
            <input type="submit" value="PUT提交">
        </form>
    </body>
    </html>
    

    2.在yml配置文件中开启rest表单支持

    # RestFul风格开启,开启支持表单的rest风格
    spring:
      mvc:
        hiddenmethod:
          filter:
            enabled: true
    

    3.编写controller层及对应映射处理

    package com.robin.boot.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class RestTestController {
    
        @RequestMapping(value = "/user",method = RequestMethod.GET)
        public String getUser(){
            return "GET user , 获取用户成功";
        }
    
        @RequestMapping(value = "/user",method = RequestMethod.POST)
        public String saveUser(){
            return "POST user, 保存用户成功";
        }
    
        @RequestMapping(value = "/user",method = RequestMethod.DELETE)
        public String delUser(){
            return "DELETE user, 删除用户成功";
        }
    
        @RequestMapping(value = "/user",method = RequestMethod.PUT)
        public String updateUser(){
            return "PUT user, 修改用户成功";
        }
    }

    4.启动服务,逐个访问

    springboot中restful风格请求的使用方法示例

    访问成功,对同一请求/user实现了,不同方式提交的不同处理。

    springboot中restful风格请求的使用方法示例

    springboot中restful风格请求的使用方法示例

    springboot中restful风格请求的使用方法示例

    springboot中restful风格请求的使用方法示例

    总结 

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。