I have an AngularJS web application that looks like it is correctly sending JSON to the Tomcat server, but the server receives null values. This question didn't help because my property names are already lowercase, and this question didn't help because I've already got the @RequestBody
notation. Edit: as pointed out in the comments, I don't actually have this notation. I was reading it wrong.
Here is the server method in question:
@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";
}
Here is the Kind object it expects to receive:
@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;
}
}
Here is the method that makes the request:
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;
}
This is the JSON sent to the server:
{"name":"Something"}
N.B. I assumed that I can get away without sending id
or cards
parameters, since id
is auto-generated and cards
can be empty; however, I get the same null results when sending the following JSON:
{"id":0,"name":"Something","cards":[]}
These are the request headers:
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
And this is what the server receives when I view the kind
object argument in debug mode:
kind= Kind
cards= null
id= 0
name= null
See Question&Answers more detail:
os