spring.io官方提供的例子Building a RESTful Web Service提供了用Maven、Gradle、STS構建一個RESTFul Web Service,實際上采用STS構建會更加的便捷。
目標
在瀏覽器中輸入url:
http://localhost:8080/greeting
訪問后得到結果:
{"id":1,"content":"Hello, World!"}
可以在url中帶上參數:
http://localhost:8080/greeting?name=User
帶上參數后的結果:
{"id":1,"content":"Hello, User!"}
開始
新建項目,通過菜單“File->New->Spring Starter Project” 新建。

在“New Spring Starter Project”對話框里自定義打上項目名,Atifact,Group,Package后,點Next。

在“New Spring Starter Project Dependencies”中,選擇Spring Boot Version,把Web組件勾上,表示要構建支持RESTful的服務。Web組件中包含的內容可以在提示框中看到,可以支持RESTful和Spring MVC。
點Finish完成向導,等待STS構建完成,可以看右下角的構建進度。

待構建完成后,在STS左側的"Package Explorer"中就能看到整個項目的結構了。
建完項目后, 首先創建一個該服務響應的json數據對應的對象,右擊包“com.example.demo”,新建一個Class,取名Greeting,然后點Finish 。


Greeting.java的代碼為:
package com.example.demo; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return this.id; } public String getContent() { return this.content; } }
按照最終訪問url響應的結果,寫上對應的字段已經他們的getter。
接着為了完成響應,創建對應的Controller,創建一個名為GreetingController的類,方法同上,點Finish。

GreetingController.java的代碼為:
package com.example.demo; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } }
在Class定義上面,我們直接使用了@RestController注釋,直接表示這是一個提供RESTful服務的Controller,這樣在所有與url關聯的方法上就不需要指定@ResponseBody來明確響應的數據類型,直接就會響應json數據。
在greeting方法的上面使用@RequestMapping將訪問的url和處理方法進行關聯,默認情況下支持GET,PUT,POST,DELETE所有的HTTP Method,如果要指定GET,可以寫成@RequestMapping(method=GET)。
在greeting方法的參數中,將方法的參數和url中的參數進行了綁定,可以通過required指明參數是否必須,如果指明了true,那么要根據情況把defaultValue指定默認值,否則會報異常。
最后,以Spring Boot App方式運行。

運行后,在瀏覽器里訪問url就能看到結果了。
url
http://localhost:8080/greeting?name=bobeut
結果:
{"id":1,"content":"Hello, bobeut!"}
End
