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

來源:互聯網
上載者:User

標籤:spring   maven   web service   

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

你將搭建的

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

http://localhost:8080/greeting
並將以JSON字串的形式返回問候,

{"id":1,"content":"Hello, World!"}


工具

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

下面是pom.xml檔案的清單:

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>org.springframework</groupId>    <artifactId>gs-rest-service</artifactId>    <version>0.1.0</version>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.1.5.RELEASE</version>    </parent>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>    </dependencies>    <properties>        <start-class>hello.Application</start-class>    </properties>    <build>        <plugins>            <plugin>                 <artifactId>maven-compiler-plugin</artifactId>                 <version>2.3.2</version>             </plugin>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build>    <repositories>        <repository>            <id>spring-releases</id>            <url>http://repo.spring.io/libs-release</url>        </repository>    </repositories>    <pluginRepositories>        <pluginRepository>            <id>spring-releases</id>            <url>http://repo.spring.io/libs-release</url>        </pluginRepository>    </pluginRepositories></project>


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

└── src    └── main        └── java            └── hello

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

package hello;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 id;    }    public String getContent() {        return content;    }}

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


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

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

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

package hello;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;@RestControllerpublic 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));    }}

寫過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外部執行個體。

package hello;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.SpringApplication;import org.springframework.context.annotation.ComponentScan;@ComponentScan@EnableAutoConfigurationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

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可以這樣執行,

mvn clean package

然後,

java -jar target/gs-rest-service-0.1.0.jar

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


在瀏覽器測試:


帶參數的測試:



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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.