Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot how to use HiddenHttpMethodFilter

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?

like image 209
diligent Avatar asked Mar 23 '26 09:03

diligent


1 Answers

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

  • For Spring Boot < 2.2 always registers the filter
  • For Spring Boot 2.2 or higher you need to set the property
like image 192
Wim Deblauwe Avatar answered Mar 25 '26 23:03

Wim Deblauwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!