Spring 3.0擁有自己獨立的數據校驗框架,同時支持JSR 303標準的校驗框架。
JSR 303是Java爲Bean數據合法性校驗所提供的標準框架,它已經包含在Java EE 6.0中。JSR 303通過在Bean屬性上標註類似於@NotNull、@Max等標準的註解指定校驗規則,並通過標準的驗證接口對Bean進行驗證。
可以通過http://jcp.org/en/jsr/detail?id=303瞭解JSR 303的詳細內容。
使用到的註解
使用到的jar包
1:首先
在web.xml中 配置 spring.xml 文件和 springmvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置spring.xml 文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解碼過濾器 -->
<filter>
<filter-name>utf</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>utf</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加載 springmvc 文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2.springmvc.xml 中加上
<context:component-scan base-package="包名"></context:component-scan>
spring.xml裏可以什麼都沒有,但是必須要寫。
首先 ,驗證分爲 2種。
1:聲明式驗證
2:編程式驗證
聲明式驗證 :
直接在 entity類,需要驗證的字段上面加對應的註解。
例
@NotEmpty(message="錯誤消息")
private String userName;
@Pattern(regexp = "\\d{6}",message="錯誤消息")
private String password;
編程式驗證:
首先只要,spring可以自動給形參的變量對象進行實例化,如果想對該對象的屬性進行校驗,那麼在該對象之前 要加上 @Valid
如
@RequestMapping("/映射url")
public String verify(@Valid Register regis,BindingResult binding){
//編程式驗證 如果密碼不同 增加一個異常
if(regis.getAgPassword()==null||!regis.getPassword().equals(regis.getAgPassword())){
binding.addError(new FieldError("register", "agPassword", message));
}
//如果 有錯誤 返回原頁
if(binding.hasErrors()){
return "原來頁面用於顯示驗證消息";
}
return "成功頁面 ";
}
jsp頁面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>spring verify</title>
</head>
<body>
<%--<a href="${pageContext.request.contextPath}/verify!I18n?request_locale=zh_CN"><s:property value="%{getText('chinese')}"/></a>
<a href="${pageContext.request.contextPath}/verify!I18n?request_locale=en_US"><s:property value="%{getText('english')}"/></a>
--%><table>
<form action="${pageContext.request.contextPath}/verify.action" method="post" enctype="multipart/form-data">
<tr><td>姓名:</td><td><input type="text" name="userName"/></td><td><font color="red"><form:errors path="register.userName"></form:errors></font></td></tr>
<tr><td><input type="submit" value="提交"/></td></tr>
</form>
</table>
</body>
</html>
<form:errors path="register.userName"></form:errors> 用於接收 校驗消息
path對應是對象名.屬性名。 對象名小寫。
接收消息如果做國際化
在spring.xml中 加上
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="/lg"></property>
</bean>
其中value值對應的就是國際化資源文件的前綴名。
在springmvc.xml文件中配置
<!-- springmvc默認的驗證 就是實例化了 一個LocalValidatorFactoryBean的實例 其中沒有實現國際化
手工創建一個該類的實例 並且注入 messageSouce 才能國際化
-->
<bean id="factoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
ref引入對應加載
ResourceBundleMessageSource的實例。
加入消息轉換器(必須)
<mvc:annotation-driven validator="factoryBean"></mvc:annotation-driven>
validator引入
LocalValidatorFactoryBean的實例
jsp頁面中 顯示錯誤驗證消息使用:
<%@taglib uri="http://www.springframework.org/tags" prefix="s"%>
<s:message code="資源文件的key">
entity類使用 @NotEmpty(message="{unull}") private String userName; @Pattern(regexp = "\\d{6}",message="{sixpassword}") private String password;
使用{key值} 來獲取資源文件中對應的value值
編程驗證裏的國際化
@RequestMapping("/映射url")
public String verify(@Valid Register regis,BindingResult binding ,Locale locale){
//編程式驗證 如果密碼不同 增加一個異常
if(regis.getAgPassword()==null||!regis.getPassword().equals(regis.getAgPassword())){
//獲取 當前國際化的對應key
String message= source.getMessage("notpassword", null, locale);
binding.addError(new FieldError("register", "agPassword", message));
}
//如果 有錯誤 返回原頁
if(binding.hasErrors()){
return "原來頁面用於顯示驗證消息";
}
return "成功頁面 ";
}