Advertisement
Guest User

Untitled

a guest
Jul 6th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. package com.myshop.model;
  2.  
  3. import javax.validation.constraints.Email;
  4.  
  5. public class LoginUser {
  6.  
  7. @Email(message = "Nieprawidłowy format adresu e-mail")
  8. String email;
  9.  
  10. String password;
  11.  
  12. public String getEmail() {
  13. return email;
  14. }
  15.  
  16. public void setEmail(String email) {
  17. this.email = email;
  18. }
  19.  
  20. public String getPassword() {
  21. return password;
  22. }
  23.  
  24. public void setPassword(String password) {
  25. this.password = password;
  26. }
  27. }
  28.  
  29. package com.myshop.controllers;
  30.  
  31. import com.myshop.model.LoginUser;
  32. import com.myshop.model.User;
  33. import com.myshop.repositories.UserRepository;
  34. import org.springframework.beans.factory.annotation.Autowired;
  35. import org.springframework.stereotype.Controller;
  36. import org.springframework.ui.Model;
  37. import org.springframework.validation.BindingResult;
  38. import org.springframework.web.bind.annotation.GetMapping;
  39. import org.springframework.web.bind.annotation.ModelAttribute;
  40. import org.springframework.web.bind.annotation.PostMapping;
  41. import org.springframework.web.servlet.ModelAndView;
  42.  
  43. import javax.validation.Valid;
  44.  
  45. @Controller
  46. public class LoginController {
  47.  
  48. @Autowired
  49. UserRepository userRepository;
  50.  
  51. @GetMapping("/login")
  52. public String loginForm(Model model) {
  53. model.addAttribute("loginUser", new LoginUser());
  54. return "login";
  55. }
  56.  
  57. @PostMapping("/login")
  58. public ModelAndView loginSubmit(@Valid @ModelAttribute LoginUser loginUser, BindingResult bindingResult, Model model) {
  59. if(bindingResult.hasErrors()){
  60. ModelAndView modelAndView = new ModelAndView("login");
  61. return modelAndView;
  62. }
  63. User user = userRepository.findByEmailAndPassword(loginUser.getEmail(), loginUser.getPassword());
  64. if (user != null) {
  65. ModelAndView modelAndView = new ModelAndView("forward:/");
  66. modelAndView.addObject("user",user);
  67. modelAndView.addObject("error","error");
  68.  
  69. return modelAndView;
  70. } else {
  71. model.addAttribute("error", "Błędny login i/lub hasło");
  72. ModelAndView modelAndView = new ModelAndView("redirect:/login");
  73. modelAndView.addObject("error",model);
  74. return modelAndView;
  75. }
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement