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?
spring.mvc.hiddenmethod.filter.enabled=true
in yourapplication.properties
to enable it again. – MertzHiddenHttpMethodFilter
opens your application to a whole bunch of new CSRF attacks. Be sure you have other means of blocking requests from external forms. And no, CORS does not work for forms. – Thomasinathomasine