Spring Boot @ResponseStatus
最后修改于 2023 年 7 月 16 日
Spring Boot @ResponseStatus 教程展示了如何在 Spring 应用程序中使用 @ResponseStatus 注解。
Spring 是一个流行的 Java 应用程序框架,而 Spring Boot 是 Spring 的一个演进,它有助于轻松创建独立的、生产级的基于 Spring 的应用程序。
@ResponseStatus
@ResponseStatus 用状态码和原因消息标记方法或异常类,这些状态码和原因消息应该被返回。当调用处理程序方法或抛出指定异常时,状态码将应用于 HTTP 响应。它会覆盖通过其他方式设置的状态信息,例如 ResponseEntity 或 redirect:。
Spring Boot @ResponseStatus 示例
在以下应用程序中,我们演示了 @ResponseStatus 注解的用法。该应用程序模拟一个通过订单 ID 检索订单的表单。尝试查找 ID 大于 500 的订单将抛出异常。由于此异常,将显示自定义错误页面。
build.gradle
...
src
├── main
│ ├── java
│ │ └── com
│ │ └── zetcode
│ │ ├── Application.java
│ │ ├── controller
│ │ │ └── MyController.java
│ │ └── exception
│ │ └── OrderNotFoundException.java
│ └── resources
│ ├── static
│ │ └── index.html
│ └── templates
│ └── error.ftlh
└── test
├── java
└── resources
这是 Spring 应用程序的项目结构。
plugins {
id 'org.springframework.boot' version '3.1.1'
id 'io.spring.dependency-management' version '1.1.0'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
}
这是 Gradle 构建文件。spring-boot-starter-freemarker 是 Freemarker 模板引擎的依赖项。
package com.zetcode.controller;
import com.zetcode.exception.OrderNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping(value = "/orders/{id}")
@ResponseBody
public String getOrder(@PathVariable("id") long id) {
if (id < 0 || id > 500) {
var message = String.format("Order %d not found", id);
throw new OrderNotFoundException(message);
}
var message = String.format("Returning order %d", id);
return message;
}
}
MyController 的 getOrder 方法响应客户端请求。它使用 @PathVariable 从路径中读取订单 ID。
if (id < 0 || id > 500) {
var message = String.format("Order %d not found", id);
throw new OrderNotFoundException(message);
}
对于无效订单 (id < 0) 和 ID 大于 500 的订单,我们抛出 OrderNotFoundException 异常。这只是一个简单的订单系统模拟。
var message = String.format("Returning order %d", id);
对于其他订单 ID,我们返回一条消息,指示已找到并返回订单。
package com.zetcode.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such order")
public class OrderNotFoundException extends RuntimeException {
public OrderNotFoundException(String message) {
super(message);
}
}
我们有一个自定义的 OrderNotFoundException。它使用 @ResponseStatus 注解进行修饰。值设置为 HttpStatus.NOT_FOUND,原因消息为“No such order”。此信息将在错误页面中使用。
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="/orders/505/">Get order with Id 505</a>
</body>
</html>
这是主页。它包含一个链接,用于查找 ID 为 505 的订单。该文件位于 src/main/resources/static 目录中。
<html>
<head>
<title>Error page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<h1>Error occurred</h1>
<p>${status}: ${error}</p>
</div>
</body>
</html>
error.ftlh 是一个通用错误页面。它是一个 Freemarker 模板文件,显示状态、错误和原因消息。这些值先前使用 @ResponseStatus 设置。它位于 src/main/resources/templates 目录中。
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Application 是设置 Spring Boot 应用程序的入口点。
在本文中,我们展示了如何在 Spring 应用程序中使用 @ResponseStatus 注解。