Spring 3 Controller Notes
Validation
Let the controller know what validator to use and what to validate.
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.WebDataBinder;
@InitBinder("myCommand")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(this.myValidator);
}
Gain access to the errors by bringing BindingResult
into the method signature. BindingResult
must immediately succeed your model attribute.
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.ui.Model;
public void submit(@Valid MyCommand myCommand, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
/* good */
} else {
/* bad */
}
}