营销网站的渠道构成基本包括,dz论坛做分类网站,做网站一次付费,简单5步_制作wordpress留言板介绍#xff1a; REST代表表示状态传输 #xff0c;是API设计的体系结构指南。 我们假设您已经具有构建RESTful API的背景。 在本教程中#xff0c;我们将设计一个简单的Spring Boot RESTful Web应用程序#xff0c;公开一些REST端点。 项目设置#xff1a; 让我们首先通… 介绍 REST代表表示状态传输 是API设计的体系结构指南。 我们假设您已经具有构建RESTful API的背景。 在本教程中我们将设计一个简单的Spring Boot RESTful Web应用程序公开一些REST端点。 项目设置 让我们首先通过Spring Initializr下载项目模板 对于RESTful Web应用程序我们只需要添加“ Spring Web”作为额外的入门依赖。 假设我们也在与数据库进行交互则添加了其他两个。 现在我们的POM文件将具有所有需要的Web应用程序和数据库依赖性 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId
/dependency
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactId
/dependency
dependency groupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId
/dependency
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId
/dependency
dependencygroupIdcom.h2database/groupIdartifactIdh2/artifactIdscoperuntime/scope
/dependencyREST控制器 现在让我们定义REST控制器 RestController
RequestMapping(/student)
public class StudentController {Autowiredprivate StudentService studentService;GetMapping(/all)public ResponseEntityListStudent getAllStudents() {return new ResponseEntityListStudent(studentService.getAllStudents(), HttpStatus.OK);}GetMapping(/{id}) public ResponseEntityStudent getStudentById(PathVariable(id) Integer id) {OptionalStudent student studentService.getById(id);if(student.isPresent())return new ResponseEntityStudent(student.get(), HttpStatus.OK);else throw new ResponseStatusException(HttpStatus.NOT_FOUND, No student found!); }PostMapping(/)public ResponseEntityStudent createStudent(RequestBodyStudent student) {Student newStudent studentService.store(student);return new ResponseEntityStudent(newStudent, HttpStatus.CREATED);}...
} 我们可以在控制器中定义所有的GETPOSTDELETE或PUT映射。 服务 在这里 StudentService是与数据库交互并为我们执行所有操作的类 Service
public class StudentService {Autowiredprivate StudentRepository repo;public Student store(Student student) {return repo.save(student);}public ListStudent 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