Languages

Spring POST method - accept and return JSON in REST controller

10 points
Asked by:
Root-ssh
178180

How to accept and return JSON from Spring controller with http post?

Current code that doesn't work:

How to make this work?

2 answers
5 points
Answered by:
Root-ssh
178180

@RequestMapping example

To make this POST request work, we need to add:

  1. consumes = MediaType.APPLICATION_JSON_VALUE
  2. produces = MediaType.APPLICATION_JSON_VALUE
  3. @ResponseBody

Important - don't forget to add @ResponseBody, as very often people forget to add this annotation is it causes 404 error from Spring Controller (HTTP Status 404 – Not Found).

Using String in consumes and produces

We can use simple String in consumes = "application/json" and produces = "application/json".

Alternative solution insted of using MediaType.APPLICATION_JSON_VALUE we can just use String, example:

consumes and produces is just simple String with value "application/json",

org.springframework.http.MediaType internally looks like this:

Full working spring controller

To setup this example we have 4 parts:

  1. RequestMappingController class
  2. jquery_ajax_post_json.html
  3. UserRequest class
  4. UserResponse class

1. RequestMappingController class

2. jquery_ajax_post_json.html

Here we have jQuery ajax request with this controller running on our test server.

3. UserRequest class

4. UserResponse class

 

0 commentsAdd comment
2 points
Answered by:
AnnLen
15120

Alternative solution to using @RequestMapping is using @PostMapping annotation.

Example:

The difference is that we don't need to add: 

 

0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join