@Valid springMVC bean校驗不起作用


    @RequestMapping("/add2")
    public String addStudentValid(@Valid @ModelAttribute("s") Student s,BindingResult result){
        if(result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            
            for (FieldError fieldError : fieldErrors) {
                log.info("errors --"+fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        log.info("s.name="+s.getName());
        log.info("s.age="+s.getAge());
        return "success";
    }
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

public class Student {

    @NotEmpty
    @Length(min=4,message="{stu.name}")
    private String name;
    @Min(value=18,message="{stu.age}")
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "toString  -  name="+name+";age="+age;
    }
    
}

需要開啟注解 <mvc:annotation-driven/>才能啟用驗證。否則@valid不管用。

如果要使用錯誤提示的國際化消息,如stu.name為properties文件中的鍵值對
@Length(min
=4,message="{stu.name}")

則需要在dispatcher-servlet.xml中配置

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
            <property name="basename" value="classpath:validmessages"/> 
            <property name="fileEncodings" value="utf-8"/>  
            <property name="cacheSeconds" value="120"/>  
</bean>   
    
    <!-- 以下 validator  ConversionService 在使用 mvc:annotation-driven 會 自動注冊-->  
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
        <!-- 如果不加默認到 使用classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="messageSource" />
    </bean> 
    
    <mvc:annotation-driven validator="validator"/>


在src/main/resources下放入validmessages.properties即可。

 

上面的配置設置了自定義validator,使用messageSource為錯誤消息提示資源文件。

 

validmessages.properties內容為

stu.name=\u540D\u79F0\u7684\u957F\u5EA6\u4E0D\u80FD\u5C0F\u4E8E{min}\u554A!
stu.age=\u5E74\u9F84\u5FC5\u987B\u5927\u4E8E{value}\u5C81\u554A!

 

可以通過{value} {min} {max}等引用注解里的值。

 

當名稱長度小於4  age小於18 輸出:

名稱的長度不能小於4啊!
age年齡必須大於18歲啊!

 

 

本次測試的dispatcher-servlet.xml為

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
 xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="  
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
     http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    ">  
   
   
   <context:component-scan base-package="com.upper"/>
   
    <!-- freemarker的配置 -->  
    <bean id="freemarkerConfigurer"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="/WEB-INF/views/" />  
        <property name="defaultEncoding" value="GBK" />  
        <property name="freemarkerSettings">  
            <props>  
                <prop key="template_update_delay">0</prop>  
                <prop key="locale">zh_CN</prop>  
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>  
                <prop key="date_format">yyyy-MM-dd</prop>  
                <prop key="number_format">#.##</prop>  
                <!--  <prop key="auto_import">c_index.tpl as p</prop> -->
            </props>  
        </property>  
    </bean>  
    <!-- FreeMarker視圖解析 如返回userinfo。。在這里配置后綴名ftl和視圖解析器。。 -->  
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="viewClass"  
            value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />  
        <property name="suffix" value=".ftl" />  
        <property name="contentType" value="text/html;charset=GBK" />  
        <property name="exposeRequestAttributes" value="true" />  
        <property name="exposeSessionAttributes" value="true" />  
        <property name="exposeSpringMacroHelpers" value="true" />  
        <property name="requestContextAttribute" value="rc" />  
        <property name="allowSessionOverride" value="true"/>  
    </bean> 
    
    
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
            <property name="basename" value="classpath:validmessages"/>  
            <property name="fileEncodings" value="utf-8"/>  
            <property name="cacheSeconds" value="120"/>  
    </bean>   
    
    <!-- 以下 validator  ConversionService 在使用 mvc:annotation-driven 會 自動注冊-->  
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- 如果不加默認到 使用classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="messageSource" />
    </bean> 
    
    <mvc:annotation-driven validator="validator"/>
</beans>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM