✅ What is @RequestMapping?
@RequestMapping is a Spring annotation used to map HTTP requests to specific
handler methods or classes in a controller.
It will work with all kinds of HTTPs requests all get, post, put, patch, delete
until specified
It's like telling Spring:
“When someone visits this URL, run this method!”
✅ Syntax:
java
Copy
Edit
@RequestMapping(value = "/path", method = RequestMethod.GET)
✅ Example: Basic Usage
java
Copy
Edit
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping("/hello")
@ResponseBody
public String sayHello() {
return "Hello from @RequestMapping!";
}
}
🔹 Output:
Visiting http://localhost:8080/hello returns:
css
Copy
Edit
Hello from @RequestMapping!
✅ Specifying HTTP Method (GET, POST, etc.)
java
Copy
Edit
import org.springframework.web.bind.annotation.*;
@RestController
public class ApiController {
@RequestMapping(value = "/api", method = RequestMethod.GET)
public String getApi() {
return "GET method called";
}
@RequestMapping(value = "/api", method = RequestMethod.POST)
public String postApi() {
return "POST method called";
}
}
✅ Shortcut Annotations (Preferred)
Spring Boot provides shortcut annotations that are easier to read and more
specific:
Shortcut Equivalent
@GetMapping("/path") @RequestMapping(value = "/path", method =
RequestMethod.GET)
@PostMapping("/path") @RequestMapping(value = "/path", method =
RequestMethod.POST)
@PutMapping("/path") @RequestMapping(value = "/path", method =
RequestMethod.PUT)
@DeleteMapping("/path") @RequestMapping(value = "/path", method =
RequestMethod.DELETE)
✅ Mapping at Class Level + Method Level
java
Copy
Edit
@RestController
@RequestMapping("/api")
public class ProductController {
@GetMapping("/products")
public String getAllProducts() {
return "List of products";
}
@PostMapping("/products")
public String addProduct() {
return "Product added";
}
}
Now:
/api/products handles GET and POST differently based on method-level mappings.
✅ Summary Table
Feature @RequestMapping
Purpose Map URL requests to controller methods
Can specify method? Yes (method = RequestMethod.GET)
Can be used on class and method? Yes
Can handle all HTTP methods? Yes
Should I prefer shortcut annotations? ✅ Yes (@GetMapping, @PostMapping, etc.)