Hibernate 验证器不工作

Hibernate validator doesn't work

我将 Hibernate 验证器与 Hibernate 和 Spring 一起使用,但验证似乎不起作用。当我不输入字符串或输入 1 个字符的字符串(不在 min=4max=20 之间)时,没有显示任何错误,因此保存在 table 中。我错过了什么?

package dao;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name="etudiant")
public class Etudiant {

    @Id
    @Column(name="ID_ETUDIANT")
    @GeneratedValue
    private Long idEtudiant;

    @Column(name="NOM")
    @Size (min=4, max=20)
    private String nom;

    @Size(min=4, max=20, message="nom doit etre entre 4 et 20 svp..")
    @Column(name="PRENOM")
    private String prenom;

    @Column(name="DATE_NAISSANCE")
    @Temporal(TemporalType.DATE)
    private Date dateNaissance;

    @NotNull
    @Column(name="EMAIL")
    private String email;

    public Etudiant() {
        super();
    }

    public Long getIdEtudiant() {
        return idEtudiant;
    }

    public void setIdEtudiant(Long idEtudiant) {
        this.idEtudiant = idEtudiant;
    }

    public Etudiant(String nom, String prenom, Date dateNaissance, String email) {
        super();
        this.nom = nom;
        this.prenom = prenom;
        this.dateNaissance = dateNaissance;
        this.email = email;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public Date getDateNaissance() {
        return dateNaissance;
    }

    public void setDateNaissance(Date dateNaissance) {
        this.dateNaissance = dateNaissance;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

控制器:

@RequestMapping(value="save",method=RequestMethod.POST)
public String  saveetudient(Model md,
        @Valid @ModelAttribute("etudiant") Etudiant et, 
        BindingResult res) {
    if (res.hasErrors()) {
        List <Etudiant> ets=service.listeEtudiants();
        md.addAttribute("etudiants",ets);
        return "etudiant1";
    }
    else {
        service.addEtudiant(et);
        List <Etudiant> ets=service.listeEtudiants();
        md.addAttribute("etudiants",ets);
        return "etudiant1";
    }
}

在JSP中我放了这行来显示错误:

<form action="save" method="post">

  <table border="1" width="500" bgcolor="grey">

 <tr> 

 <th>Nom </th>
<th>Prenom </th>
<th> Date de naissance</th>
<th>Email </th>
</tr>


<tr> 
 <td>  <input type="text" name="nom" >   </td>
 <td> <input type="text" name="prenom" >  </td>
 <td>  <input type="text" name="dateNaissance" > </td>
  <td> <input type="text" name="email" >  </td>
 </tr>

 </table>  <br>
 <input type="submit" value="ajouter">

 <sform:errors path="etudiant.*"/>
 <sform:errors path="prenom"/> 
</form>

XML 文件配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">

<context:component-scan base-package="controller"/>
<mvc:annotation-driven/>

<bean class="dao.DaoEtudiantImpl" name="daoetud"></bean>

<bean class="service.EtudiantMetierImpl" name="servetud">
  <property name="dao"  ref="daoetud"></property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />

  <bean id="viewResolver"        
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
    <value>/WEB-INF/</value>
 </property>
 <property name="suffix">
  <value>.jsp</value>

 </property>

花了一个小时学习了两个验证教程后:

Hibernate Validator Annotations Example

Spring MVC Form Validation Annotation Example

我建议你一些解决方案。

1) 验证休眠验证注释是否有效

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();    
Validator validator = factory.getValidator();   
Set<ConstraintViolation<Etudiant>> constraintViolations = validator.validate(etudiant);

2) 您可以创建自定义验证器,例如 EtudiantValidator,然后像下面这样手动验证:

@RequestMapping(value="save",method=RequestMethod.POST)
public String  saveetudient(Model md,@ModelAttribute("etudiant") Etudiant etudiant, BindingResult res){
    new EtudiantValidator().validate(etudiant, result);
    ...
}   

但是我深入研究了你的代码,我发现你在这个方法上有一个错误:

@RequestMapping(value="save",method=RequestMethod.POST)
public String  saveetudient(Model md,
        @Valid @ModelAttribute("etudiant") Etudiant et, 
        BindingResult res)

应该改成下面这样

@RequestMapping(value="save",method=RequestMethod.POST)
public String  saveetudient(Model md,
        @Valid @ModelAttribute("etudiant") Etudiant etudiant, 
        BindingResult res)

希望对您有所帮助!

终于找到错误了, 问题是我没有添加 hibernate-validator jar 我只在 dist/lib/required 中添加了文件:

  • 同学-1.3.1

  • javax.el-2.2.4 -javax.el-api-2.2.2

  • jboss-logging-3.3.0.Final

  • 验证-api-1.1.0

    因此,如果有人遇到这种情况,只需添加:hibernate-validator-5.3.2.Final.