关于spring:2022就业季|Spring认证教你如何使用-Spring-构建-REST-服务二

3次阅读

共计 4592 个字符,预计需要花费 12 分钟才能阅读完成。

书接上文⬆⬆⬆HTTP 是平台要应用 Web 档次包装您的存储库,您必须应用 Spring MVC。多亏了 Spring Boot,代码基础设施很少。相同,咱们能够专一于口头:nonrest/src/main/java/payroll/EmployeeController.javapackage 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;@RestControllerclass EmployeeController {private final EmployeeRepository repository;EmployeeController(EmployeeRepository repository) {this.repository = repository;}// Aggregate root// tag::get-aggregate-root[]@GetMapping(“/employees”)List<Employee> 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 示意每个办法返回的数据会间接写入响应体,而不是渲染模板。AnEmployeeRepository 由构造函数注入到控制器中。咱们有每个操作的路由(@GetMapping、@PostMapping、@PutMapping 和 @DeleteMapping,对应于 HTTP GET、POST、PUT 和 DELETE 调用)。(留神:浏览每种办法并理解它们的作用很有用。)EmployeeNotFoundException 是用于批示何时查找但未找到员工的异样。nonrest/src/main/java/payroll/EmployeeNotFoundException.javapackage payroll;class EmployeeNotFoundException extends RuntimeException {EmployeeNotFoundException(Long id) {super(“Could not find employee ” + id);}}当 EmployeeNotFoundException 抛出 an 时,Spring MVC 配置的这个额定花絮用于出现 HTTP 404:nonrest/src/main/java/payroll/EmployeeNotFoundAdvice.javapackage 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;@ControllerAdviceclass EmployeeNotFoundAdvice {@ResponseBody@ExceptionHandler(EmployeeNotFoundException.class)@ResponseStatus(HttpStatus.NOT_FOUND)String employeeNotFoundHandler(EmployeeNotFoundException ex) {return ex.getMessage();}}@ResponseBody 示意此倡议间接出现到响应注释中。@ExceptionHandlerEmployeeNotFoundException 将倡议配置为仅在抛出 an 时才响应。@ResponseStatus 说要收回一个 HttpStatus.NOT_FOUND,即一个 HTTP 404。倡议的主体生成内容。在这种状况下,它会给出异样的音讯。要启动应用程序,请右键单击其中并从 IDEpublic static void main 中 PayRollApplication 抉择运行,或者:Spring Initializr 应用 maven 包装器,所以输出:$ ./mvnw clean spring-boot:run 或者应用您装置的 Maven 版本输出:$ mvn clean spring-boot:run 当应用程序启动时,咱们能够立刻对其进行询。$ curl -v localhost:8080/ 员工这将产生:* 尝试 ::1…* TCP_NODELAY 设置 * 连贯到 localhost (::1) 端口 8080 (#0)> GET / 员工 HTTP/1.1> 主机:本地主机:8080> 用户代理:curl/7.54.0> 承受:*/*>< HTTP/1.1 200< 内容类型:application/json;charset=UTF-8< 传输编码:分块 < 日期:格林威治规范工夫 2018 年 8 月 9 日星期四 17:58:00<* 连贯 #0 到主机 localhost 放弃不变 [{“id”:1,”name”:”Bilbo Baggins”,”role”:” 窃贼 ”},{“id”:2,”name”:”Frodo Baggins”,” 角色 ”:” 小偷 ”} ] 在这里,您能够看到压缩格局的预加载数据。如果您尝试查问一个不存在的用户 ……$ curl -v localhost:8080/employees/99 你失去… 尝试 ::1… TCP_NODELAY 设置 连贯到 localhost (::1) 端口 8080 (#0)> 获取 /employees/99 HTTP/1.1> 主机:本地主机:8080> 用户代理:curl/7.54.0> 承受:/>< HTTP/1.1 404< 内容类型: text/plain;charset=UTF-8< 内容长度:26< 日期:格林威治规范工夫 2018 年 8 月 9 日星期四 18:00:56< 连贯 #0 到主机 localhost 放弃不变找不到员工 99 此音讯很好地显示了 HTTP 404 谬误以及自定义音讯 Could not find employee 99。显示以后编码的交互并不难……​如果您应用 Windows 命令提示符收回 cURL 命令,则以下命令可能无奈失常工作。您必须抉择一个反对单引号参数的终端,或者应用双引号,而后本义 JSON 中的那些。要创立新 Employee 记录,咱们在终端中应用以下命令——$ 结尾的示意前面是终端命令:$ curl -X POST localhost:8080/employees -H ‘Content-type:application/json’ -d ‘{“name”: “Samwise Gamgee”, “role”: “gardener”}’ 而后它存储新创建的员工并将其发送回给咱们:{“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”:” 戒指持有者 ”}您构建服务的形式可能会产生重大影响。在这种状况下,咱们说 update,但 replace 是更好的形容。例如,如果未提供名称,则它将被勾销。最初,您能够像这样删除用户:$ curl -X DELETE 本地主机:8080/employees/3# 当初如果咱们再看一遍,它就不见了 $ curl localhost:8080/employees/ 3 找不到员工 3 这所有都很好,然而咱们有 RESTful 服务了吗?(如果你没有听懂提醒,答案是否定的。)少了什么货色?…… 未完待续 ……2022 待业季|Spring 认证教你,如何应用 Spring 构建 REST 服务 #java##spring##spring 认证##2022 待业季#

以上就是明天对于 Spring 的一些探讨,对你有帮忙吗?如果你有趣味深刻理解,欢送到 Spring 中国教育管理中心留言交换!

正文完
 0