1

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?

2 Answers 2

1

Certainly not inheritance! Think about the role of your data structures. What do you need to back your login form. Well, simply a LoginForm. Is it persistent data? Absolutely not. What is the relation between a LoginForm and a User? Well, the first helps identify the last. Now what I think you should do is develop a LoginForm object with its validation requirement. This object won't be persistent, but will be a parameter to a method you will use to retrieve the persistent User which has its own validation.

To precise things a bit, I would introduce a new class:

public class LoginForm implements Serializable {

    @NotNull
    @Column(name="username", unique=true)
    @Size(min=5)
    private String username;

    @NotNull
    @Size(min=5)
    private String password;

    //Getters and Setters

}

... and modify the signature of your authentication method:

    @RequestMapping(value = "enter", method = RequestMethod.POST)
    public String doLogin(@ModelAttribute("user") @Valid LoginForm loginForm, BindingResult result, HttpSession session) {
        // ...
    }

By the way, I'm not sure persisting a password is such a great idea. You could save a hash or decide that authentication is the domain of an external directory.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you give a concrete example so I can understand the idea? You mean something like "Loginform implements Validator"; "public void Validate(User user, Error error){//validation logic}"
Yeah, now I can understand. Just as a side question, can I load in form:errors errors from the validation? Also, I'm hashing all passwods, hence the salt field.
This is the role of the BindingResult check here for a primer: spring.io/guides/gs/validating-form-input
1

I guess you should create registration and login controller to keep the code clean and simple. Let the code look stupid, it will be easy to maintain and will be open for further implementation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.