javascript
Spring Boot:构建一个RESTful Web应用程序
介紹:
REST代表表示狀態傳輸 ,是API設計的體系結構指南。 我們假設您已經具有構建RESTful API的背景。
在本教程中,我們將設計一個簡單的Spring Boot RESTful Web應用程序,公開一些REST端點。
項目設置:
讓我們首先通過Spring Initializr下載項目模板:
對于RESTful Web應用程序,我們只需要添加“ Spring Web”作為額外的入門依賴。 假設我們也在與數據庫進行交互,則添加了其他兩個。
現在,我們的POM文件將具有所有需要的Web應用程序和數據庫依賴性:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope> </dependency>REST控制器:
現在讓我們定義REST控制器:
@RestController @RequestMapping("/student") public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/all")public ResponseEntity<List<Student>> getAllStudents() {return new ResponseEntity<List<Student>>(studentService.getAllStudents(), HttpStatus.OK);}@GetMapping("/{id}") public ResponseEntity<Student> getStudentById(@PathVariable("id") Integer id) {Optional<Student> student = studentService.getById(id);if(student.isPresent())return new ResponseEntity<Student>(student.get(), HttpStatus.OK);else throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No student found!"); }@PostMapping("/")public ResponseEntity<Student> createStudent(@RequestBodyStudent student) {Student newStudent = studentService.store(student);return new ResponseEntity<Student>(newStudent, HttpStatus.CREATED);}... }我們可以在控制器中定義所有的GET,POST,DELETE或PUT映射。
服務:
在這里, StudentService是與數據庫交互并為我們執行所有操作的類:
@Service public class StudentService {@Autowiredprivate StudentRepository repo;public Student store(Student student) {return repo.save(student);}public List<Student> getAllStudents() {return repo.findAll();}...}我們還有另一本教程,說明如何使用Spring Boot配置H2數據庫。
運行應用程序:
最后,我們可以運行我們的UniversityApplication類:
@SpringBootApplication public class UniversityApplication {public static void main(String[] args) {SpringApplication.run(UniversityApplication.class, args);} }通過它,我們的REST端點將在嵌入式服務器上公開。
測試REST端點:
讓我們使用cURL來測試我們的REST端點:
$ curl http://localhost:8080/student/all這將返回數據庫中存在的所有學生記錄:
[{1, "James"}, {2, "Selena"}, {3, "John"}]同樣,我們有:
$ curl http://localhost:8080/student/1 {1, "James"}我們還可以使用POSTman工具來測試我們的端點。 它具有出色的用戶界面。
結論:
在本教程中,我們從頭開始構建了一個Spring Boot RESTful應用程序。 我們公開了一些API,然后使用cURL對其進行了測試。
翻譯自: https://www.javacodegeeks.com/2019/09/spring-boot-building-restful-web-application.html
總結
以上是生活随笔為你收集整理的Spring Boot:构建一个RESTful Web应用程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑自动开机方案如何设定电脑自动开机
- 下一篇: Spring Boot登录选项快速指南