Spring Boot Request Mapping

Request mapping connects a URL and HTTP method to a specific Java method. When a request arrives at your app, Spring reads the URL, finds the matching method, and calls it.

The Post Office Analogy

Think of request mapping as a post office sorting room. Each letter (request) has an address (URL) and a type (HTTP method). The sorter (Spring) reads both and drops the letter into the right slot (your method). Wrong address or wrong type — the letter gets returned with a 404 or 405 error.

@RequestMapping — The Base Annotation

@RequestMapping(value = "/products", method = RequestMethod.GET)
public List<Product> getProducts() { ... }

Shortcut annotations do the same thing with less code:

@GetMapping("/products")        ← GET  /products
@PostMapping("/products")       ← POST /products
@PutMapping("/products/{id}")   ← PUT  /products/1
@PatchMapping("/products/{id}") ← PATCH /products/1
@DeleteMapping("/products/{id}")← DELETE /products/1

Path Variables

A path variable is a value embedded directly in the URL path:

URL:    GET /orders/42/items/7
              ↑           ↑
          orderId       itemId

@GetMapping("/orders/{orderId}/items/{itemId}")
public Item getItem(
    @PathVariable Long orderId,
    @PathVariable Long itemId
) {
    return orderService.getItem(orderId, itemId);
}

The name inside {} in the URL must match the parameter name in the method (or be specified explicitly with @PathVariable("orderId")).

Query Parameters

Query parameters come after ? in the URL:

URL:    GET /products?category=electronics&page=2
                      ↑                    ↑
                  category              page

@GetMapping("/products")
public List<Product> getProducts(
    @RequestParam String category,
    @RequestParam(defaultValue = "1") int page
) {
    return productService.find(category, page);
}

Use defaultValue to make a query parameter optional. Without it, Spring returns a 400 error if the parameter is missing.

Path Variable vs Query Parameter

Use Case                               Approach
─────────────────────────────────────  ──────────────────
Identify a specific resource           Path variable
  GET /users/5                           @PathVariable

Filter or paginate a list              Query parameter
  GET /users?role=admin&page=2           @RequestParam

Required identifier                    Path variable
Optional filter                        Query parameter

Request Headers

Read a value from the HTTP request headers:

@GetMapping("/data")
public String getData(
    @RequestHeader("Authorization") String authHeader,
    @RequestHeader(value = "Accept-Language", defaultValue = "en") String lang
) {
    return "Auth: " + authHeader + ", Lang: " + lang;
}

Mapping with Consumed and Produced Types

Restrict a method to only accept or return specific content types:

@PostMapping(
    value = "/upload",
    consumes = "application/json",   ← Only accept JSON requests
    produces = "application/json"    ← Only return JSON responses
)
public Product createProduct(@RequestBody Product p) { ... }

URL Pattern Wildcards

Pattern            Matches
───────────────    ──────────────────────────────────
/files/*           /files/report, /files/logo
/files/**          /files/a/b/c/report.pdf (any depth)
/user-?            /user-a, /user-b (single char)

A Complete Mapping Reference

Annotation          Source of Value        Example URL Part
───────────────     ──────────────────     ─────────────────────────
@PathVariable       URL path segment       /users/{id} → id=5
@RequestParam       URL query string       /users?page=2 → page=2
@RequestHeader      HTTP header            Authorization: Bearer xyz
@RequestBody        HTTP request body      {"name":"Alice"} (JSON)
@CookieValue        HTTP cookie            sessionId=abc123

Summary

  • Request mapping links a URL + HTTP method to a Java method
  • Use shortcut annotations: @GetMapping, @PostMapping, etc.
  • @PathVariable reads values from the URL path (e.g., /users/{id})
  • @RequestParam reads values from the query string (e.g., ?page=2)
  • @RequestBody deserializes the JSON request body into a Java object

Leave a Comment

Your email address will not be published. Required fields are marked *