How make a correct POST request to my Spring REST project

78 views Asked by At

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?

1

There are 1 answers

0
Shubham Dixit On BEST ANSWER

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 working

To use @ModelAttribute you have to create a form with modelattribute

Something like below

  <form:form method="POST" action="/posts"
      modelAttribute="posts">
        <form:label path="name">Name</form:label>
        <form:input path="name" />

        <form:label path="id">Id</form:label>
        <form:input path="id" />

        <input type="submit" value="Submit" />
    </form:form>

And then in your controller,something like

@PostMapping("/posts")
    public @ResponseBody String add(@ModelAttribute("posts") Post p){

        postRepository.save(p);

        return "{msg : Resource added }";
    }

But as you are using curl for your requests best suitable is @RequestBodyfor getting post parameters.

Further reading here