To specify the format that a request can process for a user request, such as the JSON data format, we can use the @RequestMapping annotation with the consumes property in Spring MVC. How is it in details? Let’s find out in this tutorial!
First, I will create a Maven project as an example:
If you do not know how to create the project, just follow the instructions of this tutorial.
I will change default version of the dependencies as follows:
1 2 3 4 5 6 |
<properties> <java-version>1.8</java-version> <org.springframework-version>5.0.0.RELEASE</org.springframework-version> <org.aspectj-version>1.8.11</org.aspectj-version> <org.slf4j-version>1.7.25</org.slf4j-version> </properties> |
To run this project, I will use Maven Jetty Plugin:
1 2 3 4 5 |
<plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.7.v20170914</version> </plugin> |
Now we will define a new Controller locating in the com.huongdanjava.springmvcrequestmapping package, named HelloController. This controller only accepts requests that the data format is JSON. The contents of HelloController are as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.huongdanjava.springmvcrequestmapping; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping(value = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE) public String hello() { return "Hello World!"; } } |
At this point, if you use Postman to request this URL with the GET method and do not transmit anything else, you will get the following result:
To fix this, you must modify the header of the request by adding the Content-Type=application/json attribute. At that point, our request will be free of errors.