简体   繁体   English

Spring MVC 3.1具有Hibernate 4.3验证和错误

[英]Spring mvc 3.1 with hibernate 4.3 validation and errors

I had the following setup: 我有以下设置:

IndexCntl.java (Controller): 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 (view): 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>

and part of the model Email.java: 以及模型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;

and i'm receiving this error when i try to pass with a empty email in input: 当我尝试通过输入中的空电子邮件传递时,我收到此错误:

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)

what can be wrong in my setup??? 我的设置有什么问题???

You explicit forbid empty values: 您明确禁止空值:

    @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 validate the entity before saving or update, and your entity fails. Hibernate在保存或更新之前验证实体,您的实体将失败。

You can disable this validation in you persistence.xml file configuration. 您可以在persistence.xml文件配置中禁用此验证。

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

If you want to check only some validation rules, then you can use "Validation Groupes" 如果您只想检查一些验证规则,则可以使用“验证组”


If your problem is that the controller method is not invoked, then it is because of the @Valid annotation for Email . 如果您的问题是未调用controller方法,则是因为Email@Valid注释。 If you want to have a controller method to be invoked event if a parameter with @Valid annotaton is not valid, then you need a parameter of type BindingResult DIRECTLY AFTER that parameter 如果想要带有@Valid注释的参数无效的事件时要调用控制器方法,则该参数直接需要BindingResult类型的参数

public String doSaveEmail(@Valid @ModelAttribute("email") Email email, BindingResult resultForEmail, Model model, BindingResult resultForModel)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM