spring mvc 支持REST風格的請求方法,GET、POST、PUT和DELETE四種請求方法分別表明了數據庫CRUD中的select、insert、update、delete,下面演示一個簡單的REST實現過程。html
參照http://blog.csdn.net/u011403655/article/details/44571287建立一個spring mvc工程web
建立一個包,命名爲me.elin.rest,添加一個RESTMethod類,代碼以下spring
package me.elin.rect; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/rest") public class RESTMethod { private static final String SUCCESS = "success"; // 該方法接受POST傳值,請求url爲/rest/restPost @RequestMapping(value = "restPost", method = RequestMethod.POST) public String restPost(@RequestParam(value = "id") Integer id) { System.out.println("POST ID:" + id); return SUCCESS; } // 該方法接受GET傳值,請求url爲/rest/restGet @RequestMapping(value = "/restGet", method = RequestMethod.GET) public String restGet(@RequestParam(value = "id") Integer id) { System.out.println("GET ID:" + id); return SUCCESS; } // 該方法接受PUT傳值,請求url爲/rest/restPut @RequestMapping(value = "/restPut", method = RequestMethod.PUT) public String restPut(@RequestParam(value = "id") Integer id) { System.out.println("PUT ID:" + id); return SUCCESS; } // 該方法接受DELETE傳值,請求url爲/rest/restDelete @RequestMapping(value="/restDelete",method=RequestMethod.DELETE) public String restDelete(@RequestParam(value = "id") Integer id) { System.out.println("DELETE ID:" + id); return SUCCESS; } }
<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>
<a href="rest/restGet?id=1">發送GET請求</a> <form action="rest/restPost" method="post"> <input type="text" name="id" value="2"/> <input type="submit" value="發送POST請求"/> </form> <form action="rest/restPut" method="post"> <input type="hidden" name="_method" value="PUT"> <input type="text" name="id" value="3"> <input type="submit" value="發送PUT請求"> </form> <form action="rest/restDelete" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="text" name="id" value="4"> <input type="submit" value="發送DELETE請求"> </form>
其中get和post方法是html中自帶的,可是不支持PUT和DELETE方法,因此須要經過POST方法模擬這兩種方法,只須要在表單中添加一個隱藏域,名爲_method,值爲PUT或DELETE。數據庫