springmvc 03 HiddenHttpMethodFilter(rest模拟操作)

示例:

/order/1 HTTP GET:得到id=1的order
/order/1 HTTP DELETE:删除id=1的order
/order/1 HTTP PUT:更新id=1的order
/order/ HTTP POST:新增order

HiddenHttpMethodFilter:
浏览器form表单只支持GET,POST请求,而DELETE,PUT等method并不支持,Spring3.0添加了一个过滤器,可以把POST请求转为DELETE,PUT请求使得支持GET,POST,PUT,DELETE请求;

步骤:
  1. web.xml中添加HiddenHttpMethodFilter
<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>
  1. 前端表单添加隐藏域
    <form action="springmvc/testRest/1" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <button type="submit">testRest-DELETE</button>
    </form><br>
    
    <form action="springmvc/testRest/2" method="post">
        <input type="hidden" name="_method" value="PUT">
        <button type="submit">testRest-PUT</button>
    </form><br>
    
    <form action="springmvc/testRest/3" method="post">
        <button type="submit">testRest-POST</button>
    </form><br>
    
    <a href="springmvc/testRest/4">testRest-GET</a>
public class Rest {
    private String SUCCESS = "success";
    
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
    public String testRest_delete(@PathVariable("id") Integer id){
        System.out.println("删除成功:"+id);
        return SUCCESS;
    }
    
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
    public String testRest_put(@PathVariable("id") Integer id){
        System.out.println("更新成功:"+id);
        return SUCCESS;
    }
    
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.POST)
    public String testRest_post(@PathVariable("id") Integer id){
        System.out.println("添加成功:"+id);
        return SUCCESS;
    }
    
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
    public String testRest_get(@PathVariable("id") Integer id){
        System.out.println("获取成功:"+id);
        return SUCCESS;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容