1. 程式人生 > >springmvc對Restful的支援

springmvc對Restful的支援

什麼是Restful

Restful架構,就是目前最流行的一種網際網路軟體架構。它結構清晰、符合標準、易於理解、擴充套件方便,所以正得到越來越多網站的採用。

Restful(即Representational State Transfer的縮寫)其實是一個開發理念,是對http的很好地詮釋。

1、對URL進行規範,寫Restful格式的URL

非Rest的URL:http://.../queryItems.action?id=001&type=T01

Rest的URL風格:http://.../items/001

特點:URL簡潔,將引數通過URL傳到服務端

2、http的方法規範

不管是刪除,新增,更新。使用URL是一致的,如果是進行刪除,需要設定http的方法為delete,同理新增。。

後臺controller方法:判斷http方法,如果是delete執行刪除,如果是post執行新增

3、對http的contentType規範

請求時指定contentType,要json資料,設定成json格式的type。

controller方法Restful實現

   //itemsView/{id}裡面的{id}表示將這個位置的引數傳到@PathVariable指定名稱中
    @RequestMapping("/itemsView/{id}")
    public @ResponseBody ItemCustom itemsView(@PathVariable("id")Intege id)throws Exception{
        //呼叫service查詢商品資訊
        ItemCustom itemCustom = itemsSerVice.findItemsById(id);
        
        return itemCustom;
    }

備註:在前端控制器配置 <url-pattern>標籤中設定為  /

Restful對靜態資源的解析

需要在springmvc手動配置靜態檔案解析

<!--靜態資源解析
	包括:js、css、img..
	-->
	<mvc:resources mapping="/js/**" location="/js/"/>
	<mvc:resources mapping="/css/**" location="/css/"/>