如何在Spring Boot中正确注册HiddenHttpMethodFilter?

时间:2018-06-18 16:03:25

标签: spring-boot

我正在关注一个教程,其中包含HiddenHttpMethodFilter的以下注册码。它使用@Bean注释返回一个新实例:

@SpringBootApplication
public class ReactiveWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReactiveWebApplication.class, args);
    }

    @Bean
    HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new HiddenHttpMethodFilter();
    }
}

然而,这对我来说似乎不起作用?我有一个表格:

<form method="post" action="/images/Picture of me 1.png" ><input type="hidden" name="_method" value="delete"/>
    <input type="submit" value="Delete" />
</form>

和请求处理程序:

@DeleteMapping(value = BASE_PATH + "/" + FILENAME)
public Mono<String> deleteFile(@PathVariable String filename) {
    return imageService.deleteImage(filename).then(Mono.just("redirect:/"));
}

但是服务器没有将POST请求重定向到我的deleteFile方法:

2018-06-18 10:47:59.486  WARN 16344 --- [ctor-http-nio-5] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [POST http://localhost:8080/images/Picture%20of%20me%201.png]: Response status 405 with reason "Request method 'POST' not supported"

如果我将@DeleteMapping更改为@PostMapping,那么它是否有效,这让我怀疑HiddenHttpMethodFilter没有开始?

2 个答案:

答案 0 :(得分:1)

好的,终于明白了。原来有两种可能的导入方式:

import org.springframework.web.filter.reactive.HiddenHttpMethodFilter

import org.springframework.web.filter.HiddenHttpMethodFilter;

并且我选择了错误的(第二个)。我想在开发反应式Web项目时,您需要导入第一个项目。我希望他们对班级的命名有所不同。发布此答案,以防其他人陷入同一陷阱。

答案 1 :(得分:0)

在Spring Boot中,可以使用spring.mvc.hiddenmethod.filter.enabled属性启用HiddenHttpMethodFilter

spring.mvc.hiddenmethod.filter.enabled

false

是否启用Spring的HiddenHttpMethodFilter。

将其添加到application.properties / yaml文件并将其设置为truespring.mvc.hiddenmethod.filter.enabled=true

Documentation