用 Enums 管理網頁回應
使用 enums 管理 HTTP 回應,可以簡化在網頁應用程式中處理不同狀態代碼的流程。這個練習會示範如何建立包含額外資訊(例如 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.____());
}
}