Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. package com.example.demo.controller;
  2.  
  3. import com.example.demo.domain.User;
  4. import com.example.demo.services.UserService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.*;
  8.  
  9. import java.util.List;
  10.  
  11. @Controller
  12. @RequestMapping
  13. public class UserController {
  14. // This means to get the bean called userService
  15. // Which is auto-generated by Spring, we will use it to handle the data
  16. @Autowired
  17. private UserService userService;
  18.  
  19. /**
  20. * Get all the users in the system
  21. */
  22. @GetMapping(path = "/list")
  23. public @ResponseBody String getAllUsers() {
  24. List<User> users = userService.findAllUsers();
  25. if (users.isEmpty()) {
  26. return "No users are presented in the database";
  27. }
  28. else {
  29. return "The following users are presented in the database:\n\n" +
  30. userService.getAllUsernames(users).toString();
  31. }
  32. }
  33.  
  34. /**
  35. * Get a specific user based on their ID and their roles assigned
  36. * @param id
  37. */
  38. @GetMapping(path = "/get/{id}")
  39. public @ResponseBody String getUserById(@PathVariable Long id) {
  40. if (!userService.isExistingUserById(id)) {
  41. return "There is no user with ID " + id.toString();
  42. }
  43.  
  44. User user = userService.getUser(id);
  45. return "User details:\n\nName: "+user.getName() + "\nUsername: " + user.getLogin() +
  46. "\nPassword: " + user.getPassword() + "\nHas following roles: \n" + userService.getUserRoles(id);
  47. }
  48.  
  49. /**
  50. * Adding a new user
  51. * @param user
  52. */
  53. @PostMapping(path = "/add")
  54. public @ResponseBody String addUser(@RequestBody User user) {
  55. userService.saveUser(user);
  56. return "New user has been saved";
  57. }
  58.  
  59. /**
  60. * Delete a user
  61. * @param id
  62. */
  63. @DeleteMapping(path = "/delete/{id}")
  64. public @ResponseBody String deleteUser(@PathVariable("id") Long id) {
  65. userService.deleteUserById(id);
  66. return "User having id number " + id.toString() + " has been deleted.";
  67. }
  68.  
  69. /**
  70. * Edit user's details or add a new user if doesn't exist
  71. * @param newUser
  72. * @param id
  73. */
  74. @PutMapping(path = "/edit/{id}")
  75. public @ResponseBody User editUser(@RequestBody User newUser, @PathVariable("id") Long id) {
  76. return userService.editUser(newUser, id);
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement