I'm developing an web app using Spring MVC and Hibernate where I have the users log in to the system to access the inner pages. This is done using an interceptor that checks on Session Variables.
I can correctly Register looking for valid values. But in case of login, where I just need username and password, I'm having trouble on how to log in using bean validation, for It accuses that there's no e-mail and so on.
This is the User class:
@Entity
public class User{
@Id
@GeneratedValue
private int id;
@NotNull
@Column(name="username",unique=true)
@Size(min=5)
private String username;
@NotNull
@Email
private String email;
@NotNull
@Size(min=5)
private String password;
private String salt;
private int status;
private String name;
private String company;
private int countryid;
@DateTimeFormat(pattern="dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Calendar subscriptionDate;
//Getters and Setters
}
The Controller:
@Transactional
@Controller
public class LoginController {
@Autowired
UserDao dao;
// Other Mappings
@RequestMapping(value = "addUser", method = RequestMethod.POST)
public String makeRegistration(@ModelAttribute("user") @Valid User user, BindingResult result,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "redirect:register";
}
if (dao.add(user)) {
redirectAttributes.addFlashAttribute("user", user);
return "redirect:login";
} else {
return "redirect:register";
}
}
@RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin(@ModelAttribute("user") @Valid User user, BindingResult result, HttpSession session) {
if (result.hasErrors()) {
return "redirect:login";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
\\ Other mappings.
How can I use the "User" class for both Login and Registration? Do I have to use inhertance?