<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring Boot 2 REST API 示例 > 原文: [https://howtodoinjava.com/spring-boot2/rest/rest-api-example/](https://howtodoinjava.com/spring-boot2/rest/rest-api-example/) 在本 Spring Rest 教程中,學習使用 Spring Boot 2 框架創建 REST API,該 API 將 JSON 響應返回給客戶端。 在本 **Spring Boot 2 REST API** 教程中,我們將逐步創建兩個簡單的 GET 和 POST API 并進行測試。 ## 1\. Maven 依賴 首先,[創建一個簡單的 Maven Web 項目](https://howtodoinjava.com/maven/maven-web-project-in-eclipse/),并根據`pom.xml`文件中的 spring boot 依賴項進行更新。 重要的依賴項是`spring-boot-starter-parent`([閱讀更多](https://howtodoinjava.com/spring-boot2/spring-boot-starter-parent-dependency/))和`spring-boot-starter-web`([閱讀更多](https://howtodoinjava.com/spring-boot2/spring-boot-starter-templates/))。 入門級 Web 依賴關系可傳遞地包含更多依賴關系,以構建 Web 應用程序,例如`spring-webmvc`,`spring-web`,`hibernate-validator`,`tomcat-embed-core`,`tomcat-embed-el`,`tomcat-embed-websocket`,`jackson-databind`,`jackson-datatype-jdk8`,`jackson-datatype-jsr310`和`jackson-module-parameter-names`。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.demo</groupId> <artifactId>springbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBootDemo</name> <description>Spring Boot2 REST API Demo for https://howtodoinjava.com</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` ## 2\. Spring Boot 2 REST API 控制器 * 在 Spring 中,能夠處理 REST API 請求的控制器類稱為 rest 控制器。 應使用`@RestController`注解進行注解。 * 資源 uri 在`@RequestMapping`注解中指定。 它可以同時應用于類級別和方法級別。 添加類級別路徑和方法級別路徑后,將解析 API 的完整 URI。 * 我們應該始終寫`produce`,`consume`屬性來指定 API 的媒體類型屬性。 切勿對假設作出響應。 在給定的控制器中,我們有兩種 API 方法。 隨時根據需要添加更多方法。 1. **HTTP GET `/employee`** - 返回員工列表。 2. **HTTP POST `/employee`** – 在員工集合中添加一個員工。 `EmployeeController.java` ```java package com.howtodoinjava.rest.controller; import java.net.URI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.howtodoinjava.rest.dao.EmployeeDAO; import com.howtodoinjava.rest.model.Employee; import com.howtodoinjava.rest.model.Employees; @RestController @RequestMapping(path = "/employees") public class EmployeeController { @Autowired private EmployeeDAO employeeDao; @GetMapping(path="/", produces = "application/json") public Employees getEmployees() { return employeeDao.getAllEmployees(); } @PostMapping(path= "/", consumes = "application/json", produces = "application/json") public ResponseEntity<Object> addEmployee(@RequestBody Employee employee) { Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1; employee.setId(id); employeeDao.addEmployee(employee); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(employee.getId()) .toUri(); return ResponseEntity.created(location).build(); } } ``` 我們可以使用`application.properties`文件來控制和自定義許多實現細節。 但是為了使此演示簡單,我將其保留為空白。 ## 3\. `@SpringBootApplication` 我們的 REST API 框架已準備就緒。 現在,我們需要配置 Spring 以檢測我們的 rest 控制器(使用自動掃描)并在嵌入式 tomcat 服務器中部署 api。 幸運的是,Spring Boot 通過使用[自動配置](https://howtodoinjava.com/spring-boot2/springbootapplication-auto-configuration/)的概念使所有這些事情變得非常容易。 **自動配置**嘗試猜測和配置您可能需要的 bean。 自動配置類通常基于應用程序類路徑中的 jar 和我們在`@Configuration`類中另外定義的 bean 來應用。 在這種情況下,它會執行以下操作。 1. 它檢測到`spring-webmvc`,因此配置默認的 spring mvc 應用程序 bean。 它有助于掃描和配置`@RestController`和類似的注解。 2. 它檢測到嵌入的 tomcat jar,因此為我們配置嵌入式 tomcat。 3. 它檢測到 JSON jar,因此可以配置對 API 的 JSON 支持。 `SpringBootDemoApplication.java` ```java package com.howtodoinjava.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoApplication.class, args); } } ``` ## 4\. 模型類和 DAO 這些類與 REST 沒有直接關系。 仍然讓我們看看它們是如何編寫的。 `Employee.java` ```java package com.howtodoinjava.rest.model; public class Employee { public Employee() { } public Employee(Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; //Getters and setters @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } } ``` `Employees.java` ```java package com.howtodoinjava.rest.model; import java.util.ArrayList; import java.util.List; public class Employees { private List<Employee> employeeList; public List<Employee> getEmployeeList() { if(employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList(List<Employee> employeeList) { this.employeeList = employeeList; } } ``` DAO 類使用靜態列表存儲數據。 在這里,我們需要實現實際的數據庫交互。 `EmployeeDAO.java` ```java package com.howtodoinjava.rest.dao; import org.springframework.stereotype.Repository; import com.howtodoinjava.rest.model.Employee; import com.howtodoinjava.rest.model.Employees; @Repository public class EmployeeDAO { private static Employees list = new Employees(); static { list.getEmployeeList().add(new Employee(1, "Lokesh", "Gupta", "howtodoinjava@gmail.com")); list.getEmployeeList().add(new Employee(2, "Alex", "Kolenchiskey", "abc@gmail.com")); list.getEmployeeList().add(new Employee(3, "David", "Kameron", "titanic@gmail.com")); } public Employees getAllEmployees() { return list; } public void addEmployee(Employee employee) { list.getEmployeeList().add(employee); } } ``` ## 5\. Spring Boot REST 演示 要啟動該應用程序,請運行`SpringBootDemoApplication`類中的`main()`方法。 它將啟動嵌入式 tomcat 服務器。 在服務器日志中,您將看到已在 Spring 上下文中注冊了 API。 `Console` ```java s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/employees/],methods=[GET],produces=[application/json]}" onto public com.howtodoinjava.rest.model.Employees com.howtodoinjava.rest.controller. EmployeeController.getEmployees() s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/employees/],methods=[POST], consumes=[application/json], produces=[application/json]}" onto public org.springframework.http.ResponseEntity <java.lang.Object> com.howtodoinjava.rest.controller. EmployeeController.addEmployee( com.howtodoinjava.rest.model.Employee ) ``` #### 5.1. HTTP GET `/employee` 服務器啟動后,使用其他客戶端訪問 API。 ![Spring Boot REST HTTP GET](https://img.kancloud.cn/ab/04/ab047cb4e3290b7f14d9db4b0b736fa4_977x455.jpg) Spring Boot REST HTTP GET `API response` ```java { "employeeList": [ { "id": 1, "firstName": "Lokesh", "lastName": "Gupta", "email": "howtodoinjava@gmail.com" }, { "id": 2, "firstName": "Alex", "lastName": "Kolenchiskey", "email": "abc@gmail.com" }, { "id": 3, "firstName": "David", "lastName": "Kameron", "email": "titanic@gmail.com" } ], } ``` #### 5.2. HTTP POST `/employee` ![Spring Boot REST HTTP POST](https://img.kancloud.cn/b0/39/b039e404c6de4aea4f54e3439776778c_976x397.jpg) Spring Boot REST HTTP POST `Response headers` ```java location: http://localhost:8080/employees/4 content-length: 0 date: Sat, 06 Oct 2018 04:33:37 GMT ``` 再次點擊 GET 請求,這一次我們也將獲得新增的員工。 ![Spring Boot REST HTTP GET - Updated](https://img.kancloud.cn/ad/6f/ad6f90223ee96c9de180d75278cb0943_501x526.jpg) Spring Boot REST HTTP GET – Updated ## 6\. 更多例子 1. [Spring`@Controller`和`@RestController`注解](https://howtodoinjava.com/spring-boot2/controller-restcontroller/) 讓我知道您是否在此 **spring boot restful web 服務 json 示例**中進行查詢。 學習愉快! [下載源碼](https://howtodoinjava.com/wp-content/downloads/springbootrestdemo.zip) 參考文獻: [SpringBoot 啟動器](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看