Spring Boot如何使用HiddenHttpMethodFilter [英] Spring Boot how to use HiddenHttpMethodFilter
问题描述
众所周知,表单仅支持 GET
或 POST
方法,如下所示:
As we all know, forms only support GET
or POST
methods, like this:
<form method="[GET|POST]" action="/user/create">
如果我们的控制器具有 PUT
映射,则会出现405错误,这意味着我们只能使用 GET
或 POST
,而不能使用 PUT
.
If our controller has a PUT
mapping, we get a 405 error, which means we can only use GET
or POST
but not 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中,我们可以解决此问题:
In spring MVC, we can solve this problem:
首先,创建一个隐藏字段,如下所示:
First, create a hidden field like this:
<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
方法.
In this way, we can use the PUT
method.
但是如何在Spring Boot中做到这一点?我知道Spring Boot有一个名为 WebMvcAutoConfiguration
的类,该类拥有方法 hiddenHttpMethodFilter
,但是如何使用该类?
But how can I do it in Spring Boot? I know Spring Boot have a class named WebMvcAutoConfiguration
which owns a method hiddenHttpMethodFilter
, but how can I use the class?
推荐答案
将以下内容添加到您的 application.properties
:
Add the following to your application.properties
:
spring.mvc.hiddenmethod.filter.enabled=true
这将自动配置 HiddenHttpMethodFilter
.
接下来,在表单上使用 th:method = DELETE
让Thymeleaf自动添加隐藏字段.
Next, use th:method=DELETE
on the form to have Thymeleaf add the hidden field automatically.
(Spring Boot< 2.2始终注册过滤器,对于Spring Boot 2.2或更高版本,您需要设置属性)
(Spring Boot < 2.2 always registers the filter, for Spring Boot 2.2 or higher you need to set the property)
这篇关于Spring Boot如何使用HiddenHttpMethodFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!