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;
}
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.