avengerbot

Java Spring Rest Controller with Service Example (Simple + Exception Handling)

Jul 11th, 2022 (edited)
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. @RestController
  2. @RequestMapping (value = "/test")
  3. public class TestController {
  4.  
  5.     private final UserService userService;
  6.  
  7.     public TestController(UserService userService) {
  8.         this.userService = userService;
  9.     }
  10.    
  11.     // Получить пользователя по его уникальному идентификатору (простой)
  12.     // localhost:8080/test/users/get/id (любое целое число)
  13.     @RequestMapping(value = "/users/get/{id}", method = RequestMethod.GET)
  14.     public String fetchUser(@PathVariable Long id) {
  15.         return userService.fetchUser(id);
  16.     }
  17.    
  18.     // Получить пользователя по его уникальному идентификатору (с обработкой исключений)
  19.     // localhost:8080/test/users/get/id (любое целое число)
  20.     @RequestMapping(value = "/users/get/{id}", method = RequestMethod.GET)
  21.     public String getSimpleGreeting(@PathVariable Long id) {
  22.         try {
  23.             return ResponseEntity.status(HttpStatus.OK).body(userService.fetchUser(id));
  24.         } catch (UserNotFoundException exception) {
  25.             return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(HttpStatus.BAD_REQUEST.getReasonPhrase());
  26.         }
  27.     }
  28.      
  29. }
Add Comment
Please, Sign In to add comment