Can I validate a form in spring mvc without using anotation?

Viewed 49

I read some document on the Internet about form validation in Spring MVC. And I don't know what happend if I use only Java core code (don't use anotation and something like BindingResult, hasError()...) for validation). Is there any convention that we must use anotation for validation. For example, I use Java core code in my Controller class:

    @RequestMapping("/login")
    public String showLogin(@ModelAttribute("member") Member member, Model model) {
       if("".equals(member.getUsername()){
           model.addAttribute("error", "username is empty");
       }
       return "login";
    }

And then I show error in my login.jsp file.

I'm a fresher java web developer, please explain it to me.

1 Answers

you can do without using annotations, but I believe it would be like taking the long way around, as annotations are made to ease the validation process.

there is the JSR 380 specification, it greatly simplifies your validation work.

please read this: https://www.baeldung.com/javax-validation

having understood what javax validation is, you can implement validations directly in your java classes, and in the controller you can validate using @Valid, as in the following example:

@RequestMapping("/login")
public String showLogin(@Valid Member member, Errors errors, Model model) {
   if(errors.hasErrors()) {
        return "login";
    }
   return "login";
}

this way, spring will validate your 'member' class and if it contains any errors, it will return the error messages to the page.

Related