|
| 1 | +package com.baeldung.crud.controllers; |
| 2 | + |
| 3 | +import com.baeldung.crud.UserRepository; |
| 4 | +import com.baeldung.crud.entities.User; |
| 5 | +import javax.validation.Valid; |
| 6 | +import org.springframework.beans.factory.annotation.Autowired; |
| 7 | +import org.springframework.stereotype.Controller; |
| 8 | +import org.springframework.ui.Model; |
| 9 | +import org.springframework.validation.BindingResult; |
| 10 | +import org.springframework.web.bind.annotation.GetMapping; |
| 11 | +import org.springframework.web.bind.annotation.PathVariable; |
| 12 | +import org.springframework.web.bind.annotation.PostMapping; |
| 13 | + |
| 14 | +@Controller |
| 15 | +public class UserController { |
| 16 | + |
| 17 | + private final UserRepository userRepository; |
| 18 | + |
| 19 | + @Autowired |
| 20 | + public UserController(UserRepository userRepository) { |
| 21 | + this.userRepository = userRepository; |
| 22 | + } |
| 23 | + |
| 24 | + @GetMapping("/signup") |
| 25 | + public String showSignUpForm(User user) { |
| 26 | + return "add-user"; |
| 27 | + } |
| 28 | + |
| 29 | + @PostMapping("/adduser") |
| 30 | + public String addUser(@Valid User user, BindingResult result, Model model) { |
| 31 | + if (result.hasErrors()) { |
| 32 | + return "add-user"; |
| 33 | + } |
| 34 | + |
| 35 | + userRepository.save(user); |
| 36 | + model.addAttribute("users", userRepository.findAll()); |
| 37 | + return "index"; |
| 38 | + } |
| 39 | + |
| 40 | + @GetMapping("/edit/{id}") |
| 41 | + public String showUpdateForm(@PathVariable("id") long id, Model model) { |
| 42 | + User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); |
| 43 | + model.addAttribute("user", user); |
| 44 | + return "update-user"; |
| 45 | + } |
| 46 | + |
| 47 | + @PostMapping("/update/{id}") |
| 48 | + public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) { |
| 49 | + if (result.hasErrors()) { |
| 50 | + user.setId(id); |
| 51 | + return "update-user"; |
| 52 | + } |
| 53 | + |
| 54 | + userRepository.save(user); |
| 55 | + model.addAttribute("users", userRepository.findAll()); |
| 56 | + return "index"; |
| 57 | + } |
| 58 | + |
| 59 | + @GetMapping("/delete/{id}") |
| 60 | + public String deleteUser(@PathVariable("id") long id, Model model) { |
| 61 | + User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); |
| 62 | + userRepository.delete(user); |
| 63 | + model.addAttribute("users", userRepository.findAll()); |
| 64 | + return "index"; |
| 65 | + } |
| 66 | +} |
0 commit comments