首页  >  文章  >  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