SpringBoot PUT和Delete请求

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot PUT和Delete请求

is.lizhichao   2022-09-08 我要评论

PUT和Delete请求使用

在Form表单中,只支持get和post方式,而为了实现put方式

我们可以通过如下三个步骤实现

1)SpringMVC中配置HiddenHttpMethodFilter

2)页面创建一个post表单

3)创建一个input项,name="_method",值就是指定的请求方式

其中在HiddenHttpMethodFilter类中

获取"_method"的值,得到新的请求方式。

<input type="hidden" name="_method" value="put" th:if="${employee!=null}"/>

其中th标签是thymeleaf模板,表示只有当employee不为空时才生效,而value中的put不区分大小写。

当时在新版本的SpringBoot中,这个put请求不发生作用。原因是因为springboot自动配置,帮我们省略了第一步的配置,上面代码方法就是为了实现自动配置,但是因为注解@ConditionalOnProperty限制了自动配置,默认false不开启配置,所以页面的put提交无法使用。

解决办法

properties配置文件中配置,使之开启自动配置: spring.mvc.hiddenmethod.filter.enabled=true。

此外,DELETE请求也可以同样这样设置。

<form th:action="@{/emp/}+${emp.id}" method="post">
	<input type="hidden" name="_method" value="delete"/>
	<button type="submit" class="btn btn-sm btn-danger" > 删除</button>
</form>

如何支持put/delete请求

学过mvc的都知道,想要支持这两种特殊的请求,首先就要在web.xml中配置下面的过滤器:

<!--增加一个HiddenHttpMethodFilter过滤器:目的是给普通浏览器 增加put|delete请求方式-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

而SpringBoot就没有这么麻烦了,因为他已经默认帮我们把HiddenHttpMethodFilter纳入到IOC容器中了,所以他的使用及其简单:

1.在application.properties中配置

#开启支持put delete请求的过滤器
spring.mvc.hiddenmethod.filter.enabled=true

2.使用时依旧和springmvc一样

只需要在post请求方式的form表单中加入下面的隐藏域:

     <!--http请求方式-->
     <form action="..."  method="post">
         <input type="hidden" name="_method" value="put" />
         <!--value值改成delete 请求方式就为delete了-->
     </form>

注意上面隐藏域的name必须为 “_method”,如果想要修改,则需要给IOC加入下面的bean:

@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
    HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
    methodFilter.setMethodParam("_m");//将隐藏域 _method --> _m
    return methodFilter;
} 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们