![]() |
VOOZH | about |
The @RequestMapping annotation in Spring MVC is used to map HTTP requests to specific handler methods or controller classes. It defines the URL path, HTTP method, and other request conditions for handling incoming requests. This helps route client requests to the appropriate business logic in a structured way.
Real-World Example: In an e-commerce application, @RequestMapping("/products") can map all product-related requests, and methods like @RequestMapping(value="/add", method=POST) handle adding a new product, while /list fetches all available products.
Create a Dynamic Web Project in STS/Eclipse.
Add required Spring framework libraries.
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.
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.
Go to the src/main/webapp/WEB-INF/web.xml file and add the following configuration:
Go to the src/main/webapp/WEB-INF folder and create an XML file named frontcontroller-dispatcher-servlet.xml. Add the following configuration:
The component-scan ensures that Spring scans the com.student.controllers package for annotated classes.
Create DemoController in specified package
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:
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.
So in this example, we are going to create Multi-Action Controller. It's 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.
@RequestMapping("/boys") at class level Handle multiple requests in same controller.
Verify correct endpoint usage.
π 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