【发布时间】: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"}
注意我假设我可以在不发送id 或cards 参数的情况下离开,因为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