RESTful架構,REST即Representational State Transfer。表現層狀態轉換,就是目前最流行的一種互聯網軟件架構。它結構清晰、符合標準、易於理解、擴展方便,因此獲得愈來愈多網站的採用。前端
RESTful其實就是一個開發理念,是對http的很好詮釋。web
RESTful遵循的理念:
一、對url進行規範,書寫爲RESTful格式的url。
二、對http的方法規範。
三、對http的contentType進行規範。請求時指定contentType,須要Json數據,設置成Json格式的type
非REST的url:http://.../goods/queryGoods.action?id=1
REST的url:http://.../goods/1spring
REST的url特色:服務器
url簡潔,將參數經過url傳到服務器。不管是增(post)、刪(delete)、該(put)、查(get)使用url是一致的,且須要設置對象的http方法。然後臺的controller方法,則須要判斷http方法。架構
//REST實例:查詢返回Json @RequestMapping("/goodsView/{id}") public @ResponseBody GoodsCustom goodsView(@PathVariable("id") Integer id)throws Exception{ GoodsCustom goodsCustom=...... return goodsCustom; }
URL模板映射:mvc
@RequestMapping("/goodsView/{id}"):{XXX}是佔位符,請求的URL能夠是「/goodsView/1」或「/goodsView/2」,經過在方法中使用@PathVariable獲取{XXX}中的XXX變量。app
@PathVariable用於將請求URL中的模板變量映射到功能處理方法的參數上。post
使用URL模板映射須要配置REST的前端控制器。在web.xml中配置前端控制器:網站
<!-- springmvc的REST前端控制器 和springmvc前端控制器能夠並存--> <servlet> <servlet-name>springmvc_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc_rest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
靜態資源的解析:url
對靜態資源的解析須要配置前端控制器的url-pattern中指定 /,則會對靜態資源的解析出現問題。這時,則須要在springmvc.xml中添加靜態資源解析方法:
<!-- 靜態資源解析 --> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/img/" mapping="/img/**"/> <!-- ...... -->