Guide1:Building a RESTful Web Service

This guide walks you through the process of creating a "Hello World"RESTful web service with Spring.

You will build a service that will accept HTTP GET requests at
http://localhost:8080/greeting or http://localhost:8080/greeting?name=#.

And it will respond with a JSON representation of a greeting.

1 创建新项目

在这里插入图片描述

我还引入了 lombok 依赖。

2 创建资源表示类

src/main/java/com/example/restservice/Greeting.java

package com.example.restservice;
import lombok.Data;
@Data
public class Greeting {
    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }
}

此应用程序使用使用 Jackson JSON 库自动地将类型Greeting的实例封装成JSON,网络启动器默认包含Jackson。

3 创建资源控制器

In Spring’s approach to building RESTful web service, HTTP requests are handled by a controller.

src/main/java/com/example/restservice/GreetingController.java

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
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();

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

(1) @GetMapping 注释可以确保 HTTP GET 请求到的 /greeting 被映射到 greeting() 方法。

(2) @RequestParam 将查询字符串参数name的值绑定到greeting()方法中的参数name。如果请求中不存在参数name,则使用 defaultValue 中的值 “World"。

(3) 线程安全的AtomicXXX,适合用于多线程环境。.incrementAndGet()自增+1

(4) @RestController 使这个类作为一个使所有方法返回域对象而不是视图的一个控制器。它包含 @Controller 和 @ResponseBody

4 运行

package com.example.restservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值