Table of contents
1.
Introduction
2.
What is @RequestMapping?
3.
Basics of spring @RequestMapping
3.1.
Params
3.2.
Value or Path
3.3.
Headers
3.4.
Consumes
3.5.
Produces
3.6.
Method 
4.
@RequestMapping Annotation With Multiple URLs
5.
@RequestMapping Annotation With @RequestParam
6.
@RequestMapping Annotation With @PathVariable
7.
@RequestMapping Annotation With HTTP Methods
7.1.
Mapping HTTP GET Request
7.2.
Mapping HTTP POST Request
7.3.
Mapping HTTP PUT Request
7.4.
Mapping HTTP DELETE Request
8.
Difference Between @RequestParam and @PathVariable annotation
9.
Advantages of the @RequestMapping Annotations
10.
Disadvantages of the @RequestMapping Annotations
11.
Frequently Asked Questions
11.1.
What is difference between @GetMapping and RequestMapping?
11.2.
Why use RequestMapping?
11.3.
Is @RequestMapping mandatory?
11.4.
What is the default @RequestMapping in Spring?
11.5.
Can we have multiple @RequestMapping annotations on a single method?
11.6.
What is the significance of the ‘method’ attribute in @RequestMapping?
11.7.
What are common mistakes to avoid when using @RequestMappiing?
12.
Conclusion
Last Updated: Oct 8, 2024
Medium

Spring Boot @RequestMapping

Author Vidhi Sareen
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

@RequestMapping is the most commonly used annotation in Spring MVC. @RequestMapping maps the web request onto specific handler classes and/or on-handler methods.

RequestMapping

Here in the article, we will discuss relevant points related to @RequestMapping.

What is @RequestMapping?

In Spring MVC applications, the RequestDispatcher servlet is called Front Controller. It is responsible for mapping the HTTP request to handler methods. It defines the mapping between the incoming connection request and its corresponding handler methods. The @RequestMapping annotation is used to map the web request to its handler class or its handler method. Consider the following example in which the request mapping annotation is applied to both the class and methods.

Code Implementation

@Controller
//added base URL for class

@RequestMapping("/users")
public class usercontroller {

@RequestMapping(value = {"/"}, method = RequestMethod.GET)
@ResponseBody
public String getUsers() {
    // Return if the getUser functions works successfully
    return "Get Ninja Users";
	}
}

Output

output

Explanation

We can see here the "@RequestMapping("/users") annotation has been applied to the controller class in this code. It defines the base URL mapping for the controller. This means that any requests starting with "/user" will be handled by the controller. At the method level, "@RequestMapping("/") annotation has been used. When the request is made, it will return the response of the "getUser()" method. In this case, it will return "Get Ninja Users."

Basics of spring @RequestMapping

There are many attributes associated with @RequestMapping Annotation. They can be customized according to the behavior of the @RequestMapping. Some of them are:

Params

The Params is an attribute associated with the  @RequestMapping. It is used to specify parameters that must be present in the requested URL. For example,

@RequestMapping(value = “/home”, params = “student_id=6”)

The following annotation will map the controller method from URL "/home" only if the requested URL consists of the parameter "student_id" having value 6. The controller class will not be called if the parameter does not match the request URL.

Value or Path

It specifies the path of the URL that needs to be mapped. The value method can be used interchangeably with the path method. To understand this, let's see an example:

@RequestMapping("/api") is equivalent to @RequestMapping(path="/api").

Headers

It defines the header condition that should be present or have specific values for the method to be mapped. For example 

@RequestMapping(value = “/user”, headers = “content-type = text/plain”)


This will return any request that matches the URL path as "/user" and content type as "text/plain."

Consumes

It is used to specify media types that a method consumes, like JSON and XML. For example, 

@RequestMapping(value = “/user”, consumes = “application/XML”)

Produces

It is used to specify one or more media types that a method can produce. For example 

@RequestMapping(value = “/user”, producer = “application/json”)


This will return any request which matches the URL and Accepts the header of the application/JSON.

Method 

We need to perform different HTTP methods on the same URL in a few cases. Then in those cases @RequestMapping annotation is used to map requests to the controller method. There are different HTTP request methods, such as GETPOSTPUT, DELETE, HEAD, PATCH, etc. The following annotation is an example that shows that a controller method will be called when a POST request is made to the "/home" URL. 

@RequestMapping(value = "/home," method = RequestMethod.POST).

@RequestMapping Annotation With Multiple URLs

We can use a single method for handling multiple URLs. They can accept multiple URLs as an array or comma-separated values. This helps in mapping a single controller method to different URLs

Code implementation

@Controller

//added class URL
@RequestMapping("/api")
public class usercontroller {

//added multiple method URL
@RequestMapping(value = {"/newuser","/NewUser","/New-User"})
public String NewUser() {

return "added new user : Ninja_1";
	}
}
output
output
output

Explanation

In this code @RequestMapping annotation is used to map the new user method to handle GET requests for three different URLs: "/newuser," NewUser," and "New-User." If any URLs are requested with the GET method, then the "NewUser" method will be executed.

@RequestMapping Annotation With @RequestParam

This annotation allows you to map request parameters to the controller method parameters. The @RequestParam can be used with or without a value. @RequestMapping allows easy mapping of the URL parameters with the @RequestParam.

Code Implementation

@Controller

//added base class URL
@RequestMapping("/exp")
public class usercontroller {

 //added method URL
@RequestMapping("/end")
@ResponseBody
public String StudentHandleRequest(@RequestParam("name") String name, @RequestParam("marks") int marks) {
   
    // Process the request parameters
    return "Received name of the student : " + name + ", marks : " + marks;
	}
}

Output

output

Explanation

In this code, we have defined a controller class with the 'StudentHandleRequest' method. We have mapped '/exp' to the base URL, and '/end' is mapped to the 'StudentHandleRequest' method. Two request parameters should be passed to access the 'StudentHandleRequest' method, where 'name' accepts 'String,' and 'marks' accepts 'integer' values. When a request is made to '/exp/end,' it will return a response with the values of 'name' and 'marks.'

@RequestMapping Annotation With @PathVariable

The @RequestMapping annotation conjugates with @PathVariable and can be used to handle dynamic URLs. @PathVariable annotation be used on a method argument to bind it to the value of the URL template variable. You can also apply the regular expressions. It will be used to constrain the accepted values further.

Code implementation

@Controller

//added class URL
@RequestMapping("/exp")
public class usercontroller {

//added method URL
@RequestMapping("/end/{student_id}")
@ResponseBody

//handle request for specific ID
public String Student_id_handleRequest(@PathVariable("student_id") String student_id) {
    return "Received ID: " + student_id;
	}
}

Output

output

Explanation

The @Controller annotates the 'user controller' class. This shows it can handle HTTP requests. The 'student_id_handleRequest' is used to annotate by @RequestMapping("/end/{student_id}). This URL is used to map the 'student_id_handleRequest' method where {student_id} is the path variable. It also binds the value of the "student_id" path variable from the URL to the 'student_id' parameter of the method. It can return a response containing the received ID.

@RequestMapping Annotation With HTTP Methods

We can also map a URL with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping annotations. Let's see an example to understand this better.

Mapping HTTP GET Request

The @GetMapping Annotation maps the HTTP GET request on the specific handler method. It can be used to reduce the readability of that code. It is used to map GET requests only. It can be used in place of the @RequestMapping annotation. There is no need to specify the method attribute since @GetMapping always maps the HTTP GET method.

@GetMapping(“/api”)
Public void addStudent(@RequestBody Student student)


Let's take a look at the example below to understand @GetMapping annotation.

Code implementation
@Controller

//added class URL
@RequestMapping("/users")
public class usercontroller {

  @GetMapping({"/getmappingMethod"})
   @ResponseBody
   public String getUsers() {
     
  // Retrieve a list of all users
       return "Get all Ninja Users";
   }
}

Output

output

Explanation

The 'Usercontroller' is mapped with the base URL "/users." It contains a method known as the 'get user ()' method. The @GetMapping("/getmappingMethod") is used to map the HTTP GET request to this method. This method returns the string "Get all Ninja users."

Mapping HTTP POST Request

The @PostMapping annotation maps the HTTP POST request on a specific handler method. It can be used to reduce the readability of the code. It can be used to map the POST requests only. It is used in place of the @RequestMapping annotation. Specifying the method attribute is not required since @PostMapping always maps the HTTP POST method.

@PostMapping(“/api”)
Public void addStudent(@RequestBody Student student)

Mapping HTTP PUT Request

The @PutMapping annotation maps the HTTP PUT request on this specific handler method. It reduces the readability of the code. It can be used to only map the PUT requests in place of the @RequestMapping annotation. We don't need to specify the method attribute since @PutMapping always maps the HTTP PUT method.

@PutMapping(“/api”)
Public void addStudent(@RequestBody Student student)

Mapping HTTP DELETE Request

The @DeleteMapping annotation maps the HTTP DELETE request on their specific handler method and reduces the readability of the code. This also maps only the DELETE requests. It also uses in place of the @RequestMapping annotation. It is not required to specify the method attributes since @DeleteMapping maps the HTTP DELETE method always.

@DeleteMapping(“/api”)
Public void addStudent(@RequestBody Student student)


These annotations can provide a more concise way to map specific HTTP methods to the Controller methods. By using them, we can make our code more readable and understandable.

Difference Between @RequestParam and @PathVariable annotation

Parameters @RequestParam @PathVariable
Purpose They are used to bind requested parameters to the method parameters. They are used to extract values from the URL path.
Syntax @RequestParam(“paraName) Datatype paramName @PathVariable Datatype variableName
Specification Specify the name of the request parameter  Variable name is used to map the path in the URL
Parameter Matching Matches parameters by its name Matches variable by its position in the URL
Example Usage @RequestParam(“addedName”) String addedName @PathVariable String id

Advantages of the @RequestMapping Annotations

There are many advantages of using these @RequestMapping Annotations:

  • The @RequestMapping annotation is used with different HTTP methods. It helps in mapping these HTTP methods to their corresponding handler methods. It helps to improve their code readability.
     
  • The @RequestMapping can also be used to handle dynamic URLs. It uses the placeholders like '/{id}' to create more flexibility for their application.
     
  • @RequestMapping can use the 'produce' attributes to their related handle client format. The format can be JSONXMLHTTP, etc.).
     
  • The @RequestMapping annotation can be used with the @ExceptionHandler to handle specific errors in this method.
     
  • @RequestMapping annotation helps in simplifying unit testing of the controller methods.

Disadvantages of the @RequestMapping Annotations

There some disadvantages of @RequestMapping Annotations like:

  • It may cause ambiguity. If multiple methods have similar URLs or overlapping mapping, it can cause ambiguity or conflicts.
     
  • There can be overuse of these annotations. If there are multiple annotations like this, it can increase the load of the developer while carefully examining the code if any error occurs.
     
  • If there are a large number of annotations, then it can increase the interdependence between the code and its framework.

Frequently Asked Questions

What is difference between @GetMapping and RequestMapping?

@GetMapping is a specialized version of @RequestMapping for handling HTTP GET requests. While @RequestMapping can handle multiple request methods (GET, POST, etc.), @GetMapping is specifically used for GET requests, making it more concise and readable for that purpose.

Why use RequestMapping?

@RequestMapping is used to define the URL patterns that map to controller methods, allowing the framework to route HTTP requests to the appropriate handler.

Is @RequestMapping mandatory?

No, @RequestMapping is not mandatory. However, it's commonly used to define mappings for controller methods to handle incoming requests.

What is the default @RequestMapping in Spring?

The default @RequestMapping in Spring is usually set to "/", meaning it handles requests to the root URL of the application. This can be overridden with a different value as needed.

Can we have multiple @RequestMapping annotations on a single method?

Yes, you can have multiple request mapping for a method. They can be added by @RequestMapping annotation by using a list of values. It provides more flexibility in handling various HTTP methods, request parameters, or headers within a single method.

What is the significance of the ‘method’ attribute in @RequestMapping?

The 'method' attribute is used with @RequestMapping to specify the HTTP methods that a handler can accept. HTTP methods like GET, POST, DELETE, etc., ensure that a specific handler can give adequately controlled request mapping. 

What are common mistakes to avoid when using @RequestMappiing?

Common problems while using @RequestMapping are overusing annotations and using similar URLs; there may be some problems in mapping, resources are unavailable, or forgetting to specify the appropriate HTTP method in @RequestMapping, which can cause incorrect mapping.

Conclusion

@RequestMapping annotation in Spring MVC is one of the essential annotations used in mapping HTTP requests to the handler method. It can be used to improve the performance and flexibility of the Spring MVC.

RequestMapping helps create well-structured and maintainable code that handles the request effectively in Spring MVC applications.

To learn more about such topics, check out the link, check out the link below-

 

You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Code360.

Live masterclass