Labs ICT
โญ Pro Login

Request Mapping

Mapping URLs to handler methods.

The @RequestMapping Annotation

The @RequestMapping annotation is the foundation of request handling in Spring. It maps HTTP requests to handler methods. You can place it at the class level to define a base URL, and at the method level to narrow it down.

Think of it like a routing table. The class-level mapping sets the path prefix, and each method's mapping handles a specific sub-path and HTTP method combination.

Method-Specific Mappings

Instead of using @RequestMapping with a method attribute, Spring provides shorthand annotations that make your intent clearer: @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping.

These are not just syntactic sugar โ€” they make your code self-documenting. When you see @GetMapping("/users"), you immediately know it handles GET requests to that path.

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @GetMapping
    public List<Order> list() { }

    @PostMapping
    public Order create(@RequestBody Order order) { }

    @PutMapping("/{id}")
    public Order update(@PathVariable Long id, @RequestBody Order order) { }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) { }
}

Multiple URL Mappings

A single method can respond to multiple URLs. Pass an array of paths to the mapping annotation. This is handy when you want the same endpoint accessible at different URLs.

@GetMapping({"/search", "/find"})
public List<Product> search(@RequestParam String query) {
    return productService.search(query);
}

Consumes and Produces

You can restrict endpoints to specific content types using consumes and produces attributes. For example, an endpoint might only accept JSON and return JSON.

This is useful when your API supports multiple formats or versions. Clients send an Accept header, and Spring routes to the correct method based on what the client expects.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is @RequestMapping used for?