Chapter 2: Web and REST Annotations
1. Controller Annotations
@RestController vs @Controller
// Returns VIEWS (HTML)
@Controller
public class PageController {
@GetMapping("/home")
public String home() {
return "home"; // Looks for a home.html template
}
}
// Returns DATA (JSON/XML)
@RestController
public class ApiController {
@GetMapping("/api/data")
public Map<String, String> getData() {
return Map.of("message", "Hello"); // Automatically serialized to JSON
}
}
@ResponseBody
Forces return in JSON/XML (used with @Controller).
@Controller
public class MixedController {
@GetMapping("/page")
public String page() {
return "page"; // Returns a view
}
@GetMapping("/api/info")
@ResponseBody
public Map<String, String> info() {
return Map.of("version", "1.0"); // Returns JSON
}
}
2. HTTP Mapping Annotations
@RequestMapping
Basic annotation to map a URL to a method. Can specify the HTTP method.
@RestController
@RequestMapping("/api/v1/products") // Prefix for all methods
public class ProductController {
@RequestMapping(method = RequestMethod.GET)
public List<Product> getAll() { ... }
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Product getById(@PathVariable Long id) { ... }
}
@GetMapping
Shortcut for @RequestMapping(method = GET).
@GetMapping
public List<Product> getAll() {
return productService.findAll();
}
@GetMapping("/{id}")
public Product getById(@PathVariable Long id) {
return productService.findById(id);
}
@GetMapping("/search")
public List<Product> search(@RequestParam String name) {
return productService.findByName(name);
}
@PostMapping
Shortcut for @RequestMapping(method = POST).
@PostMapping
public ResponseEntity<Product> create(@Valid @RequestBody ProductDto dto) {
Product created = productService.create(dto);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@PutMapping
Shortcut for @RequestMapping(method = PUT). Complete replacement of a resource.
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @Valid @RequestBody ProductDto dto) {
return productService.update(id, dto);
}
@PatchMapping
Shortcut for @RequestMapping(method = PATCH). Partial update of a resource.
@PatchMapping("/{id}")
public Product partialUpdate(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
return productService.partialUpdate(id, updates);
}
@DeleteMapping
Shortcut for @RequestMapping(method = DELETE).
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
Mapping Summary
| Annotation | HTTP Method | Typical Usage |
|---|---|---|
@GetMapping | GET | Read data |
@PostMapping | POST | Create a resource |
@PutMapping | PUT | Replace a resource |
@PatchMapping | PATCH | Partial modification |
@DeleteMapping | DELETE | Delete a resource |
3. Parameter Annotations
@PathVariable
Extracts a value from the URL.
// GET /api/users/42
@GetMapping("/api/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
// GET /api/users/42/orders/7
@GetMapping("/api/users/{userId}/orders/{orderId}")
public Order getOrder(@PathVariable Long userId, @PathVariable Long orderId) {
return orderService.findByUserAndId(userId, orderId);
}
// Different name from the URL parameter
@GetMapping("/api/categories/{category-name}")
public Category getCategory(@PathVariable("category-name") String categoryName) {
return categoryService.findByName(categoryName);
}
@RequestParam
Extracts a parameter from the query string.
// GET /api/products?category=electronics
@GetMapping("/api/products")
public List<Product> getByCategory(@RequestParam String category) {
return productService.findByCategory(category);
}
// Optional parameter with default value
// GET /api/products?page=0&size=20&sort=name
@GetMapping("/api/products")
public Page<Product> getAll(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "name") String sort) {
return productService.findAll(PageRequest.of(page, size, Sort.by(sort)));
}
// Optional parameter without default value
@GetMapping("/api/search")
public List<Product> search(
@RequestParam(required = false) String name,
@RequestParam(required = false) BigDecimal minPrice) {
return productService.search(name, minPrice);
}
@RequestBody
Deserializes the request body (JSON → Java Object).
@PostMapping("/api/users")
public User createUser(@RequestBody UserDto userDto) {
return userService.create(userDto);
}
// Request body (JSON)
{
"name": "Jean Dupont",
"email": "jean@example.com",
"password": "secret123"
}
@RequestHeader
Extracts a value from an HTTP header.
@GetMapping("/api/profile")
public User getProfile(@RequestHeader("Authorization") String authHeader) {
String token = authHeader.replace("Bearer ", "");
return userService.findByToken(token);
}
@GetMapping("/api/info")
public Map<String, String> info(
@RequestHeader("User-Agent") String userAgent,
@RequestHeader(value = "Accept-Language", defaultValue = "fr") String lang) {
return Map.of("userAgent", userAgent, "language", lang);
}
@CookieValue
Extracts a value from a cookie.
@GetMapping("/api/preferences")
public Preferences getPrefs(@CookieValue(value = "theme", defaultValue = "light") String theme) {
return new Preferences(theme);
}
@ModelAttribute
Binds form parameters to an object (mostly used with @Controller).
@PostMapping("/register")
public String register(@ModelAttribute RegistrationForm form) {
userService.register(form);
return "redirect:/login";
}
4. Response Annotations
@ResponseStatus
Sets the HTTP response code.
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // 201
public Product create(@RequestBody ProductDto dto) {
return productService.create(dto);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void delete(@PathVariable Long id) {
productService.delete(id);
}
Use with exceptions:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
5. Error Handling Annotations
@ExceptionHandler
Handles exceptions at the controller level.
@RestController
public class UserController {
@GetMapping("/api/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id); // May throw ResourceNotFoundException
}
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleNotFound(ResourceNotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}
@ControllerAdvice / @RestControllerAdvice
Global exception handling for all controllers.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
return new ErrorResponse("NOT_FOUND", ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidation(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.toList();
return new ErrorResponse("VALIDATION_ERROR", errors.toString());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleGeneral(Exception ex) {
return new ErrorResponse("INTERNAL_ERROR", "An error occurred");
}
}
6. CORS and Other Annotations
@CrossOrigin
Configures Cross-Origin Resource Sharing (CORS).
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class ApiController {
// All methods allow requests from localhost:3000
}
@GetMapping("/api/public")
@CrossOrigin(origins = "*", maxAge = 3600)
public String publicEndpoint() {
return "accessible from everywhere";
}
7. Validation Annotations
@Valid / @Validated
Enables validation of received data.
@PostMapping("/api/users")
public User create(@Valid @RequestBody CreateUserDto dto) {
return userService.create(dto);
}
public class CreateUserDto {
@NotNull(message = "Name is required")
@Size(min = 2, max = 50, message = "Name must be between 2 and 50 characters")
private String name;
@NotBlank(message = "Email is required")
@Email(message = "Invalid email format")
private String email;
@NotNull
@Size(min = 8, message = "Password must be at least 8 characters")
private String password;
@Min(value = 0, message = "Age must be positive")
@Max(value = 150, message = "Age must be less than 150")
private Integer age;
@Pattern(regexp = "^\\+?[0-9]{10,15}$", message = "Invalid phone number")
private String phone;
}
Available Validation Annotations
| Annotation | Description |
|---|---|
@NotNull | Cannot be null |
@NotEmpty | Not null and not empty (String, Collection) |
@NotBlank | Not null, not empty, not just spaces |
@Size(min, max) | Size between min and max |
@Min(value) | Minimum value (numbers) |
@Max(value) | Maximum value (numbers) |
@Email | Valid email format |
@Pattern(regexp) | Matches the regular expression |
@Positive | Strictly positive number |
@PositiveOrZero | Positive number or zero |
@Negative | Strictly negative number |
@Past | Date in the past |
@Future | Date in the future |
@DecimalMin | Minimum decimal value |
@DecimalMax | Maximum decimal value |
Quick Summary
| Annotation | Role |
|---|---|
@RestController | REST Controller (JSON) |
@RequestMapping | Basic URL mapping |
@GetMapping | GET |
@PostMapping | POST |
@PutMapping | PUT |
@PatchMapping | PATCH |
@DeleteMapping | DELETE |
@PathVariable | Parameter in URL |
@RequestParam | Query string parameter |
@RequestBody | JSON body → Object |
@RequestHeader | HTTP header |
@ResponseStatus | HTTP response code |
@ExceptionHandler | Local exception handling |
@RestControllerAdvice | Global exception handling |
@CrossOrigin | CORS configuration |
@Valid | Enables validation |
➡️ Chapter 3: Data and JPA Annotations