You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot POST请求传JSON时@ModelAttribute返回空值问题

问题原因及解决方案

核心原因

你用@ModelAttribute接收参数,但这个注解是用来处理**表单格式(application/x-www-form-urlencoded)**的请求体,而你通过Postman传递的是JSON格式(application/json),Spring无法自动将JSON数据绑定到@ModelAttribute修饰的对象上,所以content字段拿到空值。

解决步骤

  1. 替换注解为@RequestBody
    将控制器方法里的@ModelAttribute换成@RequestBody,这个注解专门用来接收JSON格式的请求体:

    @PostMapping("/create")
    public User addTask(@RequestBody User user) {
        user.setDone(false);
        System.out.println(user.getContent());
        return todoService.addTask(user);
    }
    
  2. 确保User类配置正确
    你的User类必须包含content字段的getter和setter方法,字段名称要和JSON请求里的key完全一致(大小写敏感),示例:

    public class User {
        private String content;
        private boolean done;
    
        // getter和setter方法
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public boolean isDone() {
            return done;
        }
    
        public void setDone(boolean done) {
            this.done = done;
        }
    }
    
  3. Postman请求配置检查

    • 请求头里必须添加Content-Type: application/json
    • 请求体选择raw格式,类型选JSON,输入示例JSON:
      {"content": "完成API开发"}
      

内容的提问来源于stack exchange,提问作者Khushi Saraswat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:57:03