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 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, 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.