📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 10

Retour
Contrôleur REST simple (@RestController)
Facile
@RestController
public class MonControleur {
    @GetMapping("/hello")
    public String sayHello() {
        return "Bonjour le monde !";
    }
}
Extraire un paramètre de requête (@RequestParam)
Facile
@GetMapping("/search")
public List<User> searchUsers(@RequestParam String query) {
    // ...
}
Gestionnaire d'exceptions global (@ControllerAdvice)
Avancé
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}
Mapping DELETE (@DeleteMapping)
Facile
@DeleteMapping("/utilisateurs/{id}")
public void deleteUser(@PathVariable Long id) {
    // ...
}
Mapping GET (@GetMapping)
Facile
@GetMapping("/utilisateurs/{id}")
public User getUserById(@PathVariable Long id) {
    // ...
}
Mapping POST (@PostMapping)
Facile
@PostMapping("/utilisateurs")
public User createUser(@RequestBody User user) {
    // ...
}
Mapping PUT (@PutMapping)
Facile
@PutMapping("/utilisateurs/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
    // ...
}
Utiliser ResponseEntity pour un contrôle total
Intermédiaire
@GetMapping("/utilisateurs/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
    User user = service.findById(id);
    return ResponseEntity.ok(user);
}
Validation des requêtes (@Valid)
Intermédiaire
public ResponseEntity<User> createUser(@Valid @RequestBody User user) { ... }
WebFlux : Contrôleur réactif
Avancé
@GetMapping("/events")
public Flux<Event> getEvents() {
    return eventRepository.findAll();
}