@RequestMapping("/validateMsg")
public boolean validateEmp(@ModelAttribute Employee emp,BindingResult bindingResult,Model model){
boolean iserror=false;
if(emp.getFirstName()=="")
{
model.addAttribute("firstName","firstName is required");
iserror=true;
}
return iserror;
}
我写的这段代码是正确的
答案 0 :(得分:1)
您可以使用验证器。
@Component
public class EmploeeValidator implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return Emploee.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "someProp", "someProp.empty");
//other valdiation...
}
}
然后在控制器中
@Autowired
private EmploeeValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
使用它:
@RequestMapping("/emploee")
public boolean addEmp(@Valid Employee emp,Errors errors){
if(errors.hasErrors()){
//it's not valid
} else {
//ok
}
}