dil*_*ent 4 java spring spring-mvc spring-boot
众所周知,表单只支持GET或POST方法,像这样:
<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,但我如何使用该类?
将以下内容添加到您的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 或更高版本你需要设置该属性)
小智 5
我不久前处理过这个问题。你只需要在任何@Configuration类下和一个 Bean 。如:

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

| 归档时间: |
|
| 查看次数: |
9796 次 |
| 最近记录: |