2022就业季|Spring认证教你,如何使用 Spring 构建 REST 服务(二)

书接上文⬆⬆⬆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中国教育管理中心留言交流!

评论

暂无评论