0

I'm converting Struts 1.3 project to Spring. Instead of struts form fields, I'm using spring form.

I have used ActionErrors in struts to highlight the field using errorStyleClass attribute.

Similarly, in spring cssErrorClass is available. But, How to use it after the dao validation?

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("login") @Validated Login login, BindingResult result, Model model) {

    if (result.hasErrors()) {

        //THIS VALIDATION DONE BY ANNOTATION AND HIGHLIGHTING THE FIELD
        //USING "cssErrorClass"

        return HOMEPAGE;
    }

    boolean checkAuthentication = authService.checkAuthentication(login);

    if(!checkAuthentication){

        // HOW TO SET THE ERROR HERE?

        // Is there any way to set the error like

        // error.setMessage("userId","invalid.data");

        // so that, is it possible to display error message by 
        // highlighting the fields using "cssErrorClass"?

    }


    return HOMEPAGE;
}
Shakthi
  • 826
  • 3
  • 15
  • 33
  • Have you looked at this question: http://stackoverflow.com/questions/4013378/spring-mvc-and-jsr-303-hibernate-conditional-validation?rq=1? – Ivan Pronin Apr 25 '17 at 18:14
  • Yes. I have seen this example. But, it says, no validate method defined. If validate method is to be created, what should be the implementation inside? – Shakthi Apr 25 '17 at 18:36

1 Answers1

0

You need to annotate your entities using Java Bean Validation framework JSR 303, like this

public class Model{
  @NotEmpty
  String filed1;

  @Range(min = 1, max = 150)
  int filed2;

  ....
}

And add @Valid to your controller, like this

public class MyController {

public String controllerMethod(@Valid Customer customer, BindingResult result) {
    if (result.hasErrors()) {
        // process error
    } else {
        // process without errors
    }
}

You can find more examples for it here and here

EDIT:

If you want to register more errors based on custom validation steps in code, you can use rejectValue() method in the BindingResult instance, like this:

bindingResult.rejectValue("usernameField", "error code", "Not Found username message");
fujy
  • 5,168
  • 5
  • 31
  • 50
  • Hi. My question is, in the else part, I have dao call and validating the login credential from database. If the details are incorrect, how will you achieve the same scenario like result.hasErrors() in the else part again (after the db call)? – Shakthi Apr 25 '17 at 18:42
  • Hi Friend. `result.rejectValue("usernameField", "error code", "Not Found username message");` is working fine. – Shakthi Apr 25 '17 at 23:50