書接上文???
HTTP 是平臺
要使用 Web 層次包裝您的存儲庫,您必須使用 Spring MVC。多虧了 Spring Boot,代碼基礎(chǔ)設(shè)施很少。相反,我們可以專注于行動:
nonrest/src/main/java/payroll/EmployeeController.java
package payroll;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
class EmployeeController {
private final EmployeeRepository repository;
EmployeeController(EmployeeRepository repository) {
this.repository = repository;
}
// Aggregate root
// tag::get-aggregate-root[]
@GetMapping("/employees")
List all() {
return repository.findAll();
}
// end::get-aggregate-root[]
@PostMapping("/employees")
Employee newEmployee(@RequestBody Employee newEmployee) {
return repository.save(newEmployee);
}
// Single item
@GetMapping("/employees/{id}")
Employee one(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
}
@PutMapping("/employees/{id}")
Employee replaceEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) {
return repository.findById(id)
.map(employee -> {
employee.setName(newEmployee.getName());
employee.setRole(newEmployee.getRole());
return repository.save(employee);
})
.orElseGet(() -> {
newEmployee.setId(id);
return repository.save(newEmployee);
});
}
@DeleteMapping("/employees/{id}")
void deleteEmployee(@PathVariable Long id) {
repository.deleteById(id);
}
}
- @RestController表示每個方法返回的數(shù)據(jù)會直接寫入響應(yīng)體,而不是渲染模板。
- AnEmployeeRepository由構(gòu)造函數(shù)注入到控制器中。
- 我們有每個操作的路由(@GetMapping、@PostMapping、@PutMapping和@DeleteMapping,對應(yīng)于 HTTP GET、POST、PUT和DELETE調(diào)用)。(注意:閱讀每種方法并了解它們的作用很有用。)
- EmployeeNotFoundException是用于指示何時查找但未找到員工的異常。
nonrest/src/main/java/payroll/EmployeeNotFoundException.java
package payroll;
class EmployeeNotFoundException extends RuntimeException {
EmployeeNotFoundException(Long id) {
super("Could not find employee " + id);
}
}
當(dāng)EmployeeNotFoundException拋出 an 時,Spring MVC 配置的這個額外花絮用于呈現(xiàn)HTTP 404:
nonrest/src/main/java/payroll/EmployeeNotFoundAdvice.java
package payroll;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
class EmployeeNotFoundAdvice {
@ResponseBody
@ExceptionHandler(EmployeeNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String employeeNotFoundHandler(EmployeeNotFoundException ex) {
return ex.getMessage();
}
}
- @ResponseBody表示此建議直接呈現(xiàn)到響應(yīng)正文中。
- @ExceptionHandlerEmployeeNotFoundException將建議配置為僅在拋出an 時才響應(yīng)。
- @ResponseStatus說要發(fā)出一個HttpStatus.NOT_FOUND,即一個HTTP 404。
- 建議的主體生成內(nèi)容。在這種情況下,它會給出異常的消息。
要啟動應(yīng)用程序,請右鍵單擊其中并從 IDEpublic static void main中PayRollApplication選擇運(yùn)行,或者:
Spring Initializr 使用 maven 包裝器,所以輸入:
$ ./mvnw clean spring-boot:run
或者使用您安裝的 Maven 版本輸入:
$ mvn clean spring-boot:run
當(dāng)應(yīng)用程序啟動時,我們可以立即對其進(jìn)行詢。
$ curl -v localhost:8080/員工
這將產(chǎn)生:
* 嘗試 ::1...* TCP_NODELAY 設(shè)置* 連接到 localhost (::1) 端口 8080 (#0)> GET /員工 HTTP/1.1> 主機(jī):本地主機(jī):8080> 用戶代理:curl/7.54.0> 接受:*/*>< HTTP/1.1 200< 內(nèi)容類型:application/json;charset=UTF-8< 傳輸編碼:分塊< 日期:格林威治標(biāo)準(zhǔn)時間 2018 年 8 月 9 日星期四 17:58:00<* 連接 #0 到主機(jī) localhost 保持不變[{"id":1,"name":"Bilbo Baggins","role":"竊賊"},{"id":2,"name":"Frodo Baggins","角色":"小偷"} ]
在這里,您可以看到壓縮格式的預(yù)加載數(shù)據(jù)。
如果您嘗試查詢一個不存在的用戶......
$ curl -v localhost:8080/employees/99
你得到…
* 嘗試 ::1...* TCP_NODELAY 設(shè)置* 連接到 localhost (::1) 端口 8080 (#0)> 獲取 /employees/99 HTTP/1.1> 主機(jī):本地主機(jī):8080> 用戶代理:curl/7.54.0> 接受:*/*>< HTTP/1.1 404< 內(nèi)容類型: text/plain;charset=UTF-8< 內(nèi)容長度:26< 日期:格林威治標(biāo)準(zhǔn)時間 2018 年 8 月 9 日星期四 18:00:56<* 連接 #0 到主機(jī) localhost 保持不變找不到員工 99
此消息很好地顯示了HTTP 404錯誤以及自定義消息Could not find employee 99。
顯示當(dāng)前編碼的交互并不難……?
如果您使用 Windows 命令提示符發(fā)出 cURL 命令,則以下命令可能無法正常工作。您必須選擇一個支持單引號參數(shù)的終端,或者使用雙引號,然后轉(zhuǎn)義 JSON 中的那些。
要創(chuàng)建新Employee記錄,我們在終端中使用以下命令——$開頭的表示后面是終端命令:
$ curl -X POST localhost:8080/employees -H 'Content-type:application/json' -d '{"name": "Samwise Gamgee", "role": "gardener"}'
然后它存儲新創(chuàng)建的員工并將其發(fā)送回給我們:
{"id":3,"name":"Samwise Gamgee","role":"gardener"}
您可以更新用戶。讓我們改變他的角色。
$ curl -X PUT localhost:8080/employees/3 -H 'Content-type:application/json' -d '{"name": "Samwise Gamgee", "role": "ring bearer"}'
我們可以看到輸出中反映的變化。
{"id":3,"name":"Samwise Gamgee","role":"戒指持有者"}
您構(gòu)建服務(wù)的方式可能會產(chǎn)生重大影響。在這種情況下,我們說update,但replace是更好的描述。例如,如果未提供名稱,則它將被取消。
最后,您可以像這樣刪除用戶:
$ curl -X DELETE 本地主機(jī):8080/employees/3# 現(xiàn)在如果我們再看一遍,它就不見了$ curl localhost:8080/employees/3找不到員工 3
這一切都很好,但是我們有 RESTful 服務(wù)了嗎?(如果你沒有聽懂提示,答案是否定的。)
少了什么東西?
......未完待續(xù)......
2022就業(yè)季|Spring認(rèn)證教你,如何使用 Spring 構(gòu)建 REST 服務(wù)
#java##spring##spring認(rèn)證##2022就業(yè)季#
以上就是今天關(guān)于Spring的一些討論,對你有幫助嗎?如果你有興趣深入了解,歡迎到Spring中國教育管理中心留言交流!
審核編輯:湯梓紅
-
spring
+關(guān)注
關(guān)注
0文章
340瀏覽量
14390 -
REST
+關(guān)注
關(guān)注
0文章
33瀏覽量
9447
發(fā)布評論請先 登錄
相關(guān)推薦
如何用ACM簡化你的Spring Cloud微服務(wù)環(huán)境配置管理
使用阿里云ACM簡化你的Spring Cloud微服務(wù)環(huán)境配置管理
Spring Boot嵌入式Web容器原理是什么
REST端口支持構(gòu)建動態(tài)REST請求來使用RESTful API網(wǎng)絡(luò)
REST API是什么,如何使用REST端口
![<b class='flag-5'>REST</b> API是什么,如何使用<b class='flag-5'>REST</b>端口](https://file.elecfans.com//web2/M00/31/11/poYBAGIOHL6AbeeVAAIlinoYBq8424.png)
如何獲得Spring認(rèn)證?學(xué)習(xí)JAVA如何獲得Spring Professional認(rèn)證?
![如何獲得<b class='flag-5'>Spring</b>認(rèn)證?學(xué)習(xí)JAVA如何獲得<b class='flag-5'>Spring</b> Professional認(rèn)證?](https://file.elecfans.com//web2/M00/4E/CF/poYBAGLCTmeAO7LwAAAlboje75E409.png)
如何使用Spring構(gòu)建REST服務(wù)(一)
如何使用Spring構(gòu)建REST服務(wù)(三)
如何使用Spring構(gòu)建REST服務(wù)(四)
如何使用Spring構(gòu)建REST服務(wù)(五)
REST的6大指導(dǎo)原則
Spring Cloud :打造可擴(kuò)展的微服務(wù)網(wǎng)關(guān)
![<b class='flag-5'>Spring</b> Cloud :打造可擴(kuò)展的微<b class='flag-5'>服務(wù)</b>網(wǎng)關(guān)](https://file1.elecfans.com/web2/M00/A9/BF/wKgaomU0g4-AFFXfAAAocfhTfds544.png)
Spring Cloud Gateway網(wǎng)關(guān)框架
![<b class='flag-5'>Spring</b> Cloud Gateway網(wǎng)關(guān)框架](https://file1.elecfans.com/web2/M00/04/A6/wKgaombGkiKAAwa1AAE-bJwRAe8680.png)
評論