SpringMVC RestFul方式提交

来源:互联网 发布:淘宝潮流女装店铺 编辑:程序博客网 时间:2024/06/16 00:28

先来说下什么是RestFul的请求方式

在 REST 样式的 Web 服务中,每个资源都有一个地址。资源本身都是方法调用的目标,方法列表对所有资源都是一样的。这些方法都是标准方法,包括 HTTP GET、POST、PUT、DELETE,还可能包括 HEADER 和 OPTIONS

GET: testRest/1 – 获取资源,id=1
POST: testRest –新增资源
PUT: testRest/1 –修改资源,id=1
DELETE: testRest/1 –删除资源,id=1
传统的Form表单只支持GET和Post方式,SpringMVC提供了一个过滤器HiddenHttpMethodFilter,可以将页面标识的put和delete方式转换为RestFul方式

配置HiddenHttpMethodFilter

这里使用JavaConfig配置,在web.xml中也可以配置

public class SplitterWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {    protected Class<?>[] getRootConfigClasses() {        return new Class<?>[]{RootConfig.class};    }    protected Class<?>[] getServletConfigClasses() {        return new Class<?>[]{WebConfig.class};    }    protected String[] getServletMappings() {        return new String[]{"/"};    }    @Override    protected Filter[] getServletFilters() {        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();        return new Filter[]{hiddenHttpMethodFilter};    }}

AbstractAnnotationConfigDispatcherServletInitializerWebApplicationInitializer 的子类,如果要用JavaConfig来配置SpringMVC,需要继承
AbstractAnnotationConfigDispatcherServletInitializer
或实现接口WebApplicationInitializer

定义对应的方法

使用RestFul风格的话要用注解@PathVariable和占位符,占位符中的名称必须和@PathVariable中的value值一致

   @RequestMapping(value = "/testRest/{id}",method = RequestMethod.GET)    public String testRest(@PathVariable(value = "id") Integer id){        System.out.println("testRest的GET:"+id);        return "info";    }    @RequestMapping(value = "/testRest",method = RequestMethod.POST)    public String testRest(){        System.out.println("testRest的POST:");        return "info";    }    @RequestMapping(value = "/testRest/{id}",method = RequestMethod.DELETE)    public String testRestDelete(@PathVariable(value = "id") Integer id){        System.out.println("testRest的DELETE:"+id);        return "info";    }    @RequestMapping(value = "/testRest/{id}",method = RequestMethod.PUT)    public String testRestPut(@PathVariable(value = "id") Integer id){        System.out.println("testRest的Put:"+id);        return "info";    }

上面定义了4中方式对应的处理方法

用form表单实现PUT,POST,DELETE,GET

GET提交

<a href="splitter/testRest/1">splitter/testRest/1</a><P></P>

POST提交

 <form action="splitter/testRest" method="post">       <input type="submit" value="提交POST"/> </form>

PUT提交
注意不能直接在form的method=”put”,这样浏览器是不支持的,使用一个隐藏域,它的value指定RestFul的方式,当springmvc的过滤器收到后,再进行相关转换

<form action="splitter/testRest/1" method="post">    <input type="hidden" name="_method" value="PUT"/>    <input type="submit" value="提交put"/></form>

DELET提交

<form action="splitter/testRest/1" method="post">    <input type="hidden" name="_method" value="DELETE"/>    <input type="submit" value="提交DELETE"/></form>
0 0
原创粉丝点击