建立一個(gè)RESTful Web Service
本系列教程使用idea完成
idea安裝springboot插件
image.png
需求:
jdk1.8及以上
maven3.2+
第一步
新建項(xiàng)目 jdk選擇1.8 java選擇8 點(diǎn)擊下一步
image.png
第二步
選擇web下面的spring web 點(diǎn)擊完成
image.png
第三步
創(chuàng)建Greeting.java 代碼如下
package com.example.restservice;
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;
}
}
第四步
創(chuàng)建一個(gè)資源控制器
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));
}
}
最后啟動(dòng)應(yīng)用,在瀏覽器訪問http://localhost:8080/greeting
顯示如下
{"id":1,"content":"Hello, World!"}
代一個(gè)參數(shù)訪問
http://localhost:8080/greeting?name=User
顯示如下
{"id":2,"content":"Hello, User!"}