Spring Boot 教程:构建 RESTful Web 服务

 
    Spring Boot 提供了构建企业应用中 RESTful Web 服务的极佳支持。本文为你详解如何使用 Spring Boot 构建 RESTful web 服务。
注意:要构建 RESTful Web 服务,我们需要在构建配置文件中加上 Spring Boot Starter Web 依赖。
    对于 Maven 用户,使用以下的代码在 pom.xml 文件中加入依赖:
1 <dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-web</artifactId>    
4 </dependency>
    对于 Gradle 用户,使用以下的代码在 build.gradle 文件中加入依赖:
compile('org.springframework.boot:spring-boot-starter-web')
    完整的构建配置文件 Maven build – pom.xml 如下:
 1 <?xml version = "1.0" encoding = "UTF-8"?>
 2 <project xmlns = "http://maven.apache.org/POM/4.0.0"
 3    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
 4    xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
 5    http://maven.apache.org/xsd/maven-4.0.0.xsd">
 6    
 7    <modelVersion>4.0.0</modelVersion>
 8    <groupId>com.tutorialspoint</groupId>
 9    <artifactId>demo</artifactId>
10    <version>0.0.1-SNAPSHOT</version>
11    <packaging>jar</packaging>
12    <name>demo</name>
13    <description>Demo project for Spring Boot</description>
14    
15    <parent>
16       <groupId>org.springframework.boot</groupId>
17       <artifactId>spring-boot-starter-parent</artifactId>
18       <version>1.5.8.RELEASE</version>
19       <relativePath/>
20    </parent>
21    
22    <properties>
23       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
24       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
25       <java.version>1.8</java.version>
26    </properties>
27    
28    <dependencies>
29       <dependency>
30          <groupId>org.springframework.boot</groupId>
31          <artifactId>spring-boot-starter-web</artifactId>
32       </dependency>
33       <dependency>
34          <groupId>org.springframework.boot</groupId>
35          <artifactId>spring-boot-starter-test</artifactId>
36          <scope>test</scope>
37       </dependency>
38    </dependencies>
39    
40    <build>
41       <plugins>
42          <plugin>
43             <groupId>org.springframework.boot</groupId>
44             <artifactId>spring-boot-maven-plugin</artifactId>
45          </plugin>
46       </plugins>
47    </build>
48    
49 </project>
    完整的构建配置文件 Gradle Build – build.gradle 如下:
 1 bbuildscript {
 2    ext {
 3       springBootVersion = '1.5.8.RELEASE'
 4    }
 5    repositories {
 6       mavenCentral()
 7    }
 8    dependencies {
 9       classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
10    }
11 }
12  
13 apply plugin: 'java'
14 apply plugin: 'eclipse'
15 apply plugin: 'org.springframework.boot'
16  
17 group = 'com.tutorialspoint'
18 version = '0.0.1-SNAPSHOT'
19 sourceCompatibility = 1.8
20  
21 repositories {
22    mavenCentral()
23 }
24 dependencies {
25    compile('org.springframework.boot:spring-boot-starter-web')
26    testCompile('org.springframework.boot:spring-boot-starter-test')
27 }
    在继续构建 RESTful web 服务前,建议你先要熟悉下面的注解:

Rest Controller

   @RestController 注解用于定义 RESTful web 服务。它提供 JSON、XML 和自定义响应。语法如下所示:
1 @RestController
2 public class ProductServiceController {
3 }

Request Mapping

    @RequestMapping 注解用于定义请求 URI 以访问 REST 端点。我们可以定义 Request 方法来消费 produce 对象。默认的请求方法是 GET:
1 @RequestMapping(value = "/products")
2 public ResponseEntity<Object> getProducts() { }

Request Body

   @RequestBody 注解用于定义请求体内容类型。
1 public ResponseEntity<Object> createProduct(@RequestBody Product product) {
2 }

Path Variable

   @PathVariable 注解被用于定义自定义或动态的请求 URI,Path variable 被放在请求 URI 中的大括号内,如下所示:
1 public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
2 }

Request Parameter

   @RequestParam 注解被用于从请求 URL 中读取请求参数。缺少情况下这是一个必需的参数,也可以为请求参数设置默认值,如下所示:
1 public ResponseEntity<Object> getProduct(
2    @RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
3 }

GET API

     默认的 HTTP 请求方法是 GET。这个方法不需要任何请求体。你可以通过发送请求参数和路径变量来定义自定义或动态 URL。
    下面的示例代码定义了 HTTP GET 请求方法。在这个例子吧,我们使用 HashMap 来在存储 Product。注意我们使用了 POJO 类来存储产品。
     在这里,请求 URI 是 /products,它会从 HashMap 仓储中返回产品列表。下面的控制器类文件包含了 GET 方法的 REST 端点:
 1 package com.tutorialspoint.demo.controller;
 2  
 3 import java.util.HashMap;
 4 import java.util.Map;
 5  
 6 import org.springframework.http.HttpStatus;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RestController;
10  
11 import com.tutorialspoint.demo.model.Product;
12  
13 @RestController
14 public class ProductServiceController {
15    private static Map<String, Product> productRepo = new HashMap<>();
16    static {
17       Product honey = new Product();
18       honey.setId("1");
19       honey.setName("Honey");
20       productRepo.put(honey.getId(), honey);
21       
22       Product almond = new Product();
23       almond.setId("2");
24       almond.setName("Almond");
25       productRepo.put(almond.getId(), almond);
26    }
27    @RequestMapping(value = "/products")
28    public ResponseEntity<Object> getProduct() {
29       return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
30    }
31 }

POST API

   HTTP POST 请求用于创建资源。这个方法包含请求体。我们可以通过发送请求参数和路径变量来定义自定义或动态 URL。
   下面的示例代码定义了 HTTP POST 请求方法。在这个例子中,我们使用 HashMap 来存储 Product,这里产品是一个 POJO 类。
   这里,请求 URI 是 /products,在产品被存入 HashMap 仓储后,它会返回字符串。
 1 package com.tutorialspoint.demo.controller;
 2  
 3 import java.util.HashMap;
 4 import java.util.Map;
 5  
 6 import org.springframework.http.HttpStatus;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.web.bind.annotation.RequestBody;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RequestMethod;
11 import org.springframework.web.bind.annotation.RestController;
12  
13 import com.tutorialspoint.demo.model.Product;
14  
15 @RestController
16 public class ProductServiceController {
17    private static Map<String, Product> productRepo = new HashMap<>();
18    
19    @RequestMapping(value = "/products", method = RequestMethod.POST)
20    public ResponseEntity<Object> createProduct(@RequestBody Product product) {
21       productRepo.put(product.getId(), product);
22       return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
23    }
24 }

PUT API

    HTTP PUT 请求用于更新已有的资源。这个方法包含请求体。我们可以通过发送请求参数和路径变量来定义自定义或动态 URL。
    下面的例子展示了如何定义 HTTP PUT 请求方法。在这个例子中,我们使用 HashMap 更新现存的产品。此处,产品是一个 POJO 类。
    这里,请求 URI 是 /products/{id},在产品被存入 HashMap 仓储后,它会返回字符串。注意我们使用路径变量 {id} 定义需要更新的产品 ID:
 1 package com.tutorialspoint.demo.controller;
 2  
 3 import java.util.HashMap;
 4 import java.util.Map;
 5  
 6 import org.springframework.http.HttpStatus;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.web.bind.annotation.PathVariable;
 9 import org.springframework.web.bind.annotation.RequestBody;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12 import org.springframework.web.bind.annotation.RestController;
13 import com.tutorialspoint.demo.model.Product;
14  
15 @RestController
16 public class ProductServiceController {
17    private static Map<String, Product> productRepo = new HashMap<>();
18    
19    @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
20    public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
21       productRepo.remove(id);
22       product.setId(id);
23       productRepo.put(id, product);
24       return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
25    }   
26 }

DELETE API

   HTTP Delete 请求用于删除存在的资源。这个方法不包含任何请求体。我们可以通过发送请求参数和路径变量来定义自定义或动态 URL。
   下面的例子展示如何定义 HTTP DELETE 请求方法。这个例子中,我们使用 HashMap 来移除现存的产品,用 POJO 来表示。
   请求 URI 是 /products/{id} 在产品被从 HashMap 仓储中删除后,它会返回字符串。 我们使用路径变量 {id} 来定义要被删除的产品 ID。
 1 package com.tutorialspoint.demo.controller;
 2  
 3 import java.util.HashMap;
 4 import java.util.Map;
 5  
 6 import org.springframework.http.HttpStatus;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.web.bind.annotation.PathVariable;
 9 import org.springframework.web.bind.annotation.RequestBody;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12 import org.springframework.web.bind.annotation.RestController;
13  
14 import com.tutorialspoint.demo.model.Product;
15  
16 @RestController
17 public class ProductServiceController {
18    private static Map<String, Product> productRepo = new HashMap<>();
19    
20    @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
21    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
22       productRepo.remove(id);
23       return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
24    }
25 }
   下面给出完整的源代码:
Spring Boot 主应用类 – DemoApplication.java
 1 package com.tutorialspoint.demo;
 2  
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5  
 6 @SpringBootApplication
 7 public class DemoApplication {
 8    public static void main(String[] args) {
 9       SpringApplication.run(DemoApplication.class, args);
10    }
11 }
POJO 类 – Product.java
 1 package com.tutorialspoint.demo.model;
 2  
 3 public class Product {
 4    private String id;
 5    private String name;
 6  
 7    public String getId() {
 8       return id;
 9    }
10    public void setId(String id) {
11       this.id = id;
12    }
13    public String getName() {
14       return name;
15    }
16    public void setName(String name) {
17       this.name = name;
18    }
19 }
Rest Controller 类 – ProductServiceController.java
 1 package com.tutorialspoint.demo.controller;
 2  
 3 import java.util.HashMap;
 4 import java.util.Map;
 5  
 6 import org.springframework.http.HttpStatus;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.web.bind.annotation.PathVariable;
 9 import org.springframework.web.bind.annotation.RequestBody;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12 import org.springframework.web.bind.annotation.RestController;
13  
14 import com.tutorialspoint.demo.model.Product;
15  
16 @RestController
17 public class ProductServiceController {
18    private static Map<String, Product> productRepo = new HashMap<>();
19    static {
20       Product honey = new Product();
21       honey.setId("1");
22       honey.setName("Honey");
23       productRepo.put(honey.getId(), honey);
24       
25       Product almond = new Product();
26       almond.setId("2");
27       almond.setName("Almond");
28       productRepo.put(almond.getId(), almond);
29    }
30    
31    @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
32    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
33       productRepo.remove(id);
34       return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
35    }
36    
37    @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
38    public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
39       productRepo.remove(id);
40       product.setId(id);
41       productRepo.put(id, product);
42       return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
43    }
44    
45    @RequestMapping(value = "/products", method = RequestMethod.POST)
46    public ResponseEntity<Object> createProduct(@RequestBody Product product) {
47       productRepo.put(product.getId(), product);
48       return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
49    }
50    
51    @RequestMapping(value = "/products")
52    public ResponseEntity<Object> getProduct() {
53       return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
54    }
55 }
   你可以创建可执行的 JAR 文件,使用以下的 Maven 或 Gradle 命令来运行 spring boot 应用:
   Maven命令如下:
mvn clean install
   “构建成功“后,可以在 target 文件夹下发现 JAR 文件。
   Gradle命令如下:
gradle clean build
    “构建成功“后,可以在 build/libs 文件夹下发现 JAR 文件。
    可以使用以下命令来运行 JAR 文件:
java –jar <JARFILE>
    以 Tomcat 端口号 8080 启动应用,如下所示:
    在 POSTMAN 应用中点击下面的 URL 可以看到相应的输出:
 
posted @ 2020-08-21 11:11  码者无疆  阅读(513)  评论(0)    收藏  举报