Using @RequestMapping annotation with attribute consumes in Spring MVC

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:

Using @RequestMapping annotation with attribute consumes 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 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:

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:

Using @RequestMapping annotation with attribute consumes in Spring MVC

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.

Using @RequestMapping annotation with attribute consumes in Spring MVC


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

Add Comment