搭建一個RESTFUL風格的Web Service (Maven版本)

[該教程翻譯自Spring官方,並進行適當刪減。]

你將搭建的

你將搭建一個可以接受Http Get 請求的web service,   

[plain] view plaincopy
  1. http://localhost:8080/greeting  
並將以JSON字符串的形式返回問候,

[plain] view plaincopy
  1. {"id":1,"content":"Hello, World!"}  


工具

一個文本編輯器,JDK1.6及以上,Maven 3.0+或者Gradle 1.11+。(本文將使用Maven)

下面是pom.xml文件的清單:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.   
  6.     <groupId>org.springframework</groupId>  
  7.     <artifactId>gs-rest-service</artifactId>  
  8.     <version>0.1.0</version>  
  9.   
  10.     <parent>  
  11.         <groupId>org.springframework.boot</groupId>  
  12.         <artifactId>spring-boot-starter-parent</artifactId>  
  13.         <version>1.1.5.RELEASE</version>  
  14.     </parent>  
  15.   
  16.     <dependencies>  
  17.         <dependency>  
  18.             <groupId>org.springframework.boot</groupId>  
  19.             <artifactId>spring-boot-starter-web</artifactId>  
  20.         </dependency>  
  21.     </dependencies>  
  22.   
  23.     <properties>  
  24.         <start-class>hello.Application</start-class>  
  25.     </properties>  
  26.   
  27.     <build>  
  28.         <plugins>  
  29.             <plugin>   
  30.                 <artifactId>maven-compiler-plugin</artifactId>   
  31.                 <version>2.3.2</version>   
  32.             </plugin>  
  33.             <plugin>  
  34.                 <groupId>org.springframework.boot</groupId>  
  35.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  36.             </plugin>  
  37.         </plugins>  
  38.     </build>  
  39.   
  40.     <repositories>  
  41.         <repository>  
  42.             <id>spring-releases</id>  
  43.             <url>http://repo.spring.io/libs-release</url>  
  44.         </repository>  
  45.     </repositories>  
  46.     <pluginRepositories>  
  47.         <pluginRepository>  
  48.             <id>spring-releases</id>  
  49.             <url>http://repo.spring.io/libs-release</url>  
  50.         </pluginRepository>  
  51.     </pluginRepositories>  
  52. </project>  


新建項目
首先你新建一個符合Maven規範的目錄結構, src/main/java/hello

[plain] view plaincopy
  1. └── src  
  2.     └── main  
  3.         └── java  
  4.             └── hello  

在hello目錄下,新建一個Greeting類作爲“問候”的javabean。代碼清單如下:

[java] view plaincopy
  1. package hello;  
  2.   
  3. public class Greeting {  
  4.   
  5.     private final long id;  
  6.     private final String content;  
  7.   
  8.     public Greeting(long id, String content) {  
  9.         this.id = id;  
  10.         this.content = content;  
  11.     }  
  12.   
  13.     public long getId() {  
  14.         return id;  
  15.     }  
  16.   
  17.     public String getContent() {  
  18.         return content;  
  19.     }  
  20. }  

在下面的步驟你將會看到,spring將使用Jackson JSON自動將Greeting的對象轉成JSON字符串。


接下來是新建一個類做控制器。

在Spring構建一個Restful風格的web service,需要一個處理請求的控制器。

同樣在hello目錄,代碼清單如下:

[java] view plaincopy
  1. package hello;  
  2.   
  3. import java.util.concurrent.atomic.AtomicLong;  
  4. import org.springframework.web.bind.annotation.RequestMapping;  
  5. import org.springframework.web.bind.annotation.RequestParam;  
  6. import org.springframework.web.bind.annotation.RestController;  
  7.   
  8. @RestController  
  9. public class GreetingController {  
  10.   
  11.     private static final String template = "Hello, %s!";  
  12.     private final AtomicLong counter = new AtomicLong();  
  13.   
  14.     @RequestMapping("/greeting")  
  15.     public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) {  
  16.         return new Greeting(counter.incrementAndGet(),  
  17.                             String.format(template, name));  
  18.     }  
  19. }  

寫過Spring MVC的對@RequestMapping和@RequestParam等一定不陌生。

傳統的MVC控制器和Restful 風格Web Service控制器的主要區別是,產生HTTP 響應的方式不同。不同於依賴視圖技術將數據解析成HTML,這個控制器填充並返回一個對象。

這段代碼使用Spring4.o新的註解:RestController,表明該類的每個方法返回對象而不是視圖。它實際就是@Controller和@ResponseBody混合使用的簡寫方法。


Greeting對象會被轉換成JSON字符串,這得益於Spring 的HTTP消息轉換支持,你不必人工處理。由於Jackson2在classpath裏,Spring的MappingJackson2HttpMessageConverter會自動完成這一工作。


儘管你可以將這個服務打包成傳統的WAR文件部署到應用服務器,但下面將會創建一個獨立的應用,使用main方法可以將所有東西打包到一個可執行的jar文件。並且,你將使用Sping對內嵌Tomcat servlet容器的支持,作爲HTPP 運行時環境,沒必要部署成一個tomcat外部實例。

[java] view plaincopy
  1. package hello;  
  2.   
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.context.annotation.ComponentScan;  
  6.   
  7. @ComponentScan  
  8. @EnableAutoConfiguration  
  9. public class Application {  
  10.   
  11.     public static void main(String[] args) {  
  12.         SpringApplication.run(Application.class, args);  
  13.     }  
  14. }  

main方法使用了SpringApplication工具類。這將告訴Spring去讀取Application的元信息,並在Spring的應用上下文作爲一個組件被管理。

@ComponentScan註解告訴Spring在hello包下遍歷帶有@Component註解的類。這將保證Spring能找到並註冊GreetingController,因爲它被@RestController標記,這也是@Component的一種。

@EnableAutoConfiguration註解會基於你的類加載路徑的內容切換合理的默認行爲。比如,因爲應用要依賴內嵌版本的tomcat(tomcat-embed-core.jar),所有一個tomcat服務器會被啓動並代替你進行合理的配置。再比如,因爲應用要依賴Spring 的 MVC框架(spring-webmvc.jar),一個Spring MVC的DispatcherServlet將被配置並註冊,不再需要web.xml文件。自動配置是很強大靈活的機制。

使用maven可以這樣執行,

[plain] view plaincopy
  1. mvn clean package  

然後,

[plain] view plaincopy
  1. java -jar target/gs-rest-service-0.1.0.jar  

運行後無意外會出現Spring Boot結果:


在瀏覽器測試:


帶參數的測試:

轉自:http://blog.csdn.net/chenloveit/article/details/38779149?utm_source=tuicool

發佈了31 篇原創文章 · 獲贊 21 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章