首页 > Java > java教程 > 正文

如何忽略 Spring MVC 的 JSON 响应中的敏感字段?

Barbara Streisand
发布: 2024-10-26 09:40:30
原创
690 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!