Spring REST

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页面可以这样写

<a href="user/1">GET请求</a>
 
<form action="user/1" method="post">
     <input type="submit" value="POST请求"/>
</form>

<form action="user/1" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="submit" value="PUT请求"/>
 </form>
 
 <form action="user/1" method="post">
    <input type="hidden" name="_method" value="DELETE">
    <input type="submit" value="DELET请求"/>
 </form> 

   web.xml配置过滤器

<filter>
     <filter-name>methodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
 </filter>
 
 <filter-mapping>
     <filter-name>methodFilter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>

   控制器

package com.proc;
 
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 
 @Controller
 public class User {
 
     @RequestMapping(value="user/{id}",method=RequestMethod.GET)
     public String get(@PathVariable("id") Integer id){
         System.out.println("获取用户:"+id);
         return "hello";
     }
     
     @RequestMapping(value="user/{id}",method=RequestMethod.POST)
     public String post(@PathVariable("id") Integer id){
         System.out.println("添加用户:"+id);
         return "hello";
     }
     
     @RequestMapping(value="user/{id}",method=RequestMethod.PUT)
     public String put(@PathVariable("id") Integer id){
         System.out.println("更新用户:"+id);
         return "hello";
     }
     
     @RequestMapping(value="user/{id}",method=RequestMethod.DELETE)
     public String delete(@PathVariable("id") Integer id){
         System.out.println("删除用户:"+id);
         return "hello";
     }
 }

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

获取用户:1
添加用户:1
更新用户:1
删除用户:1

 

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

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

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

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

 

本文转自:http://www.cnblogs.com/caoyc/p/5635354.html

posted @ 2018-04-09 16:35  Margaery  阅读(200)  评论(0编辑  收藏  举报