Spring Framework Essentials: Everything You Need to Know About @RequestMapping

Anil R
2 min readDec 6, 2024

--

@RequestMapping is a Spring annotation used to map HTTP requests to handler methods in a controller. It provides flexible options for defining the path, HTTP methods, parameters, headers, and other aspects of the request. It is one of the core annotations for creating RESTful web services in Spring.

Usage of @RequestMapping

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyController {

@RequestMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
  • Mapped URL: /api/hello
  • Response: Hello, World!

Mapping Specific HTTP Methods

@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
return "Fetching all users";
}

@RequestMapping(value = "/users", method = RequestMethod.POST)
public String addUser() {
return "Adding a new user";
}
  • GET Request: /users → Returns "Fetching all users"
  • POST Request: /users → Returns "Adding a new user"

Mapping with Path Variables

@RequestMapping("/users/{id}")
public String getUserById(@PathVariable("id") int id) {
return "User ID: " + id;
}
  • Request: /users/5
  • Response: User ID: 5

Mapping Query Parameters

@RequestMapping("/search")
public String search(@RequestParam("q") String query) {
return "Searching for: " + query;
}
  • Request: /search?q=Spring
  • Response: Searching for: Spring

Mapping with Headers

@RequestMapping(value = "/headers", headers = "X-Requested-With=XMLHttpRequest")
public String handleAjaxRequests() {
return "Handling AJAX request";
}

Ensures the endpoint is called only when the header X-Requested-With is set to XMLHttpRequest.

Mapping with Consumes and Produces

@RequestMapping(value = "/json", consumes = "application/json", produces = "application/json")
public String handleJsonRequest() {
return "{\"message\": \"This is JSON\"}";
}
  • Consumes: Accepts only requests with Content-Type: application/json.
  • Produces: Returns responses with Content-Type: application/json.

Best Practices

  1. Use Specific Annotations for HTTP Methods:
  • Prefer @GetMapping, @PostMapping, @PutMapping, @DeleteMapping for clarity and simplicity over @RequestMapping.

2. Organize URLs:

  • Use meaningful and hierarchical URL structures:
  • Good: /api/v1/users/{id}
  • Bad: /getUser

3. Avoid Overlapping Mappings:

  • Ensure URLs and methods are unique to avoid ambiguity.

4. Validate Inputs:

  • Use @RequestParam, @PathVariable, and @RequestBody along with validation annotations like @Valid for input validation.

5. Enable Cross-Origin Requests (CORS):

  • Use @CrossOrigin for APIs accessed by front-end applications from different origins.

6. Handle Exceptions Gracefully:

  • Use @ControllerAdvice to manage exceptions across controllers.

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet