springMVC3 基于注解的输入验证

在pom.xml中加入,他需要validation-api.jar,hibernate-validator两个开发包

<!-- JSR 303 with Hibernate Validator -->
   <dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.0.0.GA</version>
   </dependency>
   <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.0.2.GA</version>
   </dependency>

.....再加入

<repositories>
   <!-- For JSR 303 and Hibernate Validator only - Encourage JBoss to publish these artifacts to Maven Central! -->
   <repository>
    <id>org.jboss.repository.maven</id>
    <url>http://repository.jboss.org/maven2</url>
    <snapshots><enabled>false</enabled></snapshots>
   </repository>
</repositories>

类的一个例子

 

package org . springframework . samples . mvc . basic . account ;

import java.math.BigDecimal ;
import java.util.Date ;
import java.util.concurrent.atomic.AtomicLong ;

import javax.validation.constraints.Future ;
import javax.validation.constraints.NotNull ;
import javax.validation.constraints.Size ;

import org.springframework.format.annotation.DateTimeFormat ;
import org.springframework.format.annotation.DateTimeFormat.ISO ;
import org.springframework.format.annotation.NumberFormat ;
import org.springframework.format.annotation.NumberFormat.Style ;

public class Account {

    private Long id ;

    @NotNull
    @Size (min = 1 , max = 25 )
    private String name ;

    @NotNull
    @NumberFormat (style = Style . CURRENCY )
    private BigDecimal balance = new BigDecimal ("1000" );

    @NotNull
    @NumberFormat (style = Style . PERCENT )
    private BigDecimal equityAllocation = new BigDecimal (".60" );

    @DateTimeFormat (iso = ISO . DATE )
    @Future
    private Date renewalDate = new Date (new Date (). getTime () + 31536000000L );

    public Long getId () {
        return id ;
    }

    void setId (Long id ) {
        this . id = id ;
    }

    public String getName () {
        return name ;
    }

    public void setName (String name ) {
        this . name = name ;
    }

    public BigDecimal getBalance () {
        return balance ;
    }

    public void setBalance (BigDecimal balance ) {
        this . balance = balance ;
    }

    public BigDecimal getEquityAllocation () {
        return equityAllocation ;
    }

    public void setEquityAllocation (BigDecimal equityAllocation ) {
        this . equityAllocation = equityAllocation ;
    }

    public Date getRenewalDate () {
        return renewalDate ;
    }

    public void setRenewalDate (Date renewalDate ) {
        this . renewalDate = renewalDate ;
    }

    Long assignId () {
        this . id = idSequence . incrementAndGet ();
        return id ;
    }

    private static final AtomicLong idSequence = new AtomicLong ();

}

然后配置你自己的message就可以,我这里是messages_zh_CN.properties

你可能感兴趣的:(springMVC)