什麼是Rest風格的url請求方式
REST功能是Spring MVC 3.0新增的,它通過不帶擴展名的URL來訪問系統資源。是一種設計模式,目的就是簡化url地址的書寫方式。
例子(前後對比)
以前的url地址
/queryBook?id=1 查詢1號圖書
/addBook 增加圖書
/updateBook?id=1... 更新1號圖書
/deleteBook?id=1 刪除1號圖書
rest風格的url地址
/資源名/資源標識符 以什麼方式發送請求,就執行什麼樣的操作
/book/1 GET---查詢1號
/book/1 DELETE---刪除1號
/book/1 PUT---更新1號
/book POST---增加圖書
如何使用
我們都知道頁面只能發送get和post兩種請求,那麼如何增加其他兩個呢?Spring爲我們提供了rest風格的支持
1、配置web.xml
SpringMVC中有一個Filter;他可以把普通的請求轉化爲規定形式的請求;配置這個filter
<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、創建一個post類型的表單 2、表單項中攜帶一個_method的參數,3、這個_method的值設爲DELETE、PUT
<a href="book/1">查詢圖書</a><br/>
<form action="book" method="post">
<input type="submit" value="添加1號圖書"/>
</form><br/>
<!-- 發送DELETE請求 -->
<form action="book/1" method="post">
<input name="_method" value="delete"/>
<input type="submit" value="刪除1號圖書"/>
</form><br/>
<!-- 發送PUT請求 -->
<form action="book/1" method="post">
<input name="_method" value="put"/>
<input type="submit" value="更新1號圖書"/>
</form><br/>
異常處理
只需要在jsp頁面添加異常處理即可