The problem I'm facing is when I try to do a POST REQUEST such as:
curl -H "Content" -X POST -d '{"content":"abc"}' http://localhost:8080/posts
I end up getting an new post but without any data:
{
id: 4,
content: null,
comment: [ ]
}
I have some preloaded data from an SQL file (I have enabled H2 in my project):
INSERT INTO post(id, content) VALUES (1, 'This is a post')
INSERT INTO post(id, content) VALUES (2, 'This is a post')
INSERT INTO post(id, content) VALUES (3, 'This is a post')
My entity:
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String content;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "post")
private Set<Comment> comment;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Set<Comment> getComment() {
return comment;
}
public void setComment(Set<Comment> comment) {
this.comment = comment;
}
}
From my controller:
@PostMapping("/posts")
public @ResponseBody String add(@ModelAttribute Post p){
postRepository.save(p);
return "{msg : Resource added }";
}
In my research for this problem I have learned you can use an RestController, however I'm not using this in my example as my code is from my school project and the teacher wants us to use @ResponseBody etc.
Is my @PostMapping method missing something? or is it my curl statement that is wrong?
The main reason why
@ModelAttibute
is not working in your case because it is bounded on form post parameters and there is no form in your case.Where with
@RequestBody
you get the request body directly. This is the reason your@ModelAttribute
not workingTo use
@ModelAttribute
you have to create a form withmodelattribute
Something like below
And then in your controller,something like
But as you are using
curl
for your requests best suitable is@RequestBody
for getting post parameters.Further reading here