使用 Enums 管理网页响应
使用 enums 管理 HTTP 响应,可以简化在 Web 应用中处理不同状态码的流程。本练习演示如何创建包含额外信息(如 HTTP 状态码)的 enums。
本练习是课程的一部分
Java 中的输入/输出与流
练习说明
- 为
HttpStatus构造函数定义一个int参数code。 - 当调用
getCode()方法时,返回字段code。 - 打印状态
OK的HttpStatus代码。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class HttpStatusExample {
enum HttpStatus {
OK(200), NOT_FOUND(404);
private int code;
// Constructor for the HttpStatus with status code
HttpStatus(____ code) {
this.code = code;
}
public int getCode() {
// Return the code for a specific HTTP status
return ____;
}
}
public static void main(String[] args) {
// Call method to print the status code
System.out.println(HttpStatus.OK.____());
}
}