【问题标题】:Spring Boot how to use HiddenHttpMethodFilterSpring Boot如何使用HiddenHttpMethodFilter
【发布时间】:2016-03-07 00:59:15
【问题描述】:

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

<form method="[GET|POST]" action="/user/create">

如果我们的控制器有一个PUT 映射,我们会得到一个405 错误,这意味着我们只能使用GETPOST 而不能使用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;
    }
}

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

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

<form method="[GET|POST]" action="/user/create">
    <input type="hidden" name="_method" value="put"/>

其次,添加过滤器

<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>     

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

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

【问题讨论】:

  • 你不需要做任何事情,因为 Spring Boot 会自动为你配置隐藏的 http 方法过滤器
  • @AndyWilkinson 非常感谢。我编辑了我的问题,但是如果我不配置隐藏的 http 方法过滤器,我该如何使用 html 表单中的 put 提交。
  • 像往常一样。只需将元素放入表单中...
  • 从 Spring Boot 2.2 开始,过滤器不再自动配置。在您的application.properties 中设置spring.mvc.hiddenmethod.filter.enabled=true 以再次启用它。
  • 请注意,使用 HiddenHttpMethodFilter 会使您的应用程序面临一大堆新的 CSRF 攻击。确保您有其他方法可以阻止来自外部表单的请求。不,CORS 不适用于表单。

标签: java spring spring-mvc spring-boot


【解决方案1】:

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

spring.mvc.hiddenmethod.filter.enabled=true

这将自动配置HiddenHttpMethodFilter

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

(Spring Boot

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如果您使用 Spring Boot,请将 spring.mvc.hiddenmethod.filter.enabled=true 添加到您的 application.properties 以避免手动配置 bean。如果您使用 Thymeleaf 作为模板,您可以使用 th:method="DELETE" 让 Thymeleaf 自动添加隐藏字段。
    • @WimDeblauwe 你的评论值得更多的支持,为我工作!
    • 现在把它变成一个单独的答案,以便于投票:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2023-03-16
    • 2021-09-27
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多