Spring MVC 使用HiddenHttpMethodFilter配置Rest风格的URL
/** Rest 风格的 URL. 以 CRUD 为例: 新增: /order POST 修改: /order/1 PUT update?id=1 获取:/order/1 GET get?id=1 删除: /order/1 DELETE delete?id=1 如何发送 PUT 请求和 DELETE 请求呢 ? 1. 需要在web.xml文件中配置 HiddenHttpMethodFilter <!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 请求转为 DELETE 或 POST 请求 --> <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> 2. 需要发送 POST 请求 3. 需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT jsp文件如下: <form action="springmvc/testRest/1" method="post"> <input type="hidden" name="_method" value="PUT"/> <input type="submit" value="TestRest PUT"/> </form> <br><br> <form action="springmvc/testRest/1" method="post"> <input type="hidden" name="_method" value="DELETE"/> <input type="submit" value="TestRest DELETE"/> </form> <br><br> <form action="springmvc/testRest" method="post"> <input type="submit" value="TestRest POST"/> </form> <br><br> <a href="springmvc/testRest/1">Test Rest Get</a> <br><br> 在 SpringMVC 的目标方法中如何得到 id 呢? 使用 @PathVariable 注解 */ @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT) public String testRestPut(@PathVariable Integer id) { System.out.println("testRest Put: " + id); return SUCCESS; } @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE) public String testRestDelete(@PathVariable Integer id) { System.out.println("testRest Delete: " + id); return SUCCESS; } @RequestMapping(value = "/testRest", method = RequestMethod.POST) public String testRest() { System.out.println("testRest POST"); return SUCCESS; } @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET) public String testRest(@PathVariable Integer id) { System.out.println("testRest GET: " + id); return SUCCESS; } /** * @PathVariable 可以来映射 URL 中的占位符到目标方法的参数中. * @param id * @return */ @RequestMapping("/testPathVariable/{id}") public String testPathVariable(@PathVariable("id") Integer id) { System.out.println("testPathVariable: " + id); return SUCCESS; } @RequestMapping("/testAntPath/*/abc") public String testAntPath() { System.out.println("testAntPath"); return SUCCESS; }
本文来自博客园,作者:wzyy,转载请注明原文链接:https://www.cnblogs.com/wwzyy/p/5838785.html
分类:
探索Spring之美
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix