Request Mapping
Introduction
Request mapping is Spring's mechanism for mapping HTTP URLs to specific methods. Learn how to define paths, HTTP methods, and parameters so your endpoints are better structured.
@RequestMapping
The base annotation for mapping requests to handler methods. It can be placed at the class level or the method level.
@RestController
@RequestMapping("/api/products")
public class ProductController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Product getById(@PathVariable Long id) {
return productService.findById(id);
}
}
@RequestMapping parameters:
| Parameter | Description | Example |
|---|---|---|
value / path |
URL path | "/users", "/{id}" |
method |
HTTP method | RequestMethod.GET |
produces |
Response content type | "application/json" |
consumes |
Request content type | "application/json" |
Shortcut Annotations
Spring provides shortcuts to keep the code concise and readable.
@GetMapping("/all")
public List<Product> getAll() {
return productService.findAll();
}
@PostMapping("/create")
public Product create(@RequestBody Product product) {
return productService.save(product);
}
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @RequestBody Product product) {
return productService.update(id, product);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
productService.delete(id);
}
@PatchMapping("/{id}")
public Product patch(@PathVariable Long id, @RequestBody Map<String, Object> fields) {
return productService.partialUpdate(id, fields);
}
| Annotation | HTTP Method | Use Case |
|---|---|---|
@GetMapping |
GET | Fetch data |
@PostMapping |
POST | Create new data |
@PutMapping |
PUT | Update all data |
@PatchMapping |
PATCH | Update part of the data |
@DeleteMapping |
DELETE | Delete data |
@PathVariable
Captures values from the URL path. Ideal for identifying a resource.
@GetMapping("/category/{categoryId}/products/{productId}")
public Product getByCategory(
@PathVariable Long categoryId,
@PathVariable Long productId) {
return productService.findByCategoryAndId(categoryId, productId);
}
@GetMapping("/users/{id:\\d+}")
public User getById(@PathVariable Long id) {
return userService.findById(id);
}
@RequestParam
Captures query parameters from the URL. Example: /products?sort=name&page=0.
@GetMapping("/search")
public List<Product> search(
@RequestParam String keyword,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String sort) {
return productService.search(keyword, page, size, sort);
}
| Parameter | Default | Purpose |
|---|---|---|
defaultValue |
- | Value to use if the parameter is missing |
required |
true | Whether it must be provided |
name |
- | Custom parameter name |
Combining Path Variables & Query Params
@RestController
@RequestMapping("/api/v1")
public class OrderController {
@GetMapping("/users/{userId}/orders")
public Page<Order> getUserOrders(
@PathVariable Long userId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size,
@RequestParam(defaultValue = "createdAt,desc") String[] sort) {
return orderService.getOrdersByUser(userId, page, size, sort);
}
}
Path Matching
Spring supports wildcards and patterns in paths:
@GetMapping("/files/**") // Matches all paths under /files/
@GetMapping("/users/{id:[a-z]+}") // Lowercase letters only
@GetMapping({"/old", "/new"}) // Multiple paths
Summary
- Use shortcut annotations (
@GetMapping, etc.) for cleaner code. @PathVariablefor capturing parts of the URL.@RequestParamfor query strings.
Next chapter: We'll cover Request & Response Body — how to read input from the client and customize responses.