Using @RequestMapping annotation with attribute produces in Spring MVC

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:

Using @RequestMapping annotation with attribute produces in Spring MVC

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:

To run this project, I will use Maven Jetty 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:

Now, if you use Postman to check the results, you will see that the request returns “Hello World!” with the following header:

Using @RequestMapping annotation with attribute produces in Spring MVC

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:

then, we will get the result with the header as follows:

Using @RequestMapping annotation with attribute produces in Spring MVC

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.


Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment