1. 程式人生 > >SpringMVC學習(三)

SpringMVC學習(三)

資料校驗

1.匯入jar包

2.配置校驗器,並加入介面卡

3.bean上新增校驗資訊

4.controller上校驗資訊的處理

一:jar包的匯入

二:配置校驗器validator

<!-- 校驗器,配置validator -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
        <property name="validationMessageSource" ref="validationMessageSource"></property>
    </bean>
    
    <!-- 配置validationMessageSource -->
    <bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- 指定校驗資訊的資原始檔的基本檔名稱,不包括字尾,字尾預設是properties -->
        <property name="basenames">
            <list>
                <value>classpath:validationMessageSource</value>
            </list>
        </property>
        <!-- 指定檔案的編碼 -->
        <property name="fileEncodings" value="utf8"></property>
        <!-- 對資原始檔內容快取的時間,單位秒 -->
        <property name="cacheSeconds" value="120"></property>
    </bean>
	<!-- 將校驗器加入介面卡-->
	<mvc:annotation-driven validator="validator"  />

三:在bean上新增校驗資訊

public class user {
	@Size(min=3,max=10,message="{com.name.size}")
    //錯誤資訊可以通過配置檔案,也可以直接在message中直接書寫
	private String username;
	@NotEmpty(message="密碼好像空了")
	private String password;
}

四:controller控制器

public class show2 {
	@RequestMapping(value="/show2")
	public String show2(Model model,@Validated user user,BindingResult result){
            //所校驗的資訊後面需要跟上BindingResult result
		if(result.hasErrors()){
			List<ObjectError> errors = result.getAllErrors();
			for (ObjectError Error : errors) {
				System.out.println(Error);
			}
			model.addAttribute("errors", errors);
			return "jsp/error";
		}
		model.addAttribute("user", user);
		return "jsp/welcome";
	}
}

五:訪問