使用Spring构建RESTful的Web服务

使用Spring构建RESTful的Web服务

2019-04-10 17:33:06
上海

目标

构建一个可以接受http请求的API。

这个API看起来是这样的,访问http://localhost:8080/greeting,返回

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

或者带上参数http://localhost:8080/greeting?name=User,返回

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

准备

  • Java8或更高。
  • maven3.2或更高
  • Spring boot 2.1.3
  • 编辑器或者IDE

操作

下载样例源码,或者使用git clone到本地:

git clone https://github.com/spring-guides/gs-rest-service.git

然后进入到initial文件夹下,之后的所有操作以该文件夹为工作目录。

创建资源类

新建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;
    }
}

创建控制类

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

控制类用于处理HTTP请求。

  • @RestController注释表明这是一个控制类。
  • @RequestMapping("/greeting")注释可以将请求到/greeting地址的HTTP请求映射到greeting()方法。

    @RequestMapping默认会映射所有HTTP方式,可以通过@RequestMapping(method=GET)指定具体的方式。

  • @RequestParam注释用于将请求中的name字段与greeting()方法中的name参数绑定。

添加main方法

新建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注释相当于下列多个注释:

  • @Configuration
  • @EnableAutoConfiguration
  • @EnableWebMvc
  • @ComponentScan

运行

在工作目录下打开控制台窗口,运行:

mvn spring-boot:run

之后访问http://localhost:8080/greeting即可看到API返回的数据,也可以在查询中带上参数name

若要停止应用,按Ctrl+C(在git bash中失效)。

打包

在工作目录下打开控制台窗口,运行:

mvn package

可以将应用打包为jar包,保存在target目录下。

以下命令可以查看jar包中都有什么:

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

以下命令可以运行jar包:

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

同样,若要停止应用,按Ctrl+C

使用IntelliJ IDEA

如果使用IntelliJ IDEA,它已经自带了maven和spring,可以直接在IDE界面中点击按钮运行或调试,并且可以通过图形界面将应用打包。

参考

Getting Started · Building a RESTful Web Service

Spring Boot Reference Guide

在 GitHub 上查看本页