表單引入 JSR303 後臺驗證

1 . 先看效果



2 . 引入相關jar包



3 . 配置springmvc.xml(不是web.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


	<!-- <context:component-scan base-package="package_name"/> -->
	<context:component-scan base-package="org.lee" />
	
	<mvc:annotation-driven /> 
	<!-- 註解實現日記記錄 -->
	<aop:aspectj-autoproxy />


	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />   <!-- path before request -->
		<property name="suffix" value=".jsp" />  <!-- suffix -->
	</bean>




	<!-- 國際化 -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames" value="i18n.message"></property>

		<property name="defaultEncoding" value="UTF-8" />
	</bean>

	<!-- 基於Session的國際化配置 -->
	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>

	<!-- 動態語言切換 -->
	<bean id="localeChangeInterceptor"
		class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
		<property name="paramName" value="locale" />
	</bean>


	<!-- 靜態資源訪問 -->
	<mvc:resources location="/My97DatePicker/" mapping="/My97DatePicker/**" />
	<mvc:resources location="/static/lib/" mapping="/static/lib/**" />
	<mvc:resources location="/static/css/" mapping="/static/css/**" />
	<mvc:resources location="/static/assets/" mapping="/static/assets/**" />
	<mvc:resources location="/static/docs/" mapping="/static/docs/**" />
	<mvc:resources location="/static/docs/js/" mapping="/static/docs/js/**" />
	<mvc:resources location="/static/docs/assets/js/" mapping="/static/docs/assets/js/**" />
	<mvc:resources location="/static/js/" mapping="/static/js/**" />
	<mvc:resources location="/static/js/jqprint/" mapping="/static/js/jqprint/**" />
	<mvc:resources location="/static/bootstrap-3.3.5-dist/css/"
		mapping="/static/bootstrap-3.3.5-dist/css/**" />
	<mvc:resources location="/static/bootstrap-3.3.5-dist/js/"
		mapping="/static/bootstrap-3.3.5-dist/js/**" />
	<mvc:resources location="/static/bootstrap-3.3.5-dist/fonts/"
		mapping="/static/bootstrap-3.3.5-dist/fonts/**" />

	<!-- Bootstrap-Multiselect -->
	<mvc:resources location="/static/bootstrap-multiselect-0.9.13/dist/css/"
		mapping="/static/bootstrap-multiselect-0.9.13/dist/css/**" />
	<mvc:resources location="/static/bootstrap-multiselect-0.9.13/dist/js/"
		mapping="/static/bootstrap-multiselect-0.9.13/dist/js/**" />
	<mvc:resources location="/static/bootstrap-multiselect-0.9.13/dist/less/"
		mapping="/static/bootstrap-multiselect-0.9.13/dist/less/**" />

	<mvc:resources location="/static/bootstrap-multiselect-0.9.13/docs/css/"
		mapping="/static/bootstrap-multiselect-0.9.13/docs/css/**" />
	<mvc:resources location="/static/bootstrap-multiselect-0.9.13/docs/js/"
		mapping="/static/bootstrap-multiselect-0.9.13/docs/js/**" />
	<mvc:resources location="/static/bootstrap-multiselect-0.9.13/docs/less/"
		mapping="/static/bootstrap-multiselect-0.9.13/docs/less/**" />


	<!-- JSR 303 Validator -->
	<bean id="validator"
		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
		<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
		<property name="validationMessageSource" ref="messageSource" />
	</bean>
	<mvc:annotation-driven validator="validator" />



	<!-- 數據庫配置 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- MySQL數據庫配置 -->
		<property name="url"
			value="jdbc:mysql://localhost:3306/apj?useUnicode=true&characterEncoding=utf-8" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
	</bean>


	<!-- 配置jdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
		abstract="false" lazy-init="false" autowire="default">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
	</bean>


	<!--配置Hibernate -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="org.lee.model"></property>
		<property name="hibernateProperties">
			<props>
				<!-- 方言 -->
				<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<!-- 控制檯顯示SQL -->
				<prop key="show_sql">true</prop>
				<!-- 自動更新表結構 -->
				<prop key="hbm2ddl.auto">update</prop>

			</props>
		</property>
	</bean>
	
	
	<!--配置Hibernate事務 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" />



	<!-- 考題管理的ajax相關配置 -->

	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJackson2HttpMessageConverter" />
			</list>
		</property>
	</bean>
	<bean id="mappingJackson2HttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
				<value>text/html;charset=UTF-8</value>
				<value>text/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>



	<!-- 上傳配置 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />


	<!-- 登錄權限 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**" />
			<mvc:exclude-mapping path="/login" />
			<mvc:exclude-mapping path="/logout" />
			<mvc:exclude-mapping path="/static/**" />
			<bean class="org.lee.Interceptor.LoginInterceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>


</beans>



4 . 驗證條件寫在model裏面(下面的@size,@pattern,@Email是驗證條件,而@Id,@Column是配置多對一的東西,現在不用管他們)

import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

@Entity
@Table(name = "exam_user")
public class UserHibernate implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7484295368856997107L;

	@Id
	@Size(min = 1, max = 15, message = "ID爲1-15個字符")
	@Column(name = "user_id", nullable = false)
	private String  userId;

	@Column(name = "user_name", nullable = false)
	@Size(min = 1, max = 15, message = "姓名爲1-15個字符")
	private String user_name;

	@Column(name = "password", nullable = false)
	@Pattern(regexp = "^[0-9a-zA-Z_]{4,20}$", message = "請輸入4-20個字符的密碼")
	private String password;

	@Email
	@Column(name = "email", nullable = true)
	private String email;

	@Column(name = "gender", nullable = false)
	@Pattern(regexp = "^[0]|[1]$", message = "0:男;1:女")
	private String gender;

	@Column(name = "birthday", nullable = false)
	@Pattern(regexp = "^((((19|20)\\d{2})-(0?(1|[3-9])|1[012])-(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2})-(0?[13578]|1[02])-31)|(((19|20)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))-0?2-29))$", message = "請輸入合法的日期格式,例如:2017-09-09")
	private String birthday;

	@Column(name = "tel", nullable = true)
	private String tel;

	@Column(name = "address", nullable = true)
	private String address;

	@Column(name = "last_lock_time", nullable = true)
	private Date lastLockTime;

	@Column(name = "login_fail_count", nullable = true)
	private Integer loginFailCount;

	

	@OneToMany(mappedBy = "userHibernate")
	private Set<ExamUserRole> examUserRole;
	
	@OneToMany(mappedBy = "userHibernate")
	private Set<ExamUserSubject> examUserSubject;

	
	
	
	public UserHibernate() {
		super();
	}


	public String getUserId() {
		return userId;
	}


	public void setUserId(String userId) {
		this.userId = userId;
	}


	public String getUser_name() {
		return user_name;
	}

	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

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

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Date getLastLockTime() {
		return lastLockTime;
	}

	public void setLastLockTime(Date lastLockTime) {
		this.lastLockTime = lastLockTime;
	}

	public Integer getLoginFailCount() {
		return loginFailCount;
	}

	public void setLoginFailCount(Integer loginFailCount) {
		this.loginFailCount = loginFailCount;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public Set<ExamUserRole> getExamUserRole() {
		return examUserRole;
	}
	
	


	public Set<ExamUserSubject> getExamUserSubject() {
		return examUserSubject;
	}


	public void setExamUserSubject(Set<ExamUserSubject> examUserSubject) {
		this.examUserSubject = examUserSubject;
	}


	public void setExamUserRole(Set<ExamUserRole> examUserRole) {
		this.examUserRole = examUserRole;
	}
	

}


5 .   然後回到UserControler處理表單


5 . 錯誤信息顯示效果如最上面的圖片,驗證不通過就會在表單頁面顯示錯誤信息並停留在本頁面


6 . OK , JSR303後臺驗證已經講解完畢,謝謝您的支持




發佈了56 篇原創文章 · 獲贊 75 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章