[JAVA] Handle HTTP PUT / DELETE methods in SpringBoot2.2 + Thymeleaf

Spring MVC Controller can handle PUT / DELETE as HTTP methods, but HTML5 still can't handle these HTTP methods. So far to fill this gap

--Controller mapping defines mapping to PUT / DELETE method

Controller.java


@Controller
@RequestMapping("/item")
public class ItemController {
    ...
    @DeleteMapping("{id}")
    public String delete(@PathVariable("id") Long id) {
        service.delete(id);
        return "redirect:/item";
    }
}

--If you define the form of put / delete method on the thymeleaf side, replace it with post and embed a hidden parameter called _method.

template.html


<form th:action="@{/item/{id}(id=*{id})}" th:method="delete">
    <input type="submit" value="delete" />
</form>

rendered.html


<form action="/item/1" method="post">
    <input type="hidden" name="_method" value="delete" />
    <input type="submit" value="delete" />
</form>

--When this hidden parameter is detected by a filter called HiddenHttpMethodFilter, the request method is replaced.

I was taking the approach.

Until SpringBoot 2.1, this HiddenHttpMethodFilter was enabled by default AutoConfiguration, so it was available without any special awareness, but from SpringBoot 2.2, the default behavior has changed and it seems that it has been turned off.

Spring Boot 2.2 Release Notes: HttpHiddenMethodFilter disabled by default

According to the release notes

it causes early consumption of a request body if the body may contain parameters.

So I couldn't understand what early consumption means, but I wonder if the overhead of biting the filter for what I want to do is more of a disadvantage. There is no sign that HTML supports PUT / DELETE, and it may be that there is no need to force the PUT / DELETE method from an HTML website that is not a REST API.

If you want to use HttpHiddenMethodFilter, you can enable it in Configuration.

application.yml


spring.mvc.hiddenmethod.filter.enabled: true

You can now use the PUT / DELETE methods from HTML as before. However, shouldn't we use the fact that Spring Boot is disabled by default?

Postscript

Why was it removed from the default? About that point. It was discussed around the following issue.

https://github.com/spring-projects/spring-boot/issues/16953 https://github.com/spring-projects/spring-boot/issues/18088

Roughly summarized

--Not required if you use it as an API without using a template engine --The filter is taking a long time to process when MultipartFile is included in the request parameter --When an error exceeding MaxUploadSize occurs, Filter throws an error, so MVC cannot handle it.

That seems to be the reason. Based on this, it seems good to enable it when there is no problem.

Recommended Posts

Handle HTTP PUT / DELETE methods in SpringBoot2.2 + Thymeleaf
Draw screen with Thymeleaf in SpringBoot
Put the image obtained from http in NotificationCompat