構建RESTful Web 服務(譯)

構建RESTful Web 服務

這個指南將會帶你用Spring創建一個"hello word" RESTful Web 服務

你可以創建什麼

你可以用創建一個服務接受HTTP GET請求

http://localhost:8080/greeting

並且響應JSON格式的greeting

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

你可以在查詢字符串中自定義帶有可選擇name參數的greeting

http://localhost:8080/greeting?name=User

這個name的值重寫"word"這個默認值,並且體現在這個響應中

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

 你需要什麼

 

怎麼完成這個指南

像大多數Spring Getting Started指南一樣,你可以從scratch開始並且完成每一步,或者你可以跳過基本的你已經熟悉步驟,不管怎樣,你最後都要以工作代碼結束

現在開始這個scratch,請點擊這鏈接 Build with Gradle

跳過基本步驟,請做一下步驟:

當你完成之後,你可以code這個檢查結果:gs-rest-service/complete.

創建一個資源來表示這個類

現在你可以設置項目和構建系統,你可以創建你的web 服務

通過考慮服務交互來開始

這個服務會提交關於/greeting的GET請求,也可以選擇帶有name的參數在查詢字符串裏,這個GET請求應該返回一個JSON格式的200 ok在表示greeting的主體中,它應該看起來像這樣。

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

這個id字段是這個greeting的唯一認證,這個content字段是代表greeting的文本描述

爲了構建greeting代表,你可創建一個資源代表類,並且提供一個具有字段,構造函數和訪問器的普通java對象。

src/main/java/hello/Greeting.java

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中

接下來你可以創造服務這些greeting的controller資源

創造一個Controller資源

In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController annotation, and the GreetingController below handles GET requests for /greeting by returning a new instance of the Greeting class:

在Spring構建WEB service中,HTTP請求被Controller控制,這些組件很容易的被@Controller註解標識,下面的GreetingController來處理greeting的GET請求,並返回一個新的Greeting類的實例

src/main/java/hello/GreetingController.java

 

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;

@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", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

這個controller簡單明瞭,但是在後臺有大量的事情處理,讓我們繼續一步一步打破它

The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to the greeting() method.

這個@RequestMapping註解確定greeting的HTTP請求可以匹配到greeting()方法

the above example does not specify GET vs. PUTPOST, and so forth, because @RequestMapping maps all HTTP operations by default. Use @RequestMapping(method=GET) to narrow this mapping.

上面並沒指定GET、PUT、POST,因爲@RequestMapping註解默認匹配所有HTTP操作,使用@Requestmapping(method=GET)來精準定位這個映射。

@RequestParam binds the value of the query string parameter name into the name parameter of the greeting() method. If the name parameter is absent in the request, the defaultValue of "World" is used

@RequestPara綁定查詢字符串中的參數到greeting()方法的name參數,如果name參數不存在,就是用默認值“World”

The implementation of the method body creates and returns a new Greeting object with id and content attributes based on the next value from the counter, and formats the given name by using the greeting template.
方法主體的實現產生並且返回一個新的帶有id和content字段的Greeting對象,並且使用greeting規範被給予的name

A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller simply populates and returns a Greeting object. The object data will be written directly to the HTTP response as JSON.

傳統的MVC控制器和RESTful web服務之間最關鍵的區別是HTTP響應主體的創建,RESTful web服務控制器簡單的返回Greeting對象,而不是依賴試圖技術來執行服務端對greeting數據到HTML的渲染,對象數據將以JSON格式被直接寫入到HTTP響應中

This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

這個代碼使用Spring4新的@RestController註解,被標記爲控制器,並且每個方法都返回一個對象,而不是試圖,它是@Controller和@ResponseBody 的結合。

The Greeting object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting instance to JSON.

這個greeting對象必須被轉換成JSON,多虧Spring消息轉換器的支持,你不需要手動轉換,因爲Jackson 2是在Spring的MappingJackson2HttpMessageConverter自動的把Greeting這個實例轉換爲JSON。

使這個程序執行

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

儘管可能將這個服務打成WAR包發佈到遠端服務器上,下面更簡單的方法演示創建一個獨立的應用程序,你打包所有東西成單一的可執行的JAR包,被java的main()方法驅動,通過這個方法,你使用Spring的支持爲了潛入Tomcat服務容器到HTTP運行時,而不是部署到一個外部的實例中

src/main/java/hello/Application.java

 

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@SpringBootApplication is a convenience annotation that adds all of the following:

@SpringBootApplication 是一個很方便的註解,添加了一下內容:

  • @Configuration tags the class as a source of bean definitions for the application context.

  • @Configuration 標記這個類給Spring應用上下文作爲bean的來源

  • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

  • @EnableAutoConfiguration 告訴Spring基於類路徑配置、其他beans和各種屬性配置來添加bean

  • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

  • 通常你會添加@EnableWebMvc 給Spring MVC應用程序,但是SpringBoot自動添加它,當它在類路徑上看到spring-webmvc,標記這個應用程序爲web應用程序,並且激活關鍵行爲,比如設置一個DispatcherServlet.

  • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

  • @ComponentScan 告訴Spring取在htllo包尋找其他的組件,配置和服務,允許它找到控制器

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.

main()方法使用SpringBoot的SpringApplication.run()方法去啓動一個應用程序,你注意到這裏沒有一行xml嗎?也沒有web.xml文件,這個web應用程序是100%純java,你也不用處理任何管道和基礎設施。

構建一個可執行的JAR包

You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

你可以使用gradle或者maven來運行應用程序,或者你可以構建一個可執行的JAR包,包括所有必須的依賴,類,和資源並且運行它,在整個開發週期,越過不同環境等等,使你很容易的控制版本和發佈這個服務到應用程序中。

If you are using Gradle, you can run the application using ./gradlew bootRun. Or you can build the JAR file using ./gradlew build. Then you can run the JAR file:

如果你使用Gradle,你可以使用./gradlew bootRun 運行容器,或者你可以創建一個JAR包使用./gradlew build,然後運行JAR包:

java -jar build/libs/gs-rest-service-0.1.0.jar

If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package. Then you can run the JAR file:

如果你使用Maven,你可以使用./mvnw spring-boot:run運行你的容器,或者你可以創建一個JAR包使用./mvnw clean package,然後運行JAR包:

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

Logging output is displayed. The service should be up and running within a few seconds.

日誌輸出已經顯示了,這個服務會在幾秒內啓動。

測試這個服務

Now that the service is up, visit http://localhost:8080/greeting, where you see:

現在這個服務已經啓動,你可以訪問http://localhost:8080/greeting,當你看到:

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

Provide a name query string parameter with http://localhost:8080/greeting?name=User. Notice how the value of the content attribute changes from "Hello, World!" to "Hello User!"

提供一個name查詢自渡船參數用這個http://localhost:8080/greeting?name=User,注意內容屬性的值怎麼從"Hello, World!"改變成"Hello User!"

{"id":2,"content":"Hello, User!"}

This change demonstrates that the @RequestParam arrangement in GreetingController is working as expected. The name parameter has been given a default value of "World", but can always be explicitly overridden through the query string.

這個變化演示了在GreetingController裏的@RequestParam註解正在按預期進行,這個name參數已經被提供默認值“World”,但是可以通過查詢字符串被重寫。

Notice also how the id attribute has changed from 1 to 2. This proves that you are working against the same GreetingController instance across multiple requests, and that its counter field is being incremented on each call as expected.

也注意id屬性從1變成2,這證明了你可以對同樣的GreetingController請求工作通過多個請求,它的counter字段會自動增加。

總結

Congratulations! You’ve just developed a RESTful web service with Spring.

恭喜,你開發了一個有Spring的REST Web服務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章