使用spring構建一個restful service project

spring官方指導:http://spring.io/guides/gs/rest-service/html

預期效果: 訪問如同這樣一個get請求:java

<!-- lang: html -->
http://localhost:8080/greeting

可以響應以下的json字串:git

<!-- lang: js -->
{"id":1,"content":"Hello, World!"}

也能夠傳遞一個參數,以下:github

<!-- lang: js -->
http://localhost:8080/greeting?name=User

response爲:web

<!-- lang: js -->
{"id":1,"content":"Hello, User!"}

須要的準備工做spring

  • About 15 minutes A favorite text editor or IDE JDK 1.6 or later Gradle 1.8+ or Maven 3.0+ You can also import the code from this guide as well as view the web page directly into Spring Tool Suite (STS) and work your way through it from there.

下載示範project:shell

<!-- lang: shell -->
git clone https://github.com/spring-guides/gs-rest-service.git

cd into gs-rest-service/initial

下面使用maven做爲構建工具:json

建立包目錄:mkdir -p src/main/java/helloapp

<!-- lang: shell -->
└── src
    └── main
        └── java
            └── hello

導入項目到Eclipse:maven

建立一個實體類: src/main/java/hello/Greeting.java

<!-- lang: 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;
    }
}

建立一個資源控制器: src/main/java/hello/GreetingController.java

<!-- lang: java -->
package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public @ResponseBody Greeting greeting(
            @RequestParam(value="name", required=false, defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

建立一個可執行的Application類: src/main/java/hello/Application.java

<!-- lang: java -->
package hello;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class Application {

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

運行服務:

<!-- lang: shell -->
cd gs-rest-service/complete
mvn clean package && java -jar target/gs-rest-service-0.1.0.jar

在此輸入圖片描述 在此輸入圖片描述 或者Eclipse裏面run as-》mvn install 測試: http://localhost(本地主機):8080/greeting, http://localhost(本地主機):8080/greeting?name=Nob 在此輸入圖片描述

ps:可能遇到的錯誤: Eclipse編碼要設置爲utf8,不然build時會出現問題

相關文章
相關標籤/搜索