Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
Spring @RequestMapping Annotation with Example
Next article icon

Spring @RequestMapping Annotation with Example

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The @RequestMapping annotation in Spring MVC is one of the most important annotations used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to the handler methods of controllers. When configuring Spring MVC, you need to specify the mappings between the requests and handler methods. The @RequestMapping annotation can be applied at both the class level and method level in a controller. The class-level annotation maps a specific request path or pattern onto a controller, while method-level annotations make mappings more specific to handler methods. Let’s understand the @RequestMapping annotation at both the method level and class level with examples.

Requirements: 

  • Eclipse (EE version)/STS IDE
  • Spring JAR Files
  • Tomcat Apache latest version

@RequestMapping Annotation at Method Level

Setting Up the Project

Note: We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine: How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?

Step 1: Create a Dynamic Web Project in STS

  • Open Spring Tool Suite (STS) and navigate to File > New > Dynamic Web Project.
  • Enter the Project Name (e.g., myfirst-mvc-project) and select the Target Runtime as Apache Tomcat.
  • Click Finish to create the project.

Step 2: Add Spring JAR Files

  • Download the Spring framework JARs from the Spring Repository.
  • Copy the JAR files into the src/main/webapp/WEB-INF/lib folder.

Step 3: Configure Apache Tomcat Server

  • In STS, right-click on the project and go to Properties > Targeted Runtimes.
  • Select Apache Tomcat and click Apply and Close.
  • Right-click on the project, select Run As > Run on Server.

Now, the project setup is complete.

Configuring Dispatcher Servlet

The DispatcherServlet is the front controller in Spring MVC that routes incoming HTTP requests to the appropriate handler methods. Let’s configure it in the web.xml file.

Step 4: Configure web.xml

Go to the src/main/webapp/WEB-INF/web.xml file and add the following configuration:

XML
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xmlns="http://xmlns.jcp.org/xml/ns/javaee"          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee                               http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">       <display-name>myfirst-mvc-project</display-name>   <welcome-file-list>     <welcome-file>index.html</welcome-file>     <welcome-file>index.jsp</welcome-file>     <welcome-file>index.htm</welcome-file>     <welcome-file>default.html</welcome-file>     <welcome-file>default.jsp</welcome-file>     <welcome-file>default.htm</welcome-file>   </welcome-file-list>       <servlet>       <!-- Provide a Servlet Name -->     <servlet-name>frontcontroller-dispatcher</servlet-name>     <!-- Provide a fully qualified path to the DispatcherServlet class -->     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     <load-on-startup>1</load-on-startup>   </servlet>       <servlet-mapping>       <!-- Provide a Servlet Name that you want to map -->     <servlet-name>frontcontroller-dispatcher</servlet-name>     <!-- Provide a URL pattern -->     <url-pattern>/student.com/*</url-pattern>   </servlet-mapping>     </web-app> 
  • The DispatcherServlet is mapped to /student.com/*, meaning all requests starting with /student.com/ will be handled by Spring MVC controllers.
  • Spring automatically looks for a configuration file named frontcontroller-dispatcher-servlet.xml.

 
Step 5: Configure frontcontroller-dispatcher-servlet.xml

Go to the src/main/webapp/WEB-INF folder and create an XML file named frontcontroller-dispatcher-servlet.xml. Add the following configuration:

XML
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"        xsi:schemaLocation="http://www.springframework.org/schema/beans         https://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         https://www.springframework.org/schema/context/spring-context.xsd">       <context:component-scan base-package="com.student.controllers"></context:component-scan>   </beans> 

The component-scan ensures that Spring scans the com.student.controllers package for annotated classes.


Create Your Controller Classes

Step 6: Create DemoController.java

Go to the src/main/java folder and create a package named com.student.controllers. Inside this package, create a Java class named DemoController. Mark the class with the @Controller annotation to tell Spring that this is a controller class.

Java
package com.student.controllers;  import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;  @Controller public class DemoController {      @ResponseBody     @RequestMapping("/hello")     public String helloWorld() {         return "Hello World!";     } } 
  • The @RequestMapping("/hello") annotation maps the /hello URL to the helloWorld() method.
  • The @ResponseBody annotation indicates that the return value of the method will be the response body.


Run Spring MVC Controller

Step 7: Run the Application

Right-click on your project and select Run As > Run on Server.


Use the following URL to access the controller:

http://localhost:8080/myfirst-mvc-project/student.com/hello

Output:

@RequestMapping Annotation at Class Level

The class-level @RequestMapping annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.

Create Your Controller Classes

So in this example, we are going to create Multi-Action Controller. MultiActionController is a Controller implementation that allows multiple request types to be handled by the same class. That means inside one controller class we can have many handler methods something like this.

Modify DemoController.java

Update the DemoController class to include a class-level @RequestMapping annotation:

Java
package com.student.controllers;  import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;  @Controller @RequestMapping("/boys") // Class-level mapping public class DemoController {      @ResponseBody     @RequestMapping("/hello")     public String helloWorld() {         return "Hello World!";     }      @ResponseBody     @RequestMapping("/geeksforgeeks")     public String welcomeGfgMessage() {         return "Welcome to GeeksforGeeks";     } } 
  • The class-level @RequestMapping("/boys") annotation applies a prefix to all method-level mappings.
  • The helloWorld() method is now mapped to /boys/hello.
  • The welcomeGfgMessage() method is mapped to /boys/geeksforgeeks.


Run the Updated Controller

Right-click on your project and select Run As > Run on Server.
 

Run Your Spring MVC Controller


 

And now, if you use this "http://localhost:8080/myfirst-mvc-project/student.com/hello" URL to run your controller then you are going to get the following warning and there will be no response

WARNING: No mapping for GET /myfirst-mvc-project/student.com/hello


In order to run your controller, you have to hit the following URL

http://localhost:8080/myfirst-mvc-project/student.com/boys/hello


Similarly, for the welcomeGfgMessage() handler method, you have to hit the following URL

http://localhost:8080/myfirst-mvc-project/student.com/boys/geeksforgeeks


Next Article
Spring @RequestMapping Annotation with Example

A

AmiyaRanjanRout
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Advance Java
  • Geeks-Premier-League-2022
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Spring MVC - Exception Handling
    Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
    6 min read
    Spring - How to Load Literal Values From Properties File
    Literals in Java are a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable named ‘’/count is assigned an integer value in the following statement. int x = 100; // Here 100 is a constant/li
    4 min read
    Spring MVC - Multiple View Page
    A view page is redirected to another view page in this example. Let's look at a simple Spring Web MVC framework sample. The procedure is as follows: In the case of Maven, load the spring jar files or add dependencies.Make your controller class.Provide a controller entry in the web.xml file.In a sepa
    3 min read
    Spring MVC - Custom Validation
    Validating user input is essential for any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side. It provides stand
    8 min read
    Difference Between ApplicationContext and WebApplicationContext in Spring MVC
    Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain Java Classes. The model object can be passed between view and controller using maps. W
    3 min read
    Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are goi
    4 min read
    Difference Between @Controller and @Service Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.  Spring @Control
    5 min read
    Difference Between @Controller and @RestController Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not directly affect the operation of the code they annotate. It does not change the action of the compiled program. Understanding the differ
    3 min read
    Spring MVC - @RequestParam Annotation
    The @RequestParam annotation is one of the most commonly used annotations in Spring MVC for handling HTTP request parameters. @RequestParam annotation enables Spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Key features of @RequestParam annotation
    5 min read
    Query String and Query Parameter in Spring MVC
    According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a pag
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences