springboot學習之構(gòu)建 RESTful Web服務
2023-04-12
springboot學習之構(gòu)建 RESTful Web服務
- 學習目標
- 學習環(huán)境
- 學習內(nèi)容
- 新建web工程
- 新建實體類
- 新建服務接口
- 運行、測試
- 攜帶name參數(shù)
- 無name參數(shù)
- 學習總結(jié)
學習目標
- 新建一個get請求,服務請求url為http://127.0.0.1:8080/greeting 返回一個應答信息:
{"id":1,"content":"Hello, World!"}
- 請求中可以攜帶參數(shù)如下:
http://127.0.0.1:8080/greeting?name=lili
- 應答信息中的“World”可以被“王山”覆蓋,返回信息如下:
{"id":1,"content":"Hello, lili!"}
學習環(huán)境
idea
maven3.6.3
jdk1.8
學習內(nèi)容
新建web工程
1、File->New->Project……

2、點擊Next

3、配置項目信息,繼續(xù)Next

4、選擇依賴,繼續(xù)Next

5、設置項目名稱和路徑位置,點擊Finish

6、工程搭建完畢。
新建實體類
package com.spring.demo.domain;
public class Greeting {
private long id;
private String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Greeting{" +
"id=" + id +
", content='" + content + '\'' +
'}';
}
}
新建服務接口
package com.spring.demo.web;
import com.spring.demo.domain.Greeting;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/greeting")
public class GreetingController {
@GetMapping()
//@RequestMapping(method=GET)
public Greeting greeting(String name){
Greeting greeting = null;
if (name != null && !"".equals(name)) {
greeting = new Greeting(1, "Hello, "+name+"!");
} else {
greeting = new Greeting(1, "Hello, World!");
}
return greeting;
}
}
運行、測試
攜帶name參數(shù)

無name參數(shù)

學習總結(jié)
通過自己的實踐和官網(wǎng)提供的demo,可做如下總結(jié)。
- @RestController表示該類的每個方法都返回一個domain以替代view,它同時包含@Controller和@ResponseBody
- @GetMapping()也可寫成@RequestMapping(method=GET)
- 使用@RequestParam進行控制器接口優(yōu)化:
@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));
}
}
- @RequestParam將查詢參數(shù)name的值綁定到greeting方法的name參數(shù)上,如果name參數(shù)值為空,默認值使用“World”。
- 返回的Greeting轉(zhuǎn)化為json格式的數(shù)據(jù),不用我們處理,Spring框架自帶的消息轉(zhuǎn)換器
MappingJackson2HttpMessageConverter自動轉(zhuǎn)換Greeting為JSON。 - 官方代碼中使用了AtomicLong這個類用來實現(xiàn)主鍵自增。
- @SpringBootApplication包含了@Configuration、@EnableAutoConfiguration、@ComponentScan。
- main()方法使用SpringApplication.run()方法去運行程序。
本文僅代表作者觀點,版權(quán)歸原創(chuàng)者所有,如需轉(zhuǎn)載請在文中注明來源及作者名字。
免責聲明:本文系轉(zhuǎn)載編輯文章,僅作分享之用。如分享內(nèi)容、圖片侵犯到您的版權(quán)或非授權(quán)發(fā)布,請及時與我們聯(lián)系進行審核處理或刪除,您可以發(fā)送材料至郵箱:service@tojoy.com





