Spring REST(4)

REST风格

  /user/1    get请求    获取用户

  /user/1  post请求    新增用户

  /user/1  put请求      更新用户

  /user/1  delete请求  删除用户

 

在Spring MVC中如何提交put和delete请求呢?

  需要在web.xml文件中配置一个HiddenHttpMethodFilter过滤器。该过滤过滤post请求,如果在post请求中有个一个_method参数,那么_method参数值就是请求方式。所以在jsp页面可以这样写

复制代码
 1 <a href="user/1">GET请求</a>  2  3 <form action="user/1" method="post">  4 <input type="submit" value="POST请求"/>  5 </form>  6  7 <form action="user/1" method="post">  8 <input type="hidden" name="_method" value="PUT">  9 <input type="submit" value="PUT请求"/> 10 </form> 11 12 <form action="user/1" method="post"> 13 <input type="hidden" name="_method" value="DELETE"> 14 <input type="submit" value="DELET请求"/> 15 </form
复制代码

  web.xml配置过滤器

复制代码
1 <filter>
2     <filter-name>methodFilter</filter-name> 3 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 4 </filter> 5 6 <filter-mapping> 7 <filter-name>methodFilter</filter-name> 8 <url-pattern>/*</url-pattern> 9 </filter-mapping>
复制代码

  控制器

复制代码
 1 package com.proc;
 2 
 3 import org.springframework.stereotype.Controller;  4 import org.springframework.web.bind.annotation.PathVariable;  5 import org.springframework.web.bind.annotation.RequestMapping;  6 import org.springframework.web.bind.annotation.RequestMethod;  7  8 @Controller  9 public class User { 10 11 @RequestMapping(value="user/{id}",method=RequestMethod.GET) 12 public String get(@PathVariable("id") Integer id){ 13 System.out.println("获取用户:"+id); 14 return "hello"; 15  } 16 17 @RequestMapping(value="user/{id}",method=RequestMethod.POST) 18 public String post(@PathVariable("id") Integer id){ 19 System.out.println("添加用户:"+id); 20 return "hello"; 21  } 22 23 @RequestMapping(value="user/{id}",method=RequestMethod.PUT) 24 public String put(@PathVariable("id") Integer id){ 25 System.out.println("更新用户:"+id); 26 return "hello"; 27  } 28 29 @RequestMapping(value="user/{id}",method=RequestMethod.DELETE) 30 public String delete(@PathVariable("id") Integer id){ 31 System.out.println("删除用户:"+id); 32 return "hello"; 33  } 34 }
复制代码

  我们一次点击GET请求、POST请求、PUT请求和DELETE请求

扫描二维码关注公众号,回复: 2840257 查看本文章
获取用户:1
添加用户:1
更新用户:1
删除用户:1

【总结】:发出PUT请求和DELET请求的步骤

  1、在发出请求时必须是POST请求

  2、在POST请求中添加一个名为_method的参数,其值用来指定是PUT请求还是DELETE请求

  3、配置HiddenHttpMethodFilter过滤器。该过滤器的作用是POST请求可以转换成PUT或DELET请求

猜你喜欢

转载自www.cnblogs.com/weiqingfeng/p/9498161.html
今日推荐