javascript
使用Spring Boot构建REST Web服务
本教程提供了有關(guān)如何使用Spring Boot構(gòu)建Restfull Web服務(wù)的分步指南。
先決條件:
- Eclipse IDE(最新版本)
- Maven的4
- Java 1.8
1.創(chuàng)建Maven Web項目
打開eclipse,然后創(chuàng)建一個新的Maven Web項目,并將其命名為SpringBootRest。
生成的項目的結(jié)構(gòu)如下所示:
2. pom.xml
創(chuàng)建Web項目之后,第一步是在pom.xml內(nèi)配置Spring Boot ,因此我們將以下內(nèi)容添加為父依賴項:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version> </parent>Spring Boot公開了一個名為spring-boot-starter-web的啟動程序依賴項,該依賴項會自動導(dǎo)入開發(fā)和公開REST控制器所需的所有必需jar。 因此,我們將其添加為依賴項:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency>在本教程中,我們使用Spring Boot提供的嵌入式tomcat,因此我們將包裝屬性設(shè)置為jar,從而將應(yīng)用程序構(gòu)建為可運行的jar文件:
<packaging>jar</packaging>PS:如果要使用外部tomcat,請參閱“在外部tomcat上部署Spring Boot應(yīng)用程序” 。
最后的配置步驟是添加Spring Boot插件:
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins> </build>從字面上看,這就是我們開始開發(fā)REST控制器所需要的。
以下是Spring Boot自動導(dǎo)入的jar:
這是整個pom.xml供參考:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.programmer.gate</groupId><artifactId>SpringBootRest</artifactId><packaging>jar</packaging><version>0.0.1-SNAPSHOT</version><name>SpringBootRest</name><properties><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>3. Application.java
第二步是創(chuàng)建Spring Boot初始化器類,這是我們應(yīng)用程序的入口。 用@SpringBootApplication注釋類等效于在傳統(tǒng)的Spring應(yīng)用程序中使用@Configuration,@EnableAutoConfiguration和@ComponentScan及其默認屬性。
package com.programmer.gate;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class Application{public static void main(String[] args) {SpringApplication.run(Application.class, args);} }PS:默認情況下,servlet容器會自動掃描在初始化程序的同一程序包中定義的REST控制器,該程序包外部定義的任何控制器都將被忽略。
4.實施REST資源
我們將實現(xiàn)一個非常基本的支付API,向客戶收取購買商品的費用。
感謝jackson庫,我們的API僅接受JSON請求并以JSON響應(yīng)進行響應(yīng),這使我們能夠?qū)⒄埱蠛晚憫?yīng)作為POJO類處理,而不必擔(dān)心JSON / POJO轉(zhuǎn)換。
以下是客戶應(yīng)在每個付款請求上提交的付款請求類別:
package com.programmer.gate;public class PaymentRequest {private int userId;private String itemId;private double discount;public String getItemId() {return itemId;}public void setItemId(String itemId) {this.itemId = itemId;}public double getDiscount() {return discount;}public void setDiscount(double discount) {this.discount = discount;}public int getUserId() {return userId;}public void setUserId(int userId) {this.userId = userId;}}這是從我們的服務(wù)返回的基本響應(yīng):
package com.programmer.gate;public class BaseResponse {private String status;private Integer code;public String getStatus() {return status;}public void setStatus(String status) {this.status = status;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}}現(xiàn)在,我們定義下com.programmer.gate命名為PaymentController控制器:
package com.programmer.gate;import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;@RestController @RequestMapping("/payment") public class PaymentController {private final String sharedKey = "SHARED_KEY";private static final String SUCCESS_STATUS = "success";private static final String ERROR_STATUS = "error";private static final int CODE_SUCCESS = 100;private static final int AUTH_FAILURE = 102;@RequestMapping(value = "/pay", method = RequestMethod.POST)public BaseResponse pay(@RequestParam(value = "key") String key, @RequestBody PaymentRequest request) {BaseResponse response = new BaseResponse();if(sharedKey.equalsIgnoreCase(key)){int userId = request.getUserId();String itemId = request.getItemId();double discount = request.getDiscount();// Process the request// ....// Return success response to the client.response.setStatus(SUCCESS_STATUS);response.setCode(CODE_SUCCESS);}else{response.setStatus(ERROR_STATUS);response.setCode(AUTH_FAILURE);}return response;} }我們的控制器提供的唯一服務(wù)是pay()方法,該方法看起來非常簡單,它使用預(yù)定義的共享密鑰驗證客戶端請求,處理請求并以操作狀態(tài)進行響應(yīng)。
以下是控制器使用的常見注釋:
- @RestController:此注釋將類標記為資源,它隱式定義了@Controller和@ResponseBody mvc注釋,當(dāng)使用@RestController注釋類時, 無需在方法返回的POJO類旁邊編寫@ResponseBody 。
- @RequestMapping:除了方法類型: GET / POST之外 ,此注釋還定義了資源的url,在我們的示例中,我們將付款服務(wù)公開為POST ,可通過/ payment / pay訪問。
- @RequestParam:此注釋表示特定的請求參數(shù),在我們的示例中,我們將名為key的請求參數(shù)映射到String類型的參數(shù)鍵 。
- @RequestBody:此批注表示請求的主體,在我們的示例中,我們將請求的主體映射到類型為PaymentRequest的POJO類(jackson處理JSON / POJO轉(zhuǎn)換)
注意到響應(yīng)以BaseResponse表示,不需要注釋, 杰克遜將其隱式轉(zhuǎn)換為JSON。
5.部署應(yīng)用程序
以下是部署我們的應(yīng)用程序的步驟:
- 右鍵單擊pom.xml- >運行方式-> Maven安裝
- Maven在目標文件夾內(nèi)生成一個名為SpringBootRest-0.0.1-SNAPSHOT.jar的jar文件
- 打開cmd,然后使用以下命令運行jar: java -jar SpringBootRest-0.0.1-SNAPSHOT.jar
到這里,我們的應(yīng)用程序啟動,并準備在默認端口8080上處理請求。
6.測試服務(wù)
為了測試我們的API,我們使用來自chrome的Advanced REST客戶端插件,并發(fā)起2個不同的請求:
成功的請求:在此請求中,我們將有效的共享密鑰作為請求參數(shù)以及請求正文中的項目詳細信息傳遞。 它是這樣的:
這是我們的回應(yīng):
{"status": "success","code": 100 }失敗請求:此請求看起來與上面相似,但是共享密鑰無效,這是我們從API中獲得的:
{"status": "error","code": 102 }就是這樣,希望您發(fā)現(xiàn)它有用。
翻譯自: https://www.javacodegeeks.com/2018/03/build-rest-web-service-using-spring-boot.html
總結(jié)
以上是生活随笔為你收集整理的使用Spring Boot构建REST Web服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑硬盘鉴别真伪软件(用什么软件检测固态
- 下一篇: 对于面试应该怎么搞电脑如何面试