3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ResponseEntityクラスについて

Last updated at Posted at 2024-10-22

ResponseEntityクラスは、Spring FrameworkにおけるHTTPレスポンスのカプセル化に使用されるクラスです。通常、コントローラーがクライアントに返すレスポンスには、以下の3つの要素が含まれますが、ResponseEntityはそれらをひとつのオブジェクトにまとめて処理することができます。

ResponseEntityの要素

  1. HTTPステータスコード (HttpStatus)

    • 例: 200 OK, 201 Created, 404 Not Found など。
    • クライアントにレスポンスの成功や失敗を示すために使用されます。
  2. レスポンスボディ (任意のオブジェクト)

    • 返すデータをオブジェクト形式で含めます(JSONやXMLなどに変換されます)。
    • 例: UserDtoオブジェクト、エラーメッセージなど。
  3. HTTPヘッダー (HttpHeaders)

    • レスポンスにヘッダーを追加できます。
    • 例: 認証情報、キャッシュ制御、コンテンツタイプの指定など。

ResponseEntityの使用例

ResponseEntityを使うことで、レスポンスにステータスコードやカスタムヘッダーを柔軟に追加でき、レスポンスボディも一緒に返すことができます。これにより、エラーハンドリングや成功レスポンスを細かく制御することが可能です。

1. 基本的な使用例

例1: 成功時のレスポンス (200 OK)

以下は、データを200 OKで返す例です。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user")
    public ResponseEntity<String> getUser() {
        String user = "John Doe"; // 取得したユーザー情報(シンプルな例)
        return new ResponseEntity<>(user, HttpStatus.OK);
    }
}
  • ResponseEntity<>(user, HttpStatus.OK): 取得したデータ user をレスポンスボディとして返し、HTTPステータスは 200 OK を指定しています。

2. エラーハンドリング

例2: エラー時のレスポンス (404 Not Found)

以下は、指定したユーザーが見つからなかった場合に 404 Not Found を返す例です。

@GetMapping("/user/{id}")
public ResponseEntity<String> getUserById(@PathVariable("id") int id) {
    String user = findUserById(id); // ユーザーを検索する仮のメソッド
    if (user == null) {
        return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<>(user, HttpStatus.OK);
}
  • HttpStatus.NOT_FOUND: ユーザーが見つからなかった場合に 404 Not Found を返します。
  • "User not found": レスポンスボディにエラーメッセージを含めています。

3. カスタムヘッダーを含めたレスポンス

例3: カスタムヘッダーを追加したレスポンス

以下は、レスポンスにカスタムヘッダーを追加して返す例です。

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/custom-header")
    public ResponseEntity<String> getCustomHeaderResponse() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Custom-Header", "CustomValue");

        return new ResponseEntity<>("Custom header response", headers, HttpStatus.OK);
    }
}
  • HttpHeaders: カスタムヘッダーを設定するためのクラス。
  • headers.add("Custom-Header", "CustomValue"): カスタムヘッダー Custom-Header に値 CustomValue を追加しています。

4. ResponseEntityビルダーを使った柔軟なレスポンス構築

Springは、ResponseEntityを構築するためにチェーンメソッドを提供するビルダーパターンもサポートしています。これにより、レスポンスをより簡潔に作成できます。

例4: ビルダーパターンを使ったレスポンス構築

@GetMapping("/builder")
public ResponseEntity<String> getResponseUsingBuilder() {
    return ResponseEntity
            .status(HttpStatus.OK)
            .header("Custom-Header", "HeaderValue")
            .body("Response using ResponseEntity builder");
}
  • ResponseEntity.status(HttpStatus.OK): ステータスコードを 200 OK に設定します。
  • header("Custom-Header", "HeaderValue"): カスタムヘッダーを追加します。
  • body("Response using ResponseEntity builder"): レスポンスボディを設定します。

5. ResponseEntityの返却パターンまとめ

  • 200 OK(成功):

    return ResponseEntity.ok(data); // 簡単に200 OKでデータを返す
    
  • 404 Not Found(データが見つからない):

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Data not found");
    
  • 201 Created(新規作成成功):

    return ResponseEntity.status(HttpStatus.CREATED).body(newData);
    
  • 204 No Content(データ削除成功など):

    return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); // レスポンスボディなし
    
  • 500 Internal Server Error(サーバーエラー):

    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Server error");
    

まとめ

ResponseEntityは、HTTPステータスコード、レスポンスボディ、ヘッダーを柔軟に設定できる非常に便利なクラスです。エラーハンドリング、カスタムヘッダーの追加、ビルダーパターンなど、様々な場面で活用できます。

主な特徴

  • ステータスコードの柔軟な指定:エラーハンドリングやリソース作成成功時のレスポンスに使用できます。
  • レスポンスボディのカスタマイズ:任意のオブジェクト(DTOやエラーメッセージなど)をボディとして返却できます。
  • HTTPヘッダーの追加:カスタムヘッダーや標準のヘッダーを追加して、レスポンスに必要な情報を付加できます。
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?