关于springboot:Spring-Boot快速入门之十一构建-RESTful-Web-服务

32次阅读

共计 10083 个字符,预计需要花费 26 分钟才能阅读完成。

【注】本文译自:https://www.tutorialspoint.com/spring_boot/spring_boot_building_restful_web_services.htm

Spring Boot 提供了构建企业应用中 RESTful Web 服务的极佳反对。本文为你详解如何应用 Spring Boot 构建 RESTful web 服务。

留神:要构建 RESTful Web 服务,咱们须要在构建配置文件中加上 Spring Boot Starter Web 依赖。

对于 Maven 用户,应用以下的代码在 pom.xml 文件中退出依赖:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

对于 Gradle 用户,应用以下的代码在 build.gradle 文件中退出依赖:

compile(‘org.springframework.boot:spring-boot-starter-web’)

残缺的构建配置文件 Maven build – 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>com.tutorialspoint</groupId>

<artifactId>demo</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

<name>demo</name>

<description>Demo project for Spring Boot</description>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.8.RELEASE</version>

<relativePath/>

</parent>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

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

</properties>

<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>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

残缺的构建配置文件 Gradle Build – build.gradle 如下:

bbuildscript {

ext {

springBootVersion = ‘1.5.8.RELEASE’

}

repositories {

mavenCentral()

}

dependencies {

classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”)

}

}

apply plugin: ‘java’

apply plugin: ‘eclipse’

apply plugin: ‘org.springframework.boot’

group = ‘com.tutorialspoint’

version = ‘0.0.1-SNAPSHOT’

sourceCompatibility = 1.8

repositories {

mavenCentral()

}

dependencies {

compile(‘org.springframework.boot:spring-boot-starter-web’)

testCompile(‘org.springframework.boot:spring-boot-starter-test’)

}

在持续构建 RESTful web 服务前,倡议你先要相熟上面的注解:

Rest Controller

@RestController 注解用于定义 RESTful web 服务。它提供 JSON、XML 和自定义响应。语法如下所示:

@RestController

public class ProductServiceController {

}

Request Mapping

@RequestMapping 注解用于定义申请 URI 以拜访 REST 端点。咱们能够定义 Request 办法来生产 produce 对象。默认的申请办法是 GET:

@RequestMapping(value = “/products”)

public ResponseEntity<Object> getProducts() {}

Request Body

@RequestBody 注解用于定义申请体内容类型。

public ResponseEntity<Object> createProduct(@RequestBody Product product) {

}

Path Variable

@PathVariable 注解被用于定义自定义或动静的申请 URI,Path variable 被放在申请 URI 中的大括号内,如下所示:

public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id) {

}

Request Parameter

@RequestParam 注解被用于从申请 URL 中读取申请参数。短少状况下这是一个必须的参数,也能够为申请参数设置默认值,如下所示:

public ResponseEntity<Object> getProduct(

@RequestParam(value = “name”, required = false, defaultValue = “honey”) String name) {

}

GET API

默认的 HTTP 申请办法是 GET。这个办法不须要任何申请体。你能够通过发送申请参数和门路变量来定义自定义或动静 URL。

上面的示例代码定义了 HTTP GET 申请办法。在这个例子吧,咱们应用 HashMap 来在存储 Product。留神咱们应用了 POJO 类来存储产品。

在这里,申请 URI 是 /products,它会从 HashMap 仓储中返回产品列表。上面的控制器类文件蕴含了 GET 办法的 REST 端点:

package com.tutorialspoint.demo.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();

static {

Product honey = new Product();

honey.setId(“1”);

honey.setName(“Honey”);

productRepo.put(honey.getId(), honey);

Product almond = new Product();

almond.setId(“2”);

almond.setName(“Almond”);

productRepo.put(almond.getId(), almond);

}

@RequestMapping(value = “/products”)

public ResponseEntity<Object> getProduct() {

return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);

}

}

POST API

HTTP POST 申请用于创立资源。这个办法蕴含申请体。咱们能够通过发送申请参数和门路变量来定义自定义或动静 URL。

上面的示例代码定义了 HTTP POST 申请办法。在这个例子中,咱们应用 HashMap 来存储 Product,这里产品是一个 POJO 类。

这里,申请 URI 是 /products,在产品被存入 HashMap 仓储后,它会返回字符串。

package com.tutorialspoint.demo.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = “/products”, method = RequestMethod.POST)

public ResponseEntity<Object> createProduct(@RequestBody Product product) {

productRepo.put(product.getId(), product);

return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED);

}

}

PUT API

HTTP PUT 申请用于更新已有的资源。这个办法蕴含申请体。咱们能够通过发送申请参数和门路变量来定义自定义或动静 URL。

上面的例子展现了如何定义 HTTP PUT 申请办法。在这个例子中,咱们应用 HashMap 更新现存的产品。此处,产品是一个 POJO 类。

这里,申请 URI 是 /products/{id},在产品被存入 HashMap 仓储后,它会返回字符串。留神咱们应用门路变量 {id} 定义须要更新的产品 ID:

package com.tutorialspoint.demo.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT)

public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) {

productRepo.remove(id);

product.setId(id);

productRepo.put(id, product);

return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK);

}

}

DELETE API

HTTP Delete 申请用于删除存在的资源。这个办法不蕴含任何申请体。咱们能够通过发送申请参数和门路变量来定义自定义或动静 URL。

上面的例子展现如何定义 HTTP DELETE 申请办法。这个例子中,咱们应用 HashMap 来移除现存的产品,用 POJO 来示意。

申请 URI 是 /products/{id} 在产品被从 HashMap 仓储中删除后,它会返回字符串。咱们应用门路变量 {id} 来定义要被删除的产品 ID。

package com.tutorialspoint.demo.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = “/products/{id}”, method = RequestMethod.DELETE)

public ResponseEntity<Object> delete(@PathVariable(“id”) String id) {

productRepo.remove(id);

return new ResponseEntity<>(“Product is deleted successsfully”, HttpStatus.OK);

}

}

上面给出残缺的源代码:

Spring Boot 主利用类 – DemoApplication.java

package com.tutorialspoint.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

}

POJO 类 – Product.java

package com.tutorialspoint.demo.model;

public class Product {

private String id;

private String name;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Rest Controller 类 – ProductServiceController.java

package com.tutorialspoint.demo.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();

static {

Product honey = new Product();

honey.setId(“1”);

honey.setName(“Honey”);

productRepo.put(honey.getId(), honey);

Product almond = new Product();

almond.setId(“2”);

almond.setName(“Almond”);

productRepo.put(almond.getId(), almond);

}

@RequestMapping(value = “/products/{id}”, method = RequestMethod.DELETE)

public ResponseEntity<Object> delete(@PathVariable(“id”) String id) {

productRepo.remove(id);

return new ResponseEntity<>(“Product is deleted successsfully”, HttpStatus.OK);

}

@RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT)

public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) {

productRepo.remove(id);

product.setId(id);

productRepo.put(id, product);

return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK);

}

@RequestMapping(value = “/products”, method = RequestMethod.POST)

public ResponseEntity<Object> createProduct(@RequestBody Product product) {

productRepo.put(product.getId(), product);

return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED);

}

@RequestMapping(value = “/products”)

public ResponseEntity<Object> getProduct() {

return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);

}

}

你能够创立可执行的 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 能够看到相应的输入:

GET API URL 为: http://localhost:8080/products

POST API URL 为: http://localhost:8080/products

PUT API URL 为: http://localhost:8080/products/3


DELETE API URL 为: http://localhost:8080/products/3

正文完
 0