spring mvc 支持REST风格的请求方法,GET、POST、PUT和DELETE四种请求方法分别代表了数据库CRUD中的select、insert、update、delete,下面演示一个简单的REST实现过程。
参照http://blog.csdn.net/u011403655/article/details/44571287创建一个spring mvc工程
创建一个包,命名为me.elin.rest,添加一个RESTMethod类,代码如下
1 package me.elin.rect; 2 import org.springframework.stereotype.Controller; 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RequestMethod; 5 import org.springframework.web.bind.annotation.RequestParam; 6 @Controller 7 @RequestMapping("/rest") 8 public class RESTMethod { 9 private static final String SUCCESS = "success"; 10 // 该方法接受POST传值,请求url为/rest/restPost 11 @RequestMapping(value = "restPost", method = RequestMethod.POST) 12 public String restPost(@RequestParam(value = "id") Integer id) { 13 System.out.println("POST ID:" + id); 14 return SUCCESS; 15 } 16 // 该方法接受GET传值,请求url为/rest/restGet 17 @RequestMapping(value = "/restGet", method = RequestMethod.GET) 18 public String restGet(@RequestParam(value = "id") Integer id) { 19 System.out.println("GET ID:" + id); 20 return SUCCESS; 21 } 22 // 该方法接受PUT传值,请求url为/rest/restPut 23 @RequestMapping(value = "/restPut", method = RequestMethod.PUT) 24 public String restPut(@RequestParam(value = "id") Integer id) { 25 System.out.println("PUT ID:" + id); 26 return SUCCESS; 27 } 28 // 该方法接受DELETE传值,请求url为/rest/restDelete 29 @RequestMapping(value="/restDelete",method=RequestMethod.DELETE) 30 public String restDelete(@RequestParam(value = "id") Integer id) { 31 System.out.println("DELETE ID:" + id); 32 return SUCCESS; 33 } 34 }
在web.xml中添加一个filter,用来过滤rest中的方法。代码如下
1 <filter> 2 <filter-name>HiddenHttpMethodFilter</filter-name> 3 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>HiddenHttpMethodFilter</filter-name> 7 <url-pattern>/*</url-pattern> 8 </filter-mapping>
在WebContent下创建index.jsp文件,添加如下内容
1 <a href="rest/restGet?id=1">发送GET请求</a> 2 <form action="rest/restPost" method="post"> 3 <input type="text" name="id" value="2"/> 4 <input type="submit" value="发送POST请求"/> 5 </form> 6 <form action="rest/restPut" method="post"> 7 <input type="hidden" name="_method" value="PUT"> 8 <input type="text" name="id" value="3"> 9 <input type="submit" value="发送PUT请求"> 10 </form> 11 <form action="rest/restDelete" method="post"> 12 <input type="hidden" name="_method" value="DELETE"> 13 <input type="text" name="id" value="4"> 14 <input type="submit" value="发送DELETE请求"> 15 </form>
其中get和post方法是html中自带的,但是不支持PUT和DELETE方法,所以需要通过POST方法模拟这两种方法,只需要在表单中添加一个隐藏域,名为_method,值为PUT或DELETE。
运行程序,index.jsp中一个超链接和三个表单分别表示了四种请求方法。
时间: 2024-10-06 14:50:14