Create a model object to hold the input form values.
Data Model class to hold user name
public class UserBean { private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
Create a custom validator class and use ValidationUtils with custom error messages.
Validator class
import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; @Component public class UserValidator implements Validator{ @Override public boolean supports(Class paramClass) { return UserBean.class.equals(paramClass); } @Override public void validate(Object arg0, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "error.userName" , "Invalid user name"); } }
In controller, Call this validate method and handle as below.
Controller method
@RequestMapping(value = "/user", method = RequestMethod.POST) public String processUser(@ModelAttribute UserBean userBean, BindingResult result) { UserValidator.validate(userBean, result); if( ! result.hasErrors()) { return "success"; } return "input"; }
In your input.jsp page, add this below element where you want to show the message
<form:errors path="userName" cssStyle="color: #ff0000;"/>
No comments:
Post a Comment