首頁  >  文章  >  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 註解相應的 getter 方法。這將在 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn