Spring Boot 如何使用 HiddenHttpMethodFilter

dil*_*ent 4 java spring spring-mvc spring-boot

众所周知,表单只支持GETPOST方法,像这样:

<form method="[GET|POST]" action="/user/create">
Run Code Online (Sandbox Code Playgroud)

如果我们的控制器有PUT映射,我们会得到 405 错误,这意味着我们只能使用GETorPOST而不能使用PUT

public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/create", method = RequestMethod.PUT)
    public ModelAndView createUser(@ModelAttribute("user") Users user, BindingResult bindingResult){
        ModelAndView mv = new ModelAndView("list");
        // do something...
        return mv;
    }
}
Run Code Online (Sandbox Code Playgroud)

在spring MVC中,我们可以解决这个问题:

首先,创建一个像这样的隐藏字段:

<form method="[GET|POST]" action="/user/create">
    <input type="hidden" name="_method" value="put"/>
Run Code Online (Sandbox Code Playgroud)

二、添加过滤器

<filter>  
    <filter-name>HiddenHttpMethodFilter</filter-name>  
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>  
</filter>  

<filter-mapping>  
    <filter-name>HiddenHttpMethodFilter</filter-name>  
    <servlet-name>springmvc</servlet-name>  
</filter-mapping>     
Run Code Online (Sandbox Code Playgroud)

这样,我们就可以使用PUT方法了。

但是我怎么能在 Spring Boot 中做到这一点呢?我知道 Spring Boot 有一个名为的类WebMvcAutoConfiguration,它拥有一个方法hiddenHttpMethodFilter,但我如何使用该类?

Wim*_*uwe 6

将以下内容添加到您的application.properties:

spring.mvc.hiddenmethod.filter.enabled=true
Run Code Online (Sandbox Code Playgroud)

这将自动配置HiddenHttpMethodFilter.

接下来,th:method=DELETE在表单上使用让 Thymeleaf 自动添加隐藏字段。

(Spring Boot < 2.2 总是注册过滤器,对于 Spring Boot 2.2 或更高版本你需要设置该属性)

  • [更新]@Deblauwe。我使用 Spring boot 2.7.0。我在 application.yaml 中输入了 th:method="delete" 和 atDeleteMapping 以及 : "spring.mvc.hiddenmethod.filter.enabled=true" 的形式,但它不起作用。它说“不支持请求方法帖子”。有什么想法吗?最新的 Spring boot 版本不支持它。提前致谢 (2认同)

小智 5

我不久前处理过这个问题。你只需要在任何@Configuration类下和一个 Bean 。如:
添加 HiddenHttpMethodFilter

然后,您可以在表单上使用删除请求。如:
在表单上使用删除请求

  • 如果您使用 Spring Boot,请将 spring.mvc.hiddenmethod.filter.enabled=true 添加到 application.properties 以避免手动 bean 配置。如果您使用 Thymeleaf 作为模板,则可以使用 `th:method="DELETE"` 让 Thymeleaf 自动添加隐藏字段。 (4认同)