1. 程式人生 > >Spring Boot 建立RESTful Web Service

Spring Boot 建立RESTful Web Service

1. 介紹

本篇將使用Spring Boot建立一個簡單restful風格web服務,接受HTTP GET請求:

http://localhost:8080/greeting

響應體(respond)為一個JSON字串

{"id":1,"content":"Hello, World!"}
2. 環境要求

IED 或 文字編輯器

JDK1.8+

Maven 3.0+

3. 專案工程

1) 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.4.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>
Spring Boot Maven Plugin 的作用為:

將本專案classpath裡面的所有jar包打包成一個可執行的jar檔案;

    找到包含public static void main() 方法的類,作為可執行jar的入口

提供內建的依賴分析器,為Spring boot dependencies設定預設的版本號(可以被自己指定的版本號覆蓋)


2) 建立資源表示類(resource representation,即RESTful中的R,簡單理解就是實體)

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庫將實體類的物件自動轉換成JSON。

3) 資源控制類

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));
    }
}

控制器程式碼很簡潔,但是卻做了很多事情。

@RestController將該類標註為一個spring bean,並標記其中的每個方法返回一個實體物件。相當於@[email protected]

@RequestMapping提供url和方法的對映,當接收到一個/greeting的請求時,能執行greeting()方法。

注:上面的例子沒有指定http動作(GET, PUT, POST, DELETE),所以會與所有的動作匹配。更好的方法是使@RequestMapping(method=GET)這樣只會接收到GET請求。

@RequestParam通過指定的value繫結url中的引數。本例中,url引數是可選的,因為提供了預設值“World”。

方法體建立Greeting()物件並返回。

注:傳統的MVC 控制器和RESTful 控制器的區別在於http響應是怎樣被建立的。

傳統的MVC 控制器會通過檢視轉換將Greeting物件渲染成html返回到前端。

而RESTful 控制器直接返回Greeting物件,通過JSON轉換器變成一個JSON字串。

4) 執行類

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 = @[email protected][email protected]

@Configuration將該類標註為一個spring bean

@EnableAutoConfiguration告訴Spring Boot裝載bean的方式可以基於classpath設定、其他bean或屬性設定。

正常情況下我們會為Spring MCV應用加上@EnableWebMvc,但是這裡Spring Boot已經為我們做好了,它檢測到了工程classpath下有spring-mvc jar,就會自動加上這個註解來啟用web應用的關鍵動作,如建立DispatcherServlet。

@ComponentScan 掃描當前包裡面所有帶@Component、@Service、@Controller等註解的類,加入spring容器註冊成bean。

main方法裡用Spring Boot的SpringApplication.run()方法啟動web應用。整個專案沒有一個xml配置檔案,包括web.xml,這就是Spring Boot的強大所在,讓使用者只關注業務邏輯的java程式碼,不用去處理專案配置和結構

5) 構建可執行JAR

命令列進入專案根目錄

輸入./mvnw spring-boot:run

./mvnw clean package

會發現專案目錄下生成一個target資料夾,裡面的jar檔案即為可執行JAR。

執行JAR  java -jar target/gs-rest-service-0.1.0.jar

6) 測試

返回結果

{"id":1,"content":"Hello, World!"}
帶引數的請求http://localhost:8080/greeting?name=User

返回結果

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

原文:  http://spring.io/guides/gs/rest-service/,翻譯省去了關於Gradle的部分。

相關推薦

Spring Boot 建立RESTful Web Service

1. 介紹 本篇將使用Spring Boot建立一個簡單restful風格web服務,接受HTTP GET請求: http://localhost:8080/greeting 響應體(respond)為一個JSON字串 {"id":1,"content":"Hello

spring-boot構建RESTful Web服務

往後官方demo的筆記不貼程式碼了,只貼連結 官方文件 RESTful Web服務 該服務將處理GET請求/greeting,可選地使用name查詢字串中的引數。該GET請求應該返回200 OK在表示問候的身體與JSON響應。它應該看起來像這樣: { "id": 1, "content

Spring Boot 構建restful web服務

1.建立依賴檔案 檔名:pom.xml 檔案內容: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://ww

Spring之使用Spring Boot構建RESTful Web服務

英文原文:https://spring.io/guides/gs/rest-service/ 目錄 你要構建什麼 你需要什麼 如何完成本指南 建立資源表示類 建立資源控制器 使應用程式可執行 構建可執行的JAR 測試服務 總結 參考 本指南將引導您

Spring官方指南學習】Spring構建一個 restful web service

【Spring學習筆記,稍作記錄,主要參考Spring官網 http://spring.io/guides】 構建一個restful web service 理解如何用spring去構建一個簡單的 “hello world” Restful we

用Srpingmvc 建立RESTful web service

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% St

使用Java建立RESTful Web Service

當與spring相結合,要匯入jersey-spring.jar,然後修改 web.xml  <!-- JerseyServlet --><servlet><servlet-name>JerseyServlet</servlet-

Spring Boot學習筆記之使用Spring Boot建立一個簡單的web專案(工具使用IntelliJ IDEA)

新建Maven專案 1.File --> New Project --> Maven --> Next 2.填寫專案資訊,完成之後點選Next,然後點選Finish 3.專案建好之後如下圖所示 修改pom檔案中的配置資訊 <?xml version

使用Spring boot 建立web工程

原文 利用Springboot新建一個web工程 方法有很多種,一種比較方便的方法就是直接訪問Spring INITIALIZR,填好資訊,然後Alt + Enter鍵直接生成即可。然後使用IDE(對不起我比較low)import剛才生成的專案,我是使用ma

如何封裝RESTful Web Service

如何封裝RESTful Web Service

zzWCF實現RESTFul Web Service

XML scl 新建 封裝 rest ole 字符串 factor esp http://www.cnblogs.com/KeithWang/archive/2012/02/14/2351826.html http://blog.csdn.net/qq_26054303/

Java RESTful Web Service實戰(第2版)pdf

images rep 漸進 網盤下載 調優 一點 進一步 image ctf 下載地址:網盤下載 內容簡介本書系統、深度講解了如何基於Java標準規範實現REST風格的Web服務,由擁有10余年開發經驗的阿裏雲大數據架構師撰寫,第1版上市後廣獲贊譽,成為該領域的暢銷書。第

3.消費一個RESTful Web Service

無法連接 npr 便在 can pos OS json數據 公司 可運行的jar 這節課我們根據官網教程學習如何去消費(調用)一個 RESTful Web Service 。 原文鏈接 https://spring.io/guides/gs/consuming-rest/

<<Java RESTful Web Service實戰>> 讀書筆記

protoc 交付 soap pro 內容 ica servlet容器 安全 soap協議 <<Java RESTful Web Service實戰>> 讀書筆記 第一章 JAX-RS2.0入門 REST (Representational

Spring Boot構建RESTful API與單元測試實戰

一 點睛 1 相關注解 @Controller:修飾class,用來建立處理http請求的物件 @RestController:Spring4之後加入的註解,原來在@Controller中返回json需要@ResponseBody來配合,如果直接用@

使用Spring Boot建立微服務

過去幾年以來,“微服務架構”的概念已經在軟體開發領域獲得了一個穩定的基礎。作為“面向服務架構”(SOA)的一個繼任者,微服務同樣也可以被歸類為“分散式系統”這一類,並且進一步發揚了SOA中的許多概念與實踐。不過,它們在不同之處在於每個單一服務所應承擔的責任範圍。在SOA中,每個服務將負責處理廣範圍

使用spring boot + Thymeleaf實現web小頁面

本文章只是介紹下如何使用spring boot + Thymeleaf,實現簡單的web頁面步驟和流程 幾點說明: Spring boot開發web專案,通常打成jar包,使用內建的web伺服器 Tomcat、Jetty、undertow 來執行。  靜態資源(css、js、圖片等)預

Spring Boot 建立專案(二)

如何建立Spring Boot 專案? 接下來我們將學習如何建立第一個Spring Boot專案 hello Spring Boot! 呢? 我們將以 IntelliJ IDEA 開發工具為例建立Spring Boot專案 如果還沒下載過Intel

Spring Boot 入門篇 (二) Spring Boot構建RESTful API與單元測試

http://blog.didispace.com/springbootrestfulapi/ 首先,回顧並詳細說明一下在快速入門中使用的@Controller、@RestController、@RequestMapping註解。如果您對Spring MVC不熟悉並且還沒有嘗試過快速入門案例,建

Spring-Boot快速搭建web專案全解

Spring-Boot快速搭建web專案 最近在學習Spring Boot 相關的技術,剛接觸就有種相見恨晚的感覺,因為用spring boot進行專案的搭建是在太方便了,我們往往只需要很簡單的幾步,便可完成一個spring MVC專案的搭建,感覺就是下圖:  好,下面就本人