As we all know, forms only support GET or POST methods, like this:
<form method="[GET|POST]" action="/user/create">
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;
}
}
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"/>
Second, add a filter
<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>
In this way, we can use the PUT method.
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?
Add the following to your application.properties file:
spring.mvc.hiddenmethod.filter.enabled=true
This will automatically configure the HiddenHttpMethodFilter class.
Next, use th:method="DELETE" on the form to have Thymeleaf add the hidden field automatically.
Note
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With