Restful风格中put请求和delete请求
Restful风格中的CRUD:
增加:/result POST、修改:/result/1 PUT、获取:/result/1 GET、删除:/result/1 DELETE
范例:
web.xml中配置org.springframework.web.filter.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>
- @RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
- public String testRest(@PathVariable("id") Integer id){
- System.out.println("testRestGet:"+id);
- return "success";
- }
- @RequestMapping(value="/testRest",method=RequestMethod.POST)
- public String testRest(){
- System.out.println("testRestPost");
- return "success";
- }
- @RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
- public String testRestDelete(@PathVariable("id") Integer id){
- System.out.println("testRestDelete:"+id);
- return "success";
- }
- @RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
- public String testRestPut(@PathVariable("id") Integer id){
- System.out.println("testRestPut:"+id);
- return "success";
- }
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>index</title>
- </head>
- <body>
- <a href="SpringAnnotation/testRest/1">TestRestGet</a>
- <br/><br/>
- <form action="SpringAnnotation/testRest" method="post">
- <input type="submit" value="TestRestPost"/>
- </form>
- <br/><br/>
- <form action="SpringAnnotation/testRest/1" method="post">
- <input type="hidden" name="_method" value="DELETE"/>
- <input type="submit" value="TestRestDelete"/>
- </form>
- <br/><br/>
- <form action="SpringAnnotation/testRest/1" method="post">
- <input type="hidden" name="_method" value="PUT"/>
- <input type="submit" value="TestRestPut"/>
- </form>
- </body>
- </html>
如何发送DELETE和PUT请求?
(1). 需要配置 HiddenHttpMethodFilter (2). 需要发送 POST 请求(3). 需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT