Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add the following to your application.properties:

spring.mvc.hiddenmethod.filter.enabled=true

This will automatically configure the HiddenHttpMethodFilter.

Next, use th:method=DELETE on the form to have Thymeleaf add the hidden field automatically.

(Spring Boot < 2.2 always registers the filter, for Spring Boot 2.2 or higher you need to set the property)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...