Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Spring MVC
3.
What is @RequestMapping?
3.1.
Code Implementation
3.1.1.
Output
3.2.
Explanation
4.
@RequestMapping Basics
4.1.
Params
4.2.
Value or Path
4.3.
Headers
4.4.
Consumes
4.5.
Produces
4.6.
Method 
5.
@RequestMapping Annotation With Multiple URLs
5.1.
Code implementation
5.1.1.
Output
5.2.
Explanation
6.
@RequestMapping Annotation With @RequestParam
6.1.
Code Implementation
6.1.1.
Output
6.2.
Explanation
7.
@RequestMapping Annotation With @PathVariable
7.1.
Output
8.
Explanation
9.
@RequestMapping Annotation With HTTP Methods
9.1.
Mapping HTTP GET Request
9.1.1.
Output
9.2.
Explanation
9.3.
Mapping HTTP POST Request
9.4.
Mapping HTTP PUT Request
9.5.
Mapping HTTP DELETE Request
10.
Difference Between @RequestParam and @PathVariable annotation
11.
Advantages of the @RequestMapping Annotations
12.
Disadvantages of the @RequestMapping Annotations
13.
Frequently Asked Questions
13.1.
What is the use of @RequestMapping in spring?
13.2.
Why use RequestMapping?
13.3.
Can we use @RequestMapping in spring boot?
13.4.
Is @RequestMapping mandatory?
13.5.
What is the default @RequestMapping in Spring?
13.6.
Can we have multiple @RequestMapping annotations on a single method?
13.7.
What is the significance of the ‘method’ attribute in @RequestMapping?
13.8.
What are common mistakes to avoid when using @RequestMappiing?
14.
Conclusion
Last Updated: Mar 27, 2024
Medium

Spring @RequestMapping

Author Vidhi Sareen
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

RESTful web services use HTTP methods to manage resources. To address these resources in a well-organized manner, it is necessary to understand the behavior of the output expected after an HTTP request and response. @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.

Spring MVC

A spring MVC is a Java framework used to build a web application. It follows the Model-View-Controller design pattern for the web application. Now let's discuss the architecture of Spring MVC.

  • The browser sends the request to the server. It then pre-processes the request and sends it to the front controller for processing.
     
  • The Front Controller is also known as the Dispatcher Servlet. Its functionality is to send the pre-processed request to the controller.
     
  • The controller has some codes written by the developer according to his requirements and needs.
     
  • The controller prepares its response according to the request made by the browser and sends it to the view template. 
     
  • The View Template consists of HTML code; it prepares the output, which is sent to the web page for display.

 

There are many benefits of using Spring MVC; it provides the best way to build web applications in Java, It is very flexible to configure, it gives excellent support to web services, and many more. To learn more about the working of Spring MVC, check out this link here. @RequestMapping is one of the most widely used annotations. Now we will explore different aspects related to @RequestMapping. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is @RequestMapping?

As discussed above, 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."

@RequestMapping Basics

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
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

@RequestParam @PathVariable
They are used to bind requested parameters to the method parameters. They are used to extract values from the URL path.
@RequestParam(“paraName) Datatype paramName @PathVariable Datatype variableName
Specify the name of the request parameter  Variable name is used to map the path in the URL
Matches parameters by its name Matches variable by its position in the URL
@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 the use of @RequestMapping in spring?

The @RequestMapping annotation in Spring is used to map HTTP requests to specific handler methods in a controller class.

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.

Can we use @RequestMapping in spring boot?

Yes, you can use @RequestMapping in Spring Boot as it's part of the Spring Framework, which Spring Boot builds upon.

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. This article discusses what @RequestMapping Annotation is and how it works. Different attributes are related to @RequestMapping. Some of them are Value or path, Params, Headers, Consumer, producer, and method. We explore their work with the help of different examples. 

Some use cases make it very difficult to understand what we should use @RequestParam or @PathVariable annotation. So we also have to discuss their differences in this article. @RequestAnnotation real-life examples can be RESTful APIs, form submission, and dynamic routing. In this article, we also explored some of the benefits and drawbacks of using @RequestMapping. 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 find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.

Previous article
Logback in Spring Boot
Next article
What is JAX-RS?
Live masterclass