@RequestMapping in Spring: Definition, Usage, and Examples
@RequestMapping is a Spring annotation used to map web requests to specific handler methods or classes in a controller. It defines the URL patterns and HTTP methods that a method or class should respond to in a Spring MVC application.How It Works
@RequestMapping acts like a signpost in a web application. Imagine you have a restaurant with many doors, and each door leads to a different service like ordering food or asking for the bill. @RequestMapping tells Spring which door (URL) should lead to which service (method in your code).
When a user visits a URL or sends a request, Spring looks for a matching @RequestMapping annotation on a controller method or class. If it finds one, it runs that method to handle the request and send back a response.
You can specify the URL path, HTTP method (GET, POST, etc.), and other details inside @RequestMapping. This makes it flexible to handle different types of web requests in one place.
Example
This example shows a simple Spring controller with @RequestMapping mapping the URL /hello to a method that returns a greeting message.
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String sayHello() { return "Hello, Spring!"; } }
When to Use
Use @RequestMapping when you want to connect a web URL to a method in your Spring controller. It is useful for handling different web pages or API endpoints in your application.
For example, use it to:
- Show a homepage or user profile page
- Handle form submissions or API calls
- Respond to different HTTP methods like GET for fetching data or POST for sending data
It helps organize your web app by clearly defining which URLs trigger which code.
Key Points
@RequestMappingmaps URLs and HTTP methods to controller methods.- It can be applied at class level to set a base path and at method level for specific endpoints.
- Supports multiple HTTP methods like GET, POST, PUT, DELETE.
- Helps build RESTful web services and web applications.
- Since Spring 4.3, more specific annotations like
@GetMappingand@PostMappingare recommended for clarity but@RequestMappingis still widely used.
Key Takeaways
@RequestMapping connects web URLs to controller methods in Spring.@RequestMapping remains useful.