@Data
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int id;
@Column(name = "email")
@Email(message = "*Please provide a valid Email")
@NotEmpty(message = "*Please provide an email")
private String email;
@Column(name = "password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
private String password;
@Column(name = "name")
@NotEmpty(message = "*Please provide your name")
private String name;
@Column(name = "last_name")
@NotEmpty(message = "*Please provide your last name")
private String lastName;
@Column(name = "active")
private int active;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
}
@Data
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private int id;
@Column(name = "role")
private String role;
}
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
User findByEmail(String email);
}
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer> {
Role findByRole(String role);
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public User findUserByEmail(String email) {
return userRepository.findByEmail(email);
}
public void saveUser(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setActive(1);
Role userRole = roleRepository.findByRole("USER");
user.setRoles(new HashSet<Role>(Arrays.asList(userRole)));
userRepository.save(user);
}
}
"redirect:/home";
а в зависимости от ролей? "/admin/home"
"/user/home"
"/doctor/home"
<form action="#" th:action="@{/cars/add}" th:object="${car}" method="post">
<input type="text" class="form-control" id="color" required th:field="*{color}">
@PostMapping("/cars/add")
public String addCar(@ModelAttribute Car car) {
carService.createCar(car);
return "main";
}
мой метод Get в контроллере выглядит так: