0

我有以下设置:

IndexCntl.java(控制器):

@RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, ModelMap map) {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        String formattedDate = dateFormat.format(date);
        map.addAttribute("serverTime", formattedDate );
        map.addAttribute("email", new Email());
        Map sexoOpts = new HashMap();
        sexoOpts.put("M", "Homem");
        sexoOpts.put("F", "Mulher");

        map.addAttribute("sexoList", sexoOpts);
        return "index";
    }

@RequestMapping(value = "/save-email", method = RequestMethod.POST)
    public String doSaveEmail(@Valid @ModelAttribute("email") Email email, Model model, BindingResult result){
        log.info("Email debug: "+email.getEmail()+" "+email.getMysexy()+" "+email.getWantedsexy());

        if (result.hasErrors()){
            log.info("Entrou result.hasError()");
            return "index";
        }
        Date date = new Date();
        email.setCreationDate(date);
        try{
            emailBo.saveEmail(email);
        }catch(Exception e){
            e.printStackTrace();
        }
        model.addAttribute("email", new Email());
        return "index";
    }

index.jsp(视图):

<form:form action="save-email" method="POST" modelAttribute="email" cssStyle="display:-webkit-box">
                <form:select path="mysexy" cssStyle="width:120px;">
                    <form:option value="" label="- Sou -"/>
                    <form:options items="${sexoList}" />
                </form:select>
                <form:errors path="mysexy" cssClass="errors"/>
                <form:select path="wantedsexy" cssStyle="width:120px;">
                    <form:option value="" label="- Busco -"/>
                    <form:options items="${sexoList}" />
                </form:select>
                <form:errors path="wantedsexy" cssClass="errors"/>
                <br/>
                <form:errors path="wantedsexy" cssClass="errors"/>
                <div class="input-append">
                    <input type="text" id="email" name="email" size="30" maxlength="30" placeholder="E-mail" class=""/>
                    <form:errors path="email" cssClass="errors"/>
                    <input id="btncadastrar" class="btn btn-block btn-primary" type="submit" value="Cadastrar E-mail"/>
                </div>
            </form:form>

和模型Email.java的一部分:

@Document
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Email extends BaseBean {

    // @Pattern(regexp =
    // "^[\\w\\-]+(\\.[\\w\\-]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$",
    // message="E-mail com formato incorreto.")
    @NotNull(message = "Não pode ser vazio")
    @NotEmpty(message = "Não pode ser vazio-nulo")
    @org.hibernate.validator.constraints.Email(message = "E-mail inválido")
    private String email;

    @NotEmpty(message = "Informe ao menos um valor")
    private String mysexy;

    @NotEmpty(message = "Informe ao menos um valor")
    private String wantedsexy;

当我尝试在输入中输入空电子邮件时收到此错误:

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'email' on field 'email': rejected value []; codes [NotEmpty.email.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [email.email,email]; arguments []; default message [email]]; default message [Não pode ser vazio-nulo]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'email' on field 'email': rejected value []; codes [NotEmpty.email.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [email.email,email]; arguments []; default message [email]]; default message [Não pode ser vazio-nulo]
    org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:110)

我的设置有什么问题???

4

1 回答 1

1

您明确禁止空值:

    @NotNull(message = "Não pode ser vazio")
--> @NotEmpty(message = "Não pode ser vazio-nulo") 
    @org.hibernate.validator.constraints.Email(message = "E-mail inválido")
    private String email;

Hibernate 在保存或更新之前验证实体,并且您的实体失败。

您可以在persistence.xml文件配置中禁用此验证。

<persistence ...>
  <persistence-unit ...>
    ...
    <properties>
      <property name="javax.persistence.validation.mode" value="none"/>
    </properties>
  </persistence-unit>
</persistence>

如果您只想检查一些验证规则,那么您可以使用“验证组”


如果您的问题是未调用控制器方法,那么这是@Valid因为Email. 如果您希望在带有@Valid注释的参数无效时调用控制器方法,那么您需要一个类型为BindingResultDIRECTLY AFTER 的参数

public String doSaveEmail(@Valid @ModelAttribute("email") Email email, BindingResult resultForEmail, Model model, BindingResult resultForModel)
于 2012-09-21T14:48:50.487 回答