restful风格中的put请求和delete请求的用法

xiaoxiao2021-02-28  159

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。

[html] view plain copy print ? <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>   控制器:

[html] view plain copy print ?        @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";  }   请求页面:

[html] view plain copy print ? <!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

转载请注明原文地址: https://www.6miu.com/read-53761.html

最新回复(0)