Spring Boot – @Requestmapping

Spring Boot is the most popular framework of Java for building enterprise-level web applications and back-ends. Spring Boot has a handful of features that support quicker and more efficient web app development. Some of them are Auto-configuration, Embedded Server, opinionated defaults, and Annotation Support. In this article, we’ll be exploring the core annotation of Spring Boot – @RequestMapping which is part of the set of annotations that Spring Boot employs for defining URL endpoints and REST APIs.

@RequestMapping

This annotation is a versatile and flexible annotation that can be used with a controller (class) as well as the methods to map specific web requests with the handler methods and controllers. This annotation is part of a larger set of annotations provided by Spring Framework to define URL endpoints and simplify the development of Spring Boot applications.

It has the following features:

  • Define several different endpoints to access a specific resource.
  • Build REST APIs to serve web requests.
  • Simplify the web development process by simply defining an annotation that offers a set of functionalities for handling requests.
  • Define multiple endpoints in a single @RequestMapping annotation.

Step-By-Step Implementation of @RequestMapping annotation

For this article, we’ll be using the following tools:

  • Java 8 or higher
  • Java IDE like Eclipse, IntelliJ, and VS code (We’ll be using IntelliJ)
  • POSTMAN for testing Request Mappings
  • Dependency: Spring Web Starter

Step-1: Create a starter file and extract it

Go to Spring Initializr and create a starter file having a single dependency – Spring Web. Download and extract it into your local folder and open it in your favorite IDE.

pom.xml File:

XML




<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.w3wiki</groupId>
    <artifactId>RequestMappingExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>RequestMappingExample</name>
    <description>Request Mapping Example</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
</project>


Step-2: Define a Controller

  • Create a new package for containing all the controllers that we will be adding in our application under the src/main/java/package_name/Controllers
  • Add a new TestController inside Controllers Package for defining Request Mappings. Your final directory structure would look something like this :

Step-4: Define URL Templates inside the controller

Annotate the Controller with @Controller to signify that this class is a controller that has some URL templates defined inside it and @RequestMapping on the controller as well as the methods to specify which URL path will give what output.

Below is the code Implementation of Controller:

Java




import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
  
import java.util.ArrayList;
import java.util.List;
  
// Controller class
@Controller
@ResponseBody
@RequestMapping("/test")
public class TestController {
  
    // URL Path - 1
    // Returns a String
    @RequestMapping("/hello")
    public String sayHello() {
        System.out.println("dsvsdvdsvs");
        return "Hello Geek!";
    }
  
    // URL Path - 2
    // Returns a String
    @RequestMapping("/sport")
    public String doSomeSport() {
        return "Run 5 kilometers today!";
    }
  
    // URL Path - 3
    // Returns a List
    @RequestMapping("/today/tasks")
    public List<String> todaysTasks() {
  
        List<String> myTasks = new ArrayList<String>();
        myTasks.add("Write 5 articles on w3wiki Today");
        myTasks.add("Run 5 kilometers");
        myTasks.add("Do Laundry");
  
        return myTasks;
    }
}


Explanation of the above Program:

We’ve defined multiple end points using @RequestMapping which can be accessed at following URLs :

  • http://localhost:8080/test/hello
  • http://localhost:8080/test/sport
  • http://localhost:8080/test/today/tasks

Annotations used:

  • @Controller: This annotation implicitly marks the class as a component making it eligible for component scanning while signifying that this class invokes business logic, handles incoming web requests and returns customized responses.
  • @ResponseBody: This annotation is used on both class level as well as on method level to indicate that the return value generated by this class or method doesn’t need to be resolved to a view page like HTML or JSP, rather it should be directly serialized into HTTP response body. And this serialization from Java Object to JSON is done by a technology called – Jackson Project that performs Jackson Data Binding under the hood.

Our request method can return any type of data – POJOs (Plain Old Java Objects) and this data will be serialized into JSON by the Jackson Project.

Note: @ResponseBody can be ignored if you’re using @RestController instead of @Controller.

Outputs for every endpoint on POSTMAN:

Endpoint – 1: http://localhost:8080/test/hello

Endpoint – 2: http://localhost:8080/test/sport

Endpoint – 3: http://localhost:8080/test/today/tasks

Notice that we’re selecting the type of request as GET in our POSTMAN this is because all of our methods are only returning some data, not making any changes in a database (as we’re not connected to any database).

And to be more specific, the actual use of @RequestMapping is to define the start of URL and the request handler method will perform some operation and depending on the type of operation a method performs, we will annotate it with GET, PUT, POST or DELETE. Let’s look at some of the most commonly used type of annotation we can use with a specific web request in brief:

  • @GetMapping: This annotation is associated with the requests that are requesting a resource without making any changes in the database.
  • @PostMapping: This annotation is associated with the requests that are trying to add new data in the database. Ex: Adding a new student record that contains all the information regarding a student like student_id, name, enrollment_number, branch etc.
  • @PutMapping: This annotation is associated with the update requests that wants to update or change some already existing data in our database.
  • @DeleteMapping: This annotation is associated with deleting persistent objects (already existing data) from our database.

Conclusion

In conclusion, @RequestMapping is a core annotation for defining a controller and mapping web requests to their appropriate methods. It is a core MVC Annotations defined for defining the controller and URL path, it is very crucial to understand the working and different variations of this annotation as a Java Developer you’ll be using it very frequently.

  • It maps certain web requests to their specific controller and methods.
  • We will have multiple controllers in our application, then each controller’s URL pattern will be different to identify and map web requests to an appropriate controller. For Example, we can have a controller for performing database operation, another controller for Throwing Exceptions, another for logging, monitoring etc. Each of the controller’s request mapping will have a unique URL Pattern
  • @RequestMapping can also be used to take query parameters from the URL. For example, we need a student with a specific ID. So, we can define a mapping like this – https://localhost:8080/student/{id}. The {id} is a dynamic parameter whose input can vary depending on the requests. Curly braces around it indicates that the input in this part of URL will vary.
  • Although @RequestMapping can be annotated on top of Methods as well, it’s more efficient and readable to use a specific type of mapping annotation like @GET, @PUT, @POST etc.


Contact Us