ホームページ  >  記事  >  Java  >  Spring MVCからのJSON応答の機密フィールドを無視する方法は?

Spring MVCからのJSON応答の機密フィールドを無視する方法は?

Barbara Streisand
Barbara Streisandオリジナル
2024-10-26 09:40:30691ブラウズ

How to Ignore Sensitive Fields in JSON Responses from Spring MVC?

Spring MVC からの JSON 応答の機密フィールドを無視する

RESTful API で機密情報を処理する場合、どのフィールドのフィールドを制御するかが重要です。モデル オブジェクトは JSON 応答で公開されます。 Spring MVC では、オブジェクトを JSON として送信するときに特定のフィールドを動的に除外できます。

アノテーションを使用したモデル オブジェクトの設計

次を使用して Java モデル クラス (@Entity) を構成します。 @JsonIgnoreProperties(ignoreUnknown = true) アノテーション。これにより、JSON をオブジェクトに逆シリアル化するときに不明なプロパティが無視されます。

<code class="java">@Entity
@Table(name = "user")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    // ... (Model fields)
}</code>

コントローラー メソッド

Spring MVC コントローラーでは、次を使用してデータベースからユーザー オブジェクトを取得します。サービス層。

<code class="java">@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
@ResponseBody
public User getUser(@PathVariable Integer userId) throws Exception {
    User user = userService.get(userId);
    return user;
}</code>

アノテーションを使用した選択的除外

特定のフィールドを選択的に除外するには、対応するゲッター メソッドに @JsonIgnore アノテーションを付けます。これにより、JSON シリアル化中にこれらのフィールドが無視されます。

<code class="java">@JsonIgnore
public String getEncryptedPwd() {
    return encryptedPwd;
}</code>

動的除外

除外されるフィールドのリストがユーザーに応じて異なる場合は、カスタム ソリューション:

<code class="java">@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
@ResponseBody
public User getUser(@PathVariable Integer userId, @RequestHeader("username") String username) {
    User user = userService.get(userId);
    
    // Get excluded fields list based on the logged-in user
    List<String> excludedFields = getExcludedFields(username);
    
    // Iterate through the excluded fields and set their values to null
    for (String field : excludedFields) {
        switch (field) {
            case "encryptedPwd":
                user.setEncryptedPwd(null);
                break;
            // ... (Similar logic for other fields)
        }
    }
    
    return user;
}</code>

以上がSpring MVCからのJSON応答の機密フィールドを無視する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。