【问题标题】:Spring POST receives object with null valuesSpring POST 接收具有空值的对象
【发布时间】:2018-05-17 01:04:19
【问题描述】:

我有一个 AngularJS Web 应用程序,看起来它正在正确地将 JSON 发送到 Tomcat 服务器,但服务器接收到空值。 This question 没有帮助,因为我的属性名称已经是小写的,而 this question 没有帮助,因为我已经有了 @RequestBody 符号。 编辑:正如 cmets 中所指出的,我实际上没有这个符号。我读错了。

这里是有问题的服务器方法:

@PostMapping(path="/kind/add")
public @ResponseBody String addNewKind(Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    kindRepository.save(kind);
    return "Saved";
}

这是它期望接收的 Kind 对象:

@Entity
public class Kind {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy="kind")
    private Set<Card> cards;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Card> getCards() {
        return cards;
    }

    public void setCards(Set<Card> cards) {
        this.cards = cards;
    }
}

这是发出请求的方法:

var uri = 'http://localhost:8080/catalog/api/kind/';

function create(name) {
    var deferred = $q.defer();
    var data = {
        'name': name
    };
    $http({
        method: 'POST',
        url: uri + 'add',
        data: angular.toJson(data),
        headers: {
            'Content-Type': 'application/json; charset=UTF-8'
        }
    }).then(function(response) {
        deferred.resolve(response.data);
    }).catch(function(error) {
        console.error('Error while adding kind');
        deferred.reject(error);
    });
    return deferred.promise;
}

这是发送到服务器的 JSON:

{"name":"Something"}

注意我假设我可以在不发送idcards 参数的情况下离开,因为id 是自动生成的,cards 可以为空;但是,在发送以下 JSON 时,我得到相同的 null 结果:

{"id":0,"name":"Something","cards":[]}

这些是请求标头:

Accept:           application/json, text/plain, */*
Accept-Encoding:  gzip, deflate
Accept-Language:  en-US,en;q=0.5
Connection:       keep-alive
Content-Length:   20
Content-Type:     application/json; charset=UTF-8
Cookie:            __distillery=08c4ef1_752470a4-…ID=lr9remoqoi0ht13v1urq5lq8r7
Host:             localhost:8080
Referer:          http://localhost:8080/catalog/
User-Agent:       Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/57.0

这是我在调试模式下查看kind 对象参数时服务器收到的内容:

kind= Kind
    cards= null
    id= 0
    name= null

【问题讨论】:

  • "...,因为我已经有了 @RequestBody 表示法" - 在哪里?我只看到@ResponseBody
  • @helospark 你说得对,真丢人!我在看@RequestBody 和阅读@ResponseBody

标签: javascript java angularjs spring


【解决方案1】:

您需要在方法上使用@RequestBody 注释。您的控制器不知道主体是什么,因此您发布的对象永远不会绑定(或永远不会“成功”)到您方法的 Kind 参数。

@PostMapping(path="/kind/add")
public String addNewKind(@RequestBody Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    kindRepository.save(kind);
    return "Saved";
}

如果您希望返回新的“Kind”,您希望控制器方法如下所示:

@PostMapping(path="/kind/add")
public Kind addNewKind(@RequestBody Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    return kindRepository.save(kind);
}

在旁注中,我注意到您在写出 JSON 时使用了单引号。由于您正在使用angular.toJson() 转换数据,因此您应该没问题。如果您尝试通过直接发送 JSON 字符串进行交互,这通常不起作用。 JSON 不使用单引号。

【讨论】:

  • 谢谢。我已经编辑了上面的 JSON,所以以后阅读该问题的任何人都不会感到困惑。
猜你喜欢
  • 1970-01-01
  • 2018-08-12
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 2020-09-06
  • 1970-01-01
  • 2018-11-18
相关资源
最近更新 更多