Rest 風格的 URL. 以 CRUD 為例: 新增: /order POST 修改: /order/1 PUT update?id=1 獲取:/order/1 GET get?id=1 刪除: /order/1 DELETE delete?id=1、
瀏覽器只支持Post和get的方式,想要實現delete和put的方式,需要使用過濾器HiddenHttpMethodFilter
1,配置過濾器
<filter> <filter-name>hidden</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hidden</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2,在客戶端發起請求
過濾器使用_method的這個參數來決定過濾成是什么類型的,因此,需要在前端的提交表單里面加上_method的隱藏域,注意要使用post方法進行提交
<form action="/rest/12" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="submit" value="delete"> </form> <form action="/rest/12" method="post"> <input type="hidden" name="_method" value="PUT"> <input type="submit" value="put"> </form> <form action="/rest/12" method="post"> <input type="submit" value="post"> </form> <form action="/rest/12" method="get"> <input type="submit" value="get"> </form>
3,后端控制器的編寫
控制器直接使用RequestMapping來指定方法就可以了
@RequestMapping(value = "/rest/{id}",method = RequestMethod.DELETE) public String testrestDELETE(@PathVariable int id, Model model){ model.addAttribute("msg","delete請求"+id); return SUCCESS; } @RequestMapping(value = "/rest/{id}",method = RequestMethod.PUT) public String testrestPUT(@PathVariable int id,Model model){ model.addAttribute("msg","put請求"+id); return SUCCESS; } @RequestMapping(value = "/rest/{id}",method = RequestMethod.POST) public String testrestPOST(@PathVariable int id,Model model){ model.addAttribute("msg","post請求"+id); return SUCCESS; } @RequestMapping(value = "/rest/{id}",method = RequestMethod.GET) public String testrestDELETE(@PathVariable int id, ModelMap modelMap){ modelMap.addAttribute("msg","get請求"+id); return SUCCESS; }
特別注意!!!!!!!!!!!!!
在tomcat8上面是不支持delete和post請求的,因此以上只能在tomcat7上面執行
tomcat8運行時可以進入到相應的控制器,但是視圖渲染返回的時候,由於不支持這兩種方法,就會報出異常頁面