我正在尝试验证包含电子邮件的 Spring Bean,但是当请求 Bean 中的电子邮件以空字符串形式出现时,验证器和 BindingResult 都没有显示任何错误。请看下面的代码:
豆:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springmodules.validation.bean.conf.loader.annotation.handler.Email;
import org.springmodules.validation.bean.conf.loader.annotation.handler.NotEmpty;
@Component("grouponRedemptionFormBean")
@Scope("prototype")
public class GrouponRedemptionBean {
@NotEmpty(message = "Please enter your email addresss.")
@Email(message = "Please correct your email.")
private String email;
…
}
控制器:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class GrouponVoucherRedemptionController {
@Autowired
@Qualifier("defaultBeanValidator")
private Validator validator;
@RequestMapping(value="/groupon-redemption.ep", method=RequestMethod.POST)
public String PostGrouponRedemption(@Valid @ModelAttribute GrouponRedemptionBean grouponRedemptionBean, BindingResult bindingResult,
HttpServletRequest request, HttpServletResponse response, Model model){
Errors errors = new BeanPropertyBindingResult(grouponRedemptionBean, "grouponRedemptionFormBean");
validator.validate(grouponRedemptionBean, errors);
if(errors.hasErrors()) {
bindingResult.addAllErrors(errors);
}
if (bindingResult.hasErrors()) {
return GROUPON_REDEMPTION_VIEW;
}
...
XML配置:
<mvc:annotation-driven />