Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.demo.controller;
- import com.example.demo.domain.User;
- import com.example.demo.services.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.*;
- import java.util.List;
- @Controller
- @RequestMapping
- public class UserController {
- // This means to get the bean called userService
- // Which is auto-generated by Spring, we will use it to handle the data
- @Autowired
- private UserService userService;
- /**
- * Get all the users in the system
- */
- @GetMapping(path = "/list")
- public @ResponseBody String getAllUsers() {
- List<User> users = userService.findAllUsers();
- if (users.isEmpty()) {
- return "No users are presented in the database";
- }
- else {
- return "The following users are presented in the database:\n\n" +
- userService.getAllUsernames(users).toString();
- }
- }
- /**
- * Get a specific user based on their ID and their roles assigned
- * @param id
- */
- @GetMapping(path = "/get/{id}")
- public @ResponseBody String getUserById(@PathVariable Long id) {
- if (!userService.isExistingUserById(id)) {
- return "There is no user with ID " + id.toString();
- }
- User user = userService.getUser(id);
- return "User details:\n\nName: "+user.getName() + "\nUsername: " + user.getLogin() +
- "\nPassword: " + user.getPassword() + "\nHas following roles: \n" + userService.getUserRoles(id);
- }
- /**
- * Adding a new user
- * @param user
- */
- @PostMapping(path = "/add")
- public @ResponseBody String addUser(@RequestBody User user) {
- userService.saveUser(user);
- return "New user has been saved";
- }
- /**
- * Delete a user
- * @param id
- */
- @DeleteMapping(path = "/delete/{id}")
- public @ResponseBody String deleteUser(@PathVariable("id") Long id) {
- userService.deleteUserById(id);
- return "User having id number " + id.toString() + " has been deleted.";
- }
- /**
- * Edit user's details or add a new user if doesn't exist
- * @param newUser
- * @param id
- */
- @PutMapping(path = "/edit/{id}")
- public @ResponseBody User editUser(@RequestBody User newUser, @PathVariable("id") Long id) {
- return userService.editUser(newUser, id);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement