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 detail? 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 the default version of the dependencies as follows:
1 2 3 4 5 6 7 8 9 |
<properties> <maven.compiler.source>21</maven.compiler.source> <maven.compiler.target>21</maven.compiler.target> <org.springframework-version>6.1.10</org.springframework-version> <org.slf4j-version>2.0.13</org.slf4j-version> <org.junit-version>5.10.2</org.junit-version> <jakarta.servlet-api-version>6.1.0</jakarta.servlet-api-version> </properties> |
To run this project, I will use the Maven Jetty Plugin:
1 2 3 4 5 |
<plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>11.0.21</version> </plugin> |
Now we will define a new Controller located 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.