To specify the data format that will be returned to the user when they request a URL, in Spring MVC we can use the @RequestMapping annotation with the produces attribute. 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 in 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, I will define a new Controller located in the com.huongdanjava.springmvcrequestmapping package called HelloController. This controller defines a request and when the user requests it, it returns the text “Hello World!”. The content of StudentController is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava.springmvcrequestmapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping(value = "/hello") public String hello() { return "Hello World!"; } } |
Now, if you use Postman to check the results, you will see that the request returns “Hello World!” with the following header:
The data returned in data format text/plain.
Now, if you want the data returned in JSON format, you can add the produces attribute in the @RequestMapping annotation with the value of “application/json” 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", produces = MediaType.APPLICATION_JSON_VALUE) public String hello() { return "Hello World!"; } } |
then, we will get the result with the header as follows:
As you can see, the content type returned at this time is application/json and not text/plain anymore. Of course, if you want: the text returned, you should change it to JSON format.