天天看點

Spring Web MVC實作Restful Web Service

一引言:

以前一說到Web Service大家肯定會聯想到SOAP,現在提到Web Service大家馬上聯想到RESTful,因為RESTful Web Service已經深得人心,得到重用,相比笨重的SOAP越來越流行了,那麼什麼是RESTful Web Service?REST英文全稱為Representational State Transfer,翻譯為中文即表征狀态轉移,是一種軟體架構風格,REST關鍵原則為:

為所有“事物”定義ID

将所有事物連結在一起

使用标準方法

資源多重表述

無狀态通信

RESTful Web Service 是一個使用HTTP并遵循REST原則的Web服務。它從三個方面資源進行定義:

URI,比如:http://example.com/resources/。

Web Service接受與傳回的網際網路媒體類型,比如:JSON,XML等。

Web Service在該資源上所支援的一系列請求方法(比如:POST,GET,PUT或DELETE)。

HTTP 請求方法在RESTful Web 服務中的典型應用

資源

GET

PUT

POST

DELETE

一組資源的URI,比如http://example.com/resources/

列出 URI,以及該資源組中每個資源的詳細資訊(後者可選)。

使用給定的一組資源替換目前整組資源。

在本組資源中建立/追加一個新的資源。該操作往往傳回新資源的URL。

删除整組資源。

單個資源的URI,比如http://example.com/resources/142

擷取指定的資源的詳細資訊,格式可以自選一個合适的網絡媒體類型(比如:XML、JSON等)

替換/建立指定的資源。并将其追加到相應的資源組中。

把指定的資源當做一個資源組,并在其下建立/追加一個新的元素,使其隸屬于目前資源。

删除指定的元素。

二SpringMVC對RESTful Web Service的支援:

1.将URI和HTTP請求方法映射到JAVA處理方法,并将JAVA方法處理結果傳回給HTTP請求者(對應資源定義I和III)。

@RequestMapping

這是最重要的一個注解,用于處理HTTP請求位址映射,可用于類或方法上,用于類上時表示類中的所有響應請求的方法都是以該位址作為父路徑,在Spring中,一般一個Controller類處理一種資源,是以每個Controller類都會加@RequestMapping注解。

常用屬性:

value:指定請求的位址

method:指定請求的method類型, GET、POST、PUT、DELETE等

params:指定request中必須包含某些參數值是,才讓該方法處理

1

2

3

4

5

6

7

8

9

10

11

<code>@Controller</code>

<code>@RequestMapping</code><code>(value = </code><code>"/contact"</code><code>)</code>

<code>public</code> <code>class</code> <code>ContactController {</code>

<code>    </code><code>final</code> <code>Logger logger = LoggerFactory.getLogger(ContactController.</code><code>class</code><code>);</code>

<code>    </code><code>@Autowired</code>

<code>    </code><code>private</code> <code>ContactService contactService;</code>

<code>    </code><code>@RequestMapping</code><code>(value = </code><code>"/listdata"</code><code>, method = RequestMethod.GET)</code>

<code>    </code><code>@ResponseBody</code>

<code>    </code><code>public</code> <code>Contacts listData() {</code>

<code>        </code><code>return</code> <code>new</code> <code>Contacts(contactService.findAll());</code>

<code>    </code><code>}</code>

@PathVariable

映射URL路徑裡面的參數

<code>@RequestMapping</code><code>(value = </code><code>"/{id}"</code><code>, method = RequestMethod.GET)</code>

<code>    </code><code>public</code> <code>Contact findContactById(</code><code>@PathVariable</code> <code>Long id) {</code>

<code>        </code><code>return</code> <code>contactService.findById(id);</code>

2.将接收的資料(如JSON格式資料)轉換為JAVA對象和将JAVA對象轉換為請求格式(如XML)的資料(對應資源定義II)。

@RequestBody

用于讀取Request請求的body資料,使用Bean配置中的 HttpMessageConverter 将資料轉換為JAVA對象,再把對象綁定到 controller中方法的參數上。

<code>@RequestMapping</code><code>(value = </code><code>"/"</code><code>, method = RequestMethod.POST)</code>

<code>    </code><code>public</code> <code>Contact create(</code><code>@RequestBody</code> <code>Contact contact) {</code>

<code>        </code><code>logger.info(</code><code>"Creating contact: "</code> <code>+ contact);</code>

<code>        </code><code>contactService.save(contact);</code>

<code>        </code><code>logger.info(</code><code>"Contact created successfully with info: "</code> <code>+ contact);</code>

<code>        </code><code>return</code> <code>contact;</code>

@ResponseBody

用于将Controller中方法傳回的對象,使用Bean配置中的 HttpMessageConverter 轉換為指定格式資料,再寫入到Response對象的body資料區。

<code>@RequestMapping</code><code>(value = </code><code>"/listdata"</code><code>, method = RequestMethod.GET)</code>

HttpMessageConverter配置示例:

<code>&lt;</code><code>mvc:annotation-driven</code><code>&gt;</code>

<code>        </code><code>&lt;</code><code>mvc:message-converters</code><code>&gt;</code>

<code>            </code><code>&lt;</code><code>bean</code> <code>class</code><code>=</code><code>"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"</code><code>/&gt;</code>

<code>            </code><code>&lt;</code><code>bean</code>

<code>                </code><code>class</code><code>=</code><code>"org.springframework.http.converter.xml.MarshallingHttpMessageConverter"</code><code>&gt;</code>

<code>                </code><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"marshaller"</code> <code>ref</code><code>=</code><code>"castorMarshaller"</code> <code>/&gt;</code>

<code>                </code><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"unmarshaller"</code> <code>ref</code><code>=</code><code>"castorMarshaller"</code> <code>/&gt;</code>

<code>            </code><code>&lt;/</code><code>bean</code><code>&gt;</code>

<code>        </code><code>&lt;/</code><code>mvc:message-converters</code><code>&gt;</code>

<code>    </code><code>&lt;/</code><code>mvc:annotation-driven</code><code>&gt;</code>

預設情況下Spring已經啟用了很多HttpMessageConverter,隻要将他們的實作在類路徑下即可,無需再配置。

ByteArrayHttpMessageConverter – converts byte arrays

StringHttpMessageConverter – converts Strings

ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream

SourceHttpMessageConverter – converts javax.xml.transform.Source

FormHttpMessageConverter – converts form data to/from a MultiValueMap&lt;String, String&gt;.

Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)

MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)

MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)

AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)

RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)

Spring做得太貼心了,是以開發者簡單配置就搞定RESTful WebService功能,然後就可專注于業務邏輯實作上。

<a href="http://down.51cto.com/data/2364035" target="_blank">附件:http://down.51cto.com/data/2364035</a>

     本文轉自sarchitect 51CTO部落格,原文連結:http://blog.51cto.com/stevex/1355154,如需轉載請自行聯系原作者