SpringBoot的使用HiddenHttpMethodFilter组件无法将POST转换为PUT请求解决办法

解决办法点这里

今天在学SpringBoot的时候遇到了由于starter版本1和2不同造成的小坑:

由于H5的form表单仅支持POST和GET两种请求,实现restfulAPI还需要PUT和DELETE,所以需要使用 HiddenHttpMethodFilter 组件在发送HTTP请求时对请求类型进行伪装:

<form action="/emp" method="post">
    <input type="hidden" name="_method" value="put"/>

该组件SpringBoot已经自动配置好,无需再@Bean组件,但自己用的时候却老是无法映射到Controller里对应的PUT请求,然后去瞄了眼webmvc的自动配置类:

@Bean
@ConditionalOnMissingBean({HiddenHttpMethodFilter.class})
@ConditionalOnProperty(
    prefix = "spring.mvc.hiddenmethod.filter",
    name = {"enabled"},
    matchIfMissing = false
)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
    return new OrderedHiddenHttpMethodFilter();
}

​发现较先前版本多了@ConditionalOnProperty的注解,也就是条件引入。查看括号内的内容可以知道,这个组件是否加入容器决定于这个属性,再看下SpringBoot配置的元数据对这个property的说明

{
      "name": "spring.mvc.hiddenmethod.filter.enabled",
      "type": "java.lang.Boolean",
      "description": "Whether to enable Spring's HiddenHttpMethodFilter.",
      "defaultValue": false
},

可以知道SpringBoot仅在"spring.mvc.hiddenmethod.filter.enabled"这个property的值为true时才会引入这个组件,但SpringBoot默认该属性值为false,所以该版本这个组件是默认没有加入容器的



所以我们只需在配置文件里加上这一句:
spring.mvc.hiddenmethod.filter.enabled = true

这样POST请求就可以成功转换成PUT和DELETE请求啦

你可能感兴趣的:(SpringBoot)