【SpringBoot】请求参数处理 —— Rest使用与原理

前言

Rest 方式可以发送 GET 、POST、PUT、DELETE 等方式的请求。但是表单只能GET提交或POST提交,通过 HiddenHttpMethodFilter 拦截器可以处理PUT、DELETE请求。本文主要介绍拦截器的使用。
其他的客户端工具,可以直接发送各种请求方式,因此无需filter做转换。因此,filter功能是选择性开启,不是一定要开启的。

一、Controller类
package com.example.demo.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloCotroller {

    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String getUser(){
        return "GET-张三";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String saveUser(){
        return "POST-张三";
    }


    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String putUser(){
        return "PUT-张三";
    }

    // @RequestMapping(value = "/user",method = RequestMethod.DELETE)
    @DeleteMapping(value = "/user")
    public String deleteUser(){
        return "DELETE-张三";
    }

}

  1. Delete请求两种写法——其他请求同理
@DeleteMapping(value = "/user")
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
二、配置文件
spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true #开启表单的filter功能
三、请求写法

在post请求中加入

<input type="hidden" name="_method" value="delete">

完整代码:

<!--HiddenHttpMethodFilter拦截-->
<form action="/user" method="post">
    <!--获取_method的值 value大小写都行,自动转为大写 容许的只有delete put  patch-->
    <input type="hidden" name="_method" value="delete">
    <input type="submit" value="REST-DELETE 提交">
</form>
四、自定义 _method 名字
  1. 自定义Filter
    创建一config包 —— 在config包下定义WebMvcConfigurer类
//自定义filter
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;

@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        methodFilter.setMethodParam("_myMethod");
        return methodFilter;
    }
}

Filter原理

● 表单提交会带上_method=PUT (大小写都可以)
● 请求被HiddenHttpMethodFilter拦截
1. 判断请求是否正常,并且是POST类请求
■ 获取到_method的值(value)
■ 兼容以下请求;PUT.DELETE.PATCH
■ 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值
■ 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。


请求映射原理
源码:
org.springframework.web.servlet.DispatcherServlet —— doDispatch()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值