SpringMVC——将Get和Post请求转为Delete和Put请求
一、在web.xml文件中配置过滤器org.springframework.web.filter.HiddenHttpMethodFilter
<!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 --> <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>
二、将Get请求转为Delete请求
对于put
、delete
请求的时候使用post
方式请求,同时增加一个参数_method=delete
,定义实际的请求方式
前端代码:
<!--一个删除链接,为get请求--> <a class="delete" href="emp/${emp.id}">Delete</a> <!--利用js,将get请求转为DELETE请求--> <script type="text/javascript"> $(function() { alert("hello"); $(".delete").click(function(){ var href=$(this).attr("href"); $("form").attr("action",href).submit(); return false; }); }); </script> <!--DELETE请求细节--> <form action="" method="POST"> <input type="hidden" name="_method" value="DELETE" > </form>
后端代码:
<!--接收DELETE请求的细节--> @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE) public String delete(@PathVariable("id") Integer id){ System.out.print(employeeDao.delete(id)); return "redirect:/emps"; }
三、Post请求转为Put请求
前端代码:
<form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee"><br> <c:if test="${employee.id == null }"> <!-- path 属性对应 html 表单标签的 name 属性值 --> LastName: <form:input path="lastName"/> <form:errors path="lastName"></form:errors> </c:if> <c:if test="${employee.id != null }"> <form:hidden path="id"/> <!-- 将POST请求转化为PUT请求 --> <input type="hidden" name="_method" value="PUT"/> </c:if> <br> Email: <form:input path="email"/> <input type="submit" value="Submit"/> </form:form>
后端将method=RequestMethod.PUT