×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Andras Madi-Szabo
Added: May 19, 2020 10:51 AM
Modified: May 19, 2020 10:51 AM
Views: 4355
Tags: pet vizsga
  1. import com.greenfoxacademy.pet_shelter.models.Error;
  2. import com.greenfoxacademy.pet_shelter.models.Human;
  3. import com.greenfoxacademy.pet_shelter.services.HumanService;
  4. import javassist.NotFoundException;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.ModelAttribute;
  10. import org.springframework.web.bind.annotation.PathVariable;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12.  
  13. @Controller
  14. public class MainController {
  15.  
  16.   private HumanService humanService;
  17.  
  18.   @Autowired
  19.   public MainController(HumanService humanService) {
  20.     this.humanService = humanService;
  21.   }
  22.  
  23.   @GetMapping("/list-humans")
  24.   public String listHumans(Model model) {
  25.     model.addAttribute("humans", humanService.returnAllHuman());
  26.     return "main";
  27.   }
  28.  
  29.   @GetMapping("/add-human")
  30.   public String addHuman(Model model) {
  31.     model.addAttribute("human", new Human());
  32.     return "modify";
  33.   }
  34.  
  35.   @PostMapping("/add-human")
  36.   public String addHuman(@ModelAttribute Human human, Model model) {
  37.     if (human.getName() == null || human.getAge() == 0 || human.getName().isEmpty()) {
  38.       model.addAttribute("error", new Error("Something went wrong, please check if the fields are filled out or use another name, because the name is already taken"));
  39.       model.addAttribute("human", human);
  40.       return "modify";
  41.     }
  42.     humanService.saveHuman(human);
  43.     return "redirect:/list-humans";
  44.   }
  45.  
  46.   @GetMapping("/delete/{id}")
  47.   public String deleteHuman(@PathVariable Long id) throws NotFoundException {
  48.     humanService.deleteHuman(id);
  49.     return "redirect:/list-humans";
  50.   }
  51.  
  52.   @GetMapping("/edit/{id}")
  53.   public String editHuman(@PathVariable Long id, Model model) {
  54.     model.addAttribute("human", humanService.returnHumanById(id));
  55.     model.addAttribute("isEdit", true);
  56.     return "modify";
  57.   }
  58.  
  59.   @PostMapping("/edit/{id}")
  60.   public String editHuman(@PathVariable Long id, @ModelAttribute Human human) {
  61.     human.setId(id);
  62.     humanService.editHuman(human);
  63.     return "redirect:/list-humans";
  64.   }
  65.  
  66. }