Chapitre 2: Annotations Web et REST
1. Annotations de Contrôleur
@RestController vs @Controller
// Retourne des VUES (HTML)
@Controller
public class PageController {
@GetMapping("/home")
public String home() {
return "home"; // Cherche un template home.html
}
}
// Retourne des DONNÉES (JSON/XML)
@RestController
public class ApiController {
@GetMapping("/api/data")
public Map<String, String> getData() {
return Map.of("message", "Hello"); // Sérialisé en JSON automatiquement
}
}
@ResponseBody
Force le retour en JSON/XML (utilisé avec @Controller).
@Controller
public class MixedController {
@GetMapping("/page")
public String page() {
return "page"; // Retourne une vue
}
@GetMapping("/api/info")
@ResponseBody
public Map<String, String> info() {
return Map.of("version", "1.0"); // Retourne du JSON
}
}
2. Annotations de Mapping HTTP
@RequestMapping
Annotation de base pour mapper une URL à une méthode. Peut spécifier la méthode HTTP.
@RestController
@RequestMapping("/api/v1/products") // Préfixe pour toutes les méthodes
public class ProductController {
@RequestMapping(method = RequestMethod.GET)
public List<Product> getAll() { ... }
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Product getById(@PathVariable Long id) { ... }
}
@GetMapping
Raccourci pour @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
Raccourci pour @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
Raccourci pour @RequestMapping(method = PUT). Remplacement complet d'une ressource.
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @Valid @RequestBody ProductDto dto) {
return productService.update(id, dto);
}
@PatchMapping
Raccourci pour @RequestMapping(method = PATCH). Mise à jour partielle d'une ressource.
@PatchMapping("/{id}")
public Product partialUpdate(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
return productService.partialUpdate(id, updates);
}
@DeleteMapping
Raccourci pour @RequestMapping(method = DELETE).
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
Résumé des mappings
| Annotation | Méthode HTTP | Usage typique |
|---|---|---|
@GetMapping | GET | Lire des données |
@PostMapping | POST | Créer une ressource |
@PutMapping | PUT | Remplacer une ressource |
@PatchMapping | PATCH | Modifier partiellement |
@DeleteMapping | DELETE | Supprimer une ressource |
3. Annotations de Paramètres
@PathVariable
Extrait une valeur depuis l'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);
}
// Nom différent du paramètre de l'URL
@GetMapping("/api/categories/{category-name}")
public Category getCategory(@PathVariable("category-name") String categoryName) {
return categoryService.findByName(categoryName);
}
@RequestParam
Extrait un paramètre de la query string.
// GET /api/products?category=electronics
@GetMapping("/api/products")
public List<Product> getByCategory(@RequestParam String category) {
return productService.findByCategory(category);
}
// Paramètre optionnel avec valeur par défaut
// 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)));
}
// Paramètre optionnel sans valeur par défaut
@GetMapping("/api/search")
public List<Product> search(
@RequestParam(required = false) String name,
@RequestParam(required = false) BigDecimal minPrice) {
return productService.search(name, minPrice);
}
@RequestBody
Désérialise le corps de la requête (JSON → Objet Java).
@PostMapping("/api/users")
public User createUser(@RequestBody UserDto userDto) {
return userService.create(userDto);
}
// Corps de la requête (JSON)
{
"name": "Jean Dupont",
"email": "jean@example.com",
"password": "secret123"
}
@RequestHeader
Extrait une valeur d'un en-tête HTTP.
@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
Extrait une valeur d'un cookie.
@GetMapping("/api/preferences")
public Preferences getPrefs(@CookieValue(value = "theme", defaultValue = "light") String theme) {
return new Preferences(theme);
}
@ModelAttribute
Lie les paramètres de formulaire à un objet (surtout utilisé avec @Controller).
@PostMapping("/register")
public String register(@ModelAttribute RegistrationForm form) {
userService.register(form);
return "redirect:/login";
}
4. Annotations de Réponse
@ResponseStatus
Définit le code HTTP de la réponse.
@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);
}
Utiliser avec les exceptions:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
5. Annotations de Gestion d'Erreurs
@ExceptionHandler
Gère les exceptions au niveau du contrôleur.
@RestController
public class UserController {
@GetMapping("/api/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id); // Peut lancer ResourceNotFoundException
}
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleNotFound(ResourceNotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}
@ControllerAdvice / @RestControllerAdvice
Gestion globale des exceptions pour tous les contrôleurs.
@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", "Une erreur est survenue");
}
}
6. Annotations CORS et Autres
@CrossOrigin
Configure le Cross-Origin Resource Sharing (CORS).
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class ApiController {
// Toutes les méthodes autorisent les requêtes depuis localhost:3000
}
@GetMapping("/api/public")
@CrossOrigin(origins = "*", maxAge = 3600)
public String publicEndpoint() {
return "accessible de partout";
}
7. Annotations de Validation
@Valid / @Validated
Active la validation des données reçues.
@PostMapping("/api/users")
public User create(@Valid @RequestBody CreateUserDto dto) {
return userService.create(dto);
}
public class CreateUserDto {
@NotNull(message = "Le nom est obligatoire")
@Size(min = 2, max = 50, message = "Le nom doit faire entre 2 et 50 caractères")
private String name;
@NotBlank(message = "L'email est obligatoire")
@Email(message = "Format d'email invalide")
private String email;
@NotNull
@Size(min = 8, message = "Le mot de passe doit faire au moins 8 caractères")
private String password;
@Min(value = 0, message = "L'âge doit être positif")
@Max(value = 150, message = "L'âge doit être inférieur à 150")
private Integer age;
@Pattern(regexp = "^\\+?[0-9]{10,15}$", message = "Numéro de téléphone invalide")
private String phone;
}
Annotations de validation disponibles
| Annotation | Description |
|---|---|
@NotNull | Ne peut pas être null |
@NotEmpty | Pas null et pas vide (String, Collection) |
@NotBlank | Pas null, pas vide, pas que des espaces |
@Size(min, max) | Taille entre min et max |
@Min(value) | Valeur minimale (nombres) |
@Max(value) | Valeur maximale (nombres) |
@Email | Format email valide |
@Pattern(regexp) | Correspond à l'expression régulière |
@Positive | Nombre strictement positif |
@PositiveOrZero | Nombre positif ou zéro |
@Negative | Nombre strictement négatif |
@Past | Date dans le passé |
@Future | Date dans le futur |
@DecimalMin | Valeur décimale minimale |
@DecimalMax | Valeur décimale maximale |
Résumé Rapide
| Annotation | Rôle |
|---|---|
@RestController | Contrôleur REST (JSON) |
@RequestMapping | Mapping URL de base |
@GetMapping | GET |
@PostMapping | POST |
@PutMapping | PUT |
@PatchMapping | PATCH |
@DeleteMapping | DELETE |
@PathVariable | Paramètre dans l'URL |
@RequestParam | Paramètre query string |
@RequestBody | Corps JSON → Objet |
@RequestHeader | En-tête HTTP |
@ResponseStatus | Code de réponse HTTP |
@ExceptionHandler | Gestion d'exception locale |
@RestControllerAdvice | Gestion d'exception globale |
@CrossOrigin | Configuration CORS |
@Valid | Active la validation |
➡️ Chapitre 3: Annotations Data et JPA