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;
}
2
  • Have you looked at this question: stackoverflow.com/questions/4013378/…? Commented Apr 25, 2017 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? Commented Apr 25, 2017 at 18:36

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

2 Comments

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)?
Hi Friend. result.rejectValue("usernameField", "error code", "Not Found username message"); is working fine.

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.