利用Hibernate Validator实现ssm的数据校验

你会发现你只要写一个新的东西,或者想用ssm框架新的功能时,一般都会进行下面两步,导入需要的jar包和写配置文件,当然利用Hibernate Validator实现ssm的数据校验也不例外。
1、需要的jar包(注意各个jar之间可能存在版本不兼容)
hibernate-validator-5.0.0.CR2.jar classmate-0.8.0.jar jboss-logging-3.1.1.GA.jar
validation-api-1.1.0.CR1.jar hibernate-validator-annotation-processor-5.0.0.CR2.jar
链接:https://pan.baidu.com/s/1Ms0Frr4ZgSy6UJftozxkvA
提取码:tqjq
2、配置文件
我相信你如果学这个那么你的其它的配置文件一定写好了,那我将springmvc的配置文件写给大家,大家可以进行参考

<?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:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
						http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        				http://www.springframework.org/schema/mvc 
        				http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       					http://www.springframework.org/schema/context 
       					http://www.springframework.org/schema/context/spring-context-3.2.xsd
       					http://www.springframework.org/schema/task
       					http://www.springframework.org/schema/task/spring-task-3.2.xsd">
	<!-- 将控制器所在包 加入IOC容器 -->
	<context:component-scan base-package="org.library.controller,org.library.service.impl"></context:component-scan>
	
	<!-- 配置视图解析器 -->
	<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/views/pages/"></property>
			<property name="suffix" value=".jsp"></property>
			<property name="order" value="2"></property>
	</bean>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	 	 <property name="viewNames" value="customer*"/>
		 <property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
		<property name="order" value="1"></property>
	</bean>
	
	
	    <!-- 释放静态资源 -->
		<mvc:resources location="/static/js/" mapping="/static/js/**"/>
		<mvc:resources location="/static/img/" mapping="/static/img/**"/>
		<mvc:resources location="/static/i/" mapping="/static/i/**"/>
		<mvc:resources location="/static/fonts/" mapping="/static/font/**"/>
		<mvc:resources location="/static/css/" mapping="/static/css/**"/>
		
       					
						*<!-- 表单验证框架 -->   <!-- 配置开启注解 协调资源-->   <!-- 这俩个配置文件必须写切记-->
						**<!-- 表单验证框架 -->
						   <bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
           				   <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
     					   </bean> 
					    
					    <!-- 配置开启注解 协调资源-->
						<mvc:annotation-driven validator="myvalidator"/>
						<mvc:default-servlet-handler/>
						<!-- 俩个都写的话没有tequestmapping直接交给setvert处理 -->**
						
						
						<!-- 配置json注释 -->
       					<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
       					<property name="messageConverters">
       						<list>
       						<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
       						<property name="supportedMediaTypes">
       						<list>
       							<value>text/html;charset=utf-8</value>
       						</list>
       						</property>
       						</bean>
       						<bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
       						<property name="supportedMediaTypes">
       						<list>
       							<value>text/plain;charset=utf-8</value>
       							<value>application/json;charset=utf-8</value>
       						</list>
       						</property>
       						</bean>
       						</list>
       					</property>
       					</bean>
       					

</beans>

既然进行数据校验,那么我们以注册老师为例进行这个功能的详细的讲解
2、实体类
就是在你的实体的前边进行数据校验,把你要想的格式卸载属性的前边即可。关于注解使用你可以看下面的这篇博客:https://www.cnblogs.com/myitmylife/p/3617084.html

package org.library.entity;

import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;

public class logintest {
	
	@NotBlank(message="姓名不能为空")
	public String teaname;
	@NotBlank(message="密码不能为空")
	public String teapassword;
	@Pattern(regexp="[男女]",message="只能为男或者女,且不能为空")
	public String teasex;
	@NotBlank(message="电话不能为空")
	public String teaphone;
	@NotBlank(message="邮箱不能为空")
	@Email(message="邮箱格式不正确")
	public String teaemail;
	@NotBlank(message="电话不能为空")
	public String teaschoolname;
	public String getTeaname() {
		return teaname;
	}
	public void setTeaname(String teaname) {
		this.teaname = teaname;
	}
	public String getTeapassword() {
		return teapassword;
	}
	public void setTeapassword(String teapassword) {
		this.teapassword = teapassword;
	}
	public String getTeasex() {
		return teasex;
	}
	public void setTeasex(String teasex) {
		this.teasex = teasex;
	}
	public String getTeaphone() {
		return teaphone;
	}
	public void setTeaphone(String teaphone) {
		this.teaphone = teaphone;
	}
	public String getTeaemail() {
		return teaemail;
	}
	public void setTeaemail(String teaemail) {
		this.teaemail = teaemail;
	}
	public String getTeaschoolname() {
		return teaschoolname;
	}
	public void setTeaschoolname(String teaschoolname) {
		this.teaschoolname = teaschoolname;
	}
	
	

}

3、controller实现

package org.library.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.library.entity.logintest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("logintestcontroller")
public class logintestcontroller {
	
	@RequestMapping("test")
	public ModelAndView test(@Valid logintest ls,BindingResult result) {//indingResult result就是将logintest ls错误的信息放在request中
		System.out.println("test");
		//实现将错误的信息放在map中返回前台,对于下面的使用方法  不会的建议各自的进行百度学习
		Map< String, Object> map=new HashMap<String, Object>();
		List<FieldError> errors=result.getFieldErrors();
		if(result.hasErrors()) {
			for(FieldError fielderror:errors) {
				map.put(fielderror.getField(), fielderror.getDefaultMessage());			
			}	
			return new ModelAndView("logintest",map);
		}else {
			return new ModelAndView("success");
		}
	}
	
	

}

4、前台的代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 <base href="<%=basePath %>" />
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加教师数据</title>
 
</head>
 
<body>


    <center>
        <h3>添加教师</h3>
         
            <form action="logintestcontroller/test" method="post" class="form-horizontal">
            <div class="table-responsive">
            <table width="500" class="table" >
                <tr>
                     
                    <td align="right">姓名:</td>
                    <td><input type="text" name="teaname"></td>
                    <td style=" color:#CC3300">${teaname}</td> 
                </tr>
                <tr>
                     
                    <td align="right">登录密码: </td>
                    <td><input type="password" name="teapassword" id="inputPassword3" ></td>
                    <td style=" color:#CC3300">${teapassword}</td>
                     
                </tr>
                <tr>
                    <td align="right">性别:</td>
                    <td><input type="text" name="teasex"></td>
                    <td style=" color:#CC3300">${teasex}</td>
                </tr>
                <tr>
                    <td align="right">电话:</td>
                    <td><input type="text" name="teaphone"></td>
                    <td style=" color:#CC3300">${teaphone}</td>
                </tr>
                <tr>
                    <td align="right">邮箱:</td>
                    <td><input type="text" name="teaemail"></td>
                    <td style=" color:#CC3300">${teaemail}</td>
                </tr>
                <tr>
                    <td align="right">学校名称:</td>
                    <td><input type="text" name="teaschoolname"></td>
                    <td style=" color:#CC3300">${teaschoolname}</td>
                </tr>
              
 
            </table>
            </div>
            <input type="submit" value="确认添加" class="btn btn-default">
 
            </form>
         
    </center>
</body>
</html>

你没有进行了解Hibernate Validator进行数据校验的话,本人不建议,建议了解Hibernate Validator的工作流程,在进行Hibernate Validator的学习。
对此我也给大家提供一些学习资料,对于ssm学习建议大家到腾讯课堂搜索颜群老师,他对于javaweb讲的比较多,而且比较实用。

发布了33 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/baidu_38978508/article/details/90346263