Implement user service and controller with CRUD functions
[alyverkko.git] / src / main / java / eu / svjatoslav / alyverkko / controller / UserController.java
diff --git a/src/main/java/eu/svjatoslav/alyverkko/controller/UserController.java b/src/main/java/eu/svjatoslav/alyverkko/controller/UserController.java
new file mode 100644 (file)
index 0000000..2ac721d
--- /dev/null
@@ -0,0 +1,81 @@
+package eu.svjatoslav.alyverkko.controller;
+
+import eu.svjatoslav.alyverkko.models.User;
+import eu.svjatoslav.alyverkko.service.UserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("/users")
+public class UserController {
+
+    private final UserService userService;
+
+    @Autowired
+    public UserController(UserService userService) {
+        this.userService = userService;
+    }
+
+    @GetMapping
+    public List<User> getAllUsers() {
+        return userService.findAll();
+    }
+
+    @PostMapping
+    public User createUser(@RequestBody User user) {
+        return userService.save(user);
+    }
+
+    @DeleteMapping("/{id}")
+    public void deleteUser(@PathVariable Long id) {
+        userService.deleteById(id);
+    }
+
+
+    @GetMapping
+    public String listEntities(Model model) {
+        model.addAttribute("users", userService.findAll());
+        return "user/list";
+    }
+
+    @GetMapping("/{id}")
+    public String showEntity(@PathVariable Long id, Model model) {
+        User entity = userService.findById(id);
+        if (entity != null) {
+            model.addAttribute("user", entity);
+            return "user/show";
+        }
+        return "redirect:/user";
+    }
+
+    @GetMapping("/new")
+    public String createEntityForm(Model model) {
+        model.addAttribute("entity", new User());
+        return "user/edit";
+    }
+
+    @PostMapping
+    public String saveEntity(@ModelAttribute("entity") User user) {
+        userService.save(user);
+        return "redirect:/user";
+    }
+
+    @GetMapping("/{id}/edit")
+    public String editEntityForm(@PathVariable Long id, Model model) {
+        User entity = userService.findById(id);
+        if (entity != null) {
+            model.addAttribute("user", entity);
+            return "user/edit";
+        }
+        return "redirect:/user";
+    }
+
+    @DeleteMapping("/{id}")
+    public String deleteEntity(@PathVariable Long id) {
+        userService.deleteById(id);
+        return "redirect:/user";
+    }
+}
\ No newline at end of file