jeesite学习笔记——使用Ajax查重

1、效果:

截图:

jeesite学习笔记——使用Ajax查重_第1张图片

在添加信息时,实时查重,如果重复,就不能提交表单!!

2、代码展示:

2.0由于邮箱、手机号、银行卡号都在一个页面中查重,所以共用一个验证传值变量名

//这是controller文件
//checkRepeat邮箱、手机号、银行卡号查重
@ResponseBody  
@RequiresPermissions("gsmis:expert:edit")
@RequestMapping(value = "checkRepeat")
public String checkRepeat(String checkString) {
	Expert expert = new Expert();
	String result = "0";
	//获取expert现有数据
	List list = expertService.findList(expert);
	//遍历查重,一旦重复就break跳出循环,直接返回
	for(Expert e:list) {
		if(checkString.equals(e.getEmail())) {						//邮箱查重
			result = "1";
			break;
		}else if(checkString.equals(e.getPhone())) {				//手机号查重
			result = "2";
			break;
		}else if(checkString.equals(e.getBankCardNumber())) {		//银行卡号查重
			result = "3";
			break;
		}
	}
	return result;
}

2.1邮箱实时查重:(附带正则验证)

//这是jsp文件
//全局变量,用于传送需要查重的邮箱、手机号、银行卡号值
var checkString = "";
//邮箱验证
function checkEmail() {
	//邮箱的正则表达式
	var emailReg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
	//实时获取邮箱
	var emailNew = email.value;
	//标志变量
	var checkResult = true;
	if(emailOld != emailNew && emailNew != null & emailNew != ""){		//判断是否更改
		if(emailReg.test(emailNew)){
			$.ajax({
				async:false,
				type:"post",
				url:"${ctx}/gsmis/expert/checkRepeat?checkString=" + emailNew,
				dataType:'html',
				error : function() {
			        alert('请求失败!请刷新页面重试! ');
			    },
			    success : function(data) {
			    	if (data == 0) {
			    		email_notice.innerHTML = '邮箱验证通过!';
						email_notice.style.color = 'green';
					}
					else {
						email_notice.innerHTML = "邮箱已经被占用!";
						email_notice.style.color = 'red';
						checkResult = false;
					}
			    }
			});
		}else {
			email_notice.innerHTML = '邮箱验证未通过,请重新输入!';
			email_notice.style.color = 'red';
			checkResult = false;
		}
	}else if(emailNew != null & emailNew != ""){
		email_notice.innerHTML = '邮箱验证通过!';
		email_notice.style.color = 'green';
		}else{
			email_notice.innerHTML = '请输入邮箱!';
			email_notice.style.color = 'red';
			checkResult = false;
		}
	return checkResult;
}

2.2手机号实时查重:(附带正则验证)

//这是jsp文件
//手机号码验证
function checkPhone() {
	//手机号的正则表达式
	var phoneReg = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
	//实时获取手机号
	var phoneNew = phone.value;
	var checkResult = true;
	if(phoneOld != phoneNew && phoneNew != null && phoneNew != ""){
		if(phoneReg.test(phoneNew)){
			$.ajax({
				async:false,
				type:"post",
				url:"${ctx}/gsmis/expert/checkRepeat?checkString=" + phoneNew,
				dataType:'html',
				error : function() {
			        alert('请求失败!请刷新页面重试! ');
			    },
			    success : function(data) {
			    	if (data == 0) {
			    		phone_notice.innerHTML = '手机号码验证通过!';
			    		phone_notice.style.color = 'green';
					}
					else {
						phone_notice.innerHTML = "手机号码已经被占用!";
						phone_notice.style.color = 'red';
						checkResult = false;
					}
			    }
			});
		}else {
			phone_notice.innerHTML = '手机号码验证未通过!';
			phone_notice.style.color = 'red';
			checkResult = false;
		}
	}else if(phoneNew != null && phoneNew != ""){
		phone_notice.innerHTML = '手机号码验证通过!';
   		phone_notice.style.color = 'green';
		}else{
			phone_notice.innerHTML = '请输入手机号码!';
			phone_notice.style.color = 'red';
			checkResult = false;
		}
	return checkResult;
}

2.3银行卡号实时查重:(附带Luhm验证)

//这是jsp文件
//银行卡号验证
function checkBankCardNumber() {
	//实时获取银行卡号
	var bankCardNumberNew = bankCardNumber.value;
	if(bankCardNumberOld != bankCardNumberNew && bankCardNumberNew != null && bankCardNumberNew != ""){
		//长度校验
		if(bankCardNumberNew == "" || bankCardNumberNew.length < 16 || bankCardNumberNew.length > 19) {
			bankCardNumber_notice.innerHTML = "银行卡号位数必须在16~19之间,请完整输入银行卡号!";
			bankCardNumber_notice.style.color = 'red';
			return false;
		}
		//开头6位校验
		var strBin="10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";    
		if(strBin.indexOf(bankCardNumberNew.substring(0, 2)) == -1) {
			bankCardNumber_notice.innerHTML = "银行卡号开头6位不符合规范,请检查后重新输入!";
			bankCardNumber_notice.style.color = 'red';
			return false;
		}
		//全数字校验
		var num = /^\d*$/;
		if( !num.exec(bankCardNumberNew)) {
			bankCardNumber_notice.innerHTML = "银行卡号必须全为数字,请检查后重新输入!";
			bankCardNumber_notice.style.color = 'red';
			return false;
		}
		//Luhm验证
		var lastNum = bankCardNumberNew.substr(bankCardNumberNew.length-1, 1);//取出最后一位(与luhm进行比较)
		var first15Num = bankCardNumberNew.substr(0, bankCardNumberNew.length-1);//前15或18位
		var newArr = new Array();
		for(var i = first15Num.length-1; i > -1; i --){	//前15或18位倒序存进数组
			newArr.push(first15Num.substr(i, 1));
		}
		var arrJiShu = new Array();					//奇数位*2的积 <9
		var arrJiShu2 = new Array();				//奇数位*2的积 >9
		var arrOuShu = new Array();					//偶数位数组
		for(var j = 0; j < newArr.length; j++){
			if( (j+1)%2 == 1) {							//奇数位
				if(parseInt(newArr[j]) * 2 < 9)
					arrJiShu.push(parseInt(newArr[j]) * 2);
				else
					arrJiShu2.push(parseInt(newArr[j]) * 2);
			}else									//偶数位
				arrOuShu.push(newArr[j]);
		}
		var jishu_child1 = new Array();//奇数位*2 >9 的分割之后的数组个位数
		var jishu_child2 = new Array();//奇数位*2 >9 的分割之后的数组十位数
		for(var h = 0; h < arrJiShu2.length; h++) {
		    jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
		    jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
		}        
		var sumJiShu = 0; //奇数位*2 < 9 的数组之和
		var sumOuShu = 0; //偶数位数组之和
		var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
		var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
		var sumTotal = 0;
		for(var m = 0; m

2.4、由于Ajax传值时会出现中文传值乱码,需要先转译为内码,在进行传值查重。

所以先在jsp中转码,然后在控制台controller中验证

//这是jsp文件
function checkMajorName() {
	var majorNew = major.value;
	var checkResult = true;
	var majorName = "";
	if(majorOld != majorNew && majorNew != null && majorNew != ""){
		if(majorNew){
			//由于Ajax中文传值会乱码,所以需要先翻译成utf-8内码,然后在控制台转成中文,这种转译需要连URL一起转译
			var url = "${ctx}/gsmis/major/checkMajorName?majorName=" + majorNew;
			url = encodeURI(encodeURI(url));
			$.ajax({
				async:false,
				type:"post",
				url:url,
				contentType:"application/x-www-form-urlencoded; charset=utf-8",
				dataType:"json",
				error : function() {
			        alert('请求失败!请刷新页面重试! ');
			    },
			    success : function(data) {
			    	if (data == 0) {
			    		major_notice.innerHTML = "验证通过!";
			    		major_notice.style.color = 'green';
					}else{
						major_notice.innerHTML = "专业已经存在!";
						major_notice.style.color = 'red';
						checkResult = false;
					}
			    }
			});
		}
	}else if(majorNew != null && majorNew != ""){
		major_notice.innerHTML = "验证通过!";
   		major_notice.style.color = 'green';
		}else{
			major_notice.innerHTML = "请输入专业信息!";
			major_notice.style.color = 'red';
			checkResult = false;
		}
	return checkResult;
}
//这是controller文件
//手动添加major查重
@ResponseBody
@RequiresPermissions("gsmis:major:edit")
@RequestMapping(value = "checkMajorName")
public String checkMajorName(String majorName) throws UnsupportedEncodingException{
	String result = "0";
	majorName = URLDecoder.decode(majorName,"UTF-8"); 
	//---由于数据中对major的xml中对name是模糊匹配的,为防止列表数据过多,先进行筛选,经过模糊匹配后再进行查重
	Major majorMatch = new Major();
	majorMatch.setName(majorName);
	List list = majorService.findList(majorMatch);
	for(Major m:list) {
		if(majorName.equals(m.getName())) {
			result = "1";
			break;
		}
	}
	return result;
}

3、上面在手动添加文件时查重,下面附带导入文件的查重

3.1、导入不需要加密的文件的查重

3.1.1、controller层的导入方法

@RequiresPermissions("gsmis:research:edit")
@RequestMapping(value = "import", method=RequestMethod.POST)
public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
	if(Global.isDemoMode()){
		addMessage(redirectAttributes, "演示模式,不允许操作!");
		return "redirect:" + adminPath + "/gsmis/research/?repage";
	}
	try {
		int successNum = 0;
		int failureNum = 0;
		StringBuilder failureMsg = new StringBuilder();
		ImportExcel ei = new ImportExcel(file, 1, 0);
		List list = ei.getDataList(Research.class);
		for (Research rNew : list){                
			try{
				if(researchService.importCheckRepeat(rNew)) {
					researchService.save(rNew);
					successNum++;
				}else {
					failureMsg.append("
研究方向: " + rNew.getName()+ "
			
原因: 数据重复,导入失败!"); failureNum++; } }catch(ConstraintViolationException ex){ failureMsg.append("
研究方向: " + rNew.getName()+" 导入失败:"); List messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": "); //告诉你出错原因 for (String message : messageList){ failureMsg.append(message+"; "); failureNum++; } }catch (Exception ex) { failureMsg.append("
研究方向: "+rNew.getName()+" 导入失败:"+ex.getMessage()); } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条信息,导入信息如下:"); } addMessage(redirectAttributes, "已成功导入 "+successNum+" 条信息"+failureMsg); } catch (Exception e) { addMessage(redirectAttributes, "导入研究方向信息失败!失败信息:"+e.getMessage()); } return "redirect:" + adminPath + "/gsmis/research/list?repage"; }

3.1.2、service层的查重方法

//导入数据时的查重
public boolean importCheckRepeat(Research research) {
	boolean checkRepeat = true;									//查重结果,true表示没有重复,false表示重复
	//---由于数据中对research的xml中对name是模糊匹配的,为防止列表数据过多,先进行筛选,经过模糊匹配后再进行查重
	Research researchMatch = new Research();
	researchMatch.setName(research.getName());
	List researchMatchList = findList(researchMatch);
	if(researchMatchList != null && researchMatchList.size() > 0) {
		for(Research rOld : researchMatchList) {				//先遍历researchOldList数据库已有的数据
			if(research.getName().equals(rOld.getName())) {
				checkRepeat = false;
				return checkRepeat;								//一旦找到重复的,就返回false
			}
		}
	}			
	return checkRepeat;
}

3.2、导入需要加密的文件的查重

3.2.1、controller层方法

@RequiresPermissions("gsmis:expert:edit")
@RequestMapping(value = "import", method=RequestMethod.POST)
public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
	if(Global.isDemoMode()){
		addMessage(redirectAttributes, "演示模式,不允许操作!");
		return "redirect:" + adminPath + "/gsmis/expert/?repage";
	}
	try {
		int successNum = 0;
		int failureNum = 0;
		//定义failureMsg失败信息的字符串
		StringBuilder failureMsg = new StringBuilder();
		//定义文件接收对象,存储导入的文件信息
		ImportExcel ei = new ImportExcel(file, 1, 0);
		//将导入的文件的每一条数据取出放入链表
		List list = ei.getDataList(Expert.class);
		Major major = new Major();
		//遍历链表中的每一条数据,相当于每一个eNew就是一条expert数据,这条数据是未经加密的
		for (Expert eNew : list){
			try{	
				//把专家的专业转化为专业表对应的id
				major.setName(eNew.getMajor());
				major = majorService.findByName(major);
				eNew.setMajor(major.getId());
				//将导入的专家类型转换为字典的值
				String expertType = DictUtils.getDictValue(eNew.getExpertType(), "expertType", "");
				eNew.setExpertType(expertType);
				//导入查重,如果重复,就不保存
				if(expertService.importCheckRepeat(eNew)) {
					expertService.save(eNew);
					successNum++;
				}else {
					failureMsg.append("
姓名: " + eNew.getExpertName()+ "
				
原因: 数据重复,导入失败!"); failureNum++; } }catch(ConstraintViolationException ex){ failureMsg.append("
姓名: " + eNew.getExpertName()+" 导入失败:"); List messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": "); for (String message : messageList){ failureMsg.append(message+"; "); failureNum++; } }catch (Exception ex) { failureMsg.append("
姓名: " + eNew.getExpertName()+" 导入失败:" + ex.getMessage()); } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条信息,导入信息如下:"); } addMessage(redirectAttributes, "已成功导入 "+successNum+" 条信息"+failureMsg); } catch (Exception e) { addMessage(redirectAttributes, "导入专家信息失败!失败信息:"+e.getMessage()); } return "redirect:" + adminPath + "/gsmis/expert/list?repage"; }

3.2.2service层加密查重

//导入数据时的查重
public boolean importCheckRepeat(Expert expert) {				//这里的expert是导入文件的内容,是未加密的
	boolean checkRepeat = true;									//查重结果,true表示没有重复,false表示重复
	Expert expertOld = new Expert();
	expertOld.setExpertName(expert.getExpertName());
	expertOld.setEmail(expert.getEmail());
	expertOld.setPhone(expert.getPhone());
	expertOld.setBankCardNumber(expert.getBankCardNumber());
	encryption(expertOld);
	List expertOldList = findList(expertOld);			//这里的expertOld是数据库已有的内容,是已经加密的
	if(expertOldList != null && expertOldList.size() > 0) {
        //如果数据库中存在一条邮箱、手机号、银行卡号都相同的数据,就说明重复,返回false
		checkRepeat = false;
	}
	return checkRepeat;
}

//加密单条数据
public Expert encryption(Expert expert) {
	//对专家姓名、手机号、邮箱、银行卡号进行AES加密
	expert.setExpertName(Cryptos.aesEncrypt(expert.getExpertName()));
	expert.setEmail(Cryptos.aesEncrypt(expert.getEmail()));
	expert.setPhone(Cryptos.aesEncrypt(expert.getPhone()));
	expert.setBankCardNumber(Cryptos.aesEncrypt(expert.getBankCardNumber()));
	return expert;
}

//解密单条数据
public Expert decryption(Expert expert) {
	expert.setExpertName(Cryptos.aesDecrypt(expert.getExpertName()));
	expert.setEmail(Cryptos.aesDecrypt(expert.getEmail()));
	expert.setPhone(Cryptos.aesDecrypt(expert.getPhone()));
	expert.setBankCardNumber(Cryptos.aesDecrypt(expert.getBankCardNumber()));
	return expert;
}

 

 

/ *小白一个,仅留做自我学习记忆,时常修改,有不对不全之处还望不吝赐教!* /

你可能感兴趣的:(jeesite)