Spring Boot 2020 官方基础68课程第一个 构建RESTful Web服务

本章用5-10分钟创建一个Spring  RESTful Web service "Hello World"。

他可以接受http get请求,并返回标准的Json数据如下:

1 //接口get方法  http://localhost:8080/greeting
2 {"id":1,"content":"Hello, World!"}
3 
4 //接口get方法 http://localhost:8080/greeting?name=User
5 {"id":1,"content":"Hello, User!"}

 

开发环境搭建:

下载使用JDK 1.8 or later

下载  Spring Tool Suite (STS4) 并配置maven和aliyun镜像

步骤1:新建一个spring web项目:

file-new- spring started project-



 

/spring-web-serivce-demo/src/main/java/com/example/demo/Greeting.java

 1 package com.example.demo;
 2 
 3 public class Greeting {
 4     
 5     private final long id;
 6     private final String content;
 7      
 8  
 9     public Greeting(long id, String content) {
10         this.id = id;
11         this.content = content;
12     }
13     
14     public long getId() {
15         return id;
16     }
17     public String getContent() {
18         return content;
19     }
20     
21  
22 }

 

/spring-web-serivce-demo/src/main/java/com/example/demo/GreetingController.java

package com.example.demo;

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   //  =@Controller and @ResponseBody
public class GreetingController {

    private static final String template ="Hello,%s!";
    private final AtomicLong counter =new AtomicLong();
    
    //@PostMapping  @RequestMapping(method=GET)
    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name",defaultValue = "World") String name) {
        //Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting instance to JSON.
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
    
}

 

这样就可以了。

./mvnw spring-boot:run. 测试运行

 ./mvnw clean package 打包并发布

java -jar target/~tab 运行

 

 

posted @ 2020-02-26 10:44  Dongyu  阅读(99)  评论(0)    收藏  举报