@RequestMapping annotation example In Spring Boot

Here we will see @RequestMapping annotation example In Spring Boot.

  • This annotation introduced in Spring  2.5, available in org.springframework.web.bind.annotation package.
  • It has optional elements consumes, headers, method, name, params, path, produces and value.
  • We use this annotation with the class as well as method.

Let’s see an example of @RequestMapping.

prerequisites –

  • JDK 1.8
  • Eclipse
  • maven
  • postman

Create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – requestmappigexamle, ArtifactId – requestmappigexamle and name – requestmappigexamle) and click on finish. Keep packaging as the jar.

pom.xml

 

Define Contoller(Book.java), SpringBootMain(BookMain.java), and Entity class(BookController.java).

Book.java

The controller class for @RequestMapping annotation example In Spring Boot.

BookController.java

 

BookMain.java

 

If you encounter any port related issue, define application.properties and change the port.

application.properties

server.port = 9093

Let’s run the BookMain.java and deploy the application.

 

Let’s test the URI –

@RequestMapping annotation example In Spring Boot

 

In the above example, we can see @RequestMapping annotation we are with the class as well as method. Also, we have seen two elements value and method.

 

Now suppose we want to produce XML instead of JSON, let’s modify the controller class.

 

@RequestMapping annotation example In Spring Boot

Although this is not a proper way to produce XML (See here how to produce XML response in real time development), here mainly we are discussing @RequestMapping and its elements. The same way we can reproduce JSON data.

That’s all about @RequestMapping annotation example In Spring Boot.

You may like.

Spring @RequestMapping docs.

Top