jquery+jsp+servlet+ajax实现注册功能,ajax校验用户名、验证码等

标签: jquery  servlet  ajax  jsp  验证码

注册样式很大众化

实现了以下功能:

用户名: jQuery实现:1、失去焦点校验输入是否为空及限制字符数然后显示Label;2、获得焦点后隐藏;3、ajax校验是否该用户名是否已存在于数据库

登录密码:1、失去焦点校验输入内容;2、获得焦点隐藏

确认密码:1、校验输入内容;2、校验确认密码是否等于登录密码

email:1、校验输入符合邮件格式;2、获得焦点隐藏label

图形验证码:1、random 生成数字验证码;2、校验输入内容和验证码内容是否相同;3、点击换一张实现更换验证码

立即注册:1、根据鼠标是否在上面实现更换图片效果;2、点击按钮对上面的输入框校验,必须全部符合要求才能实现提交功能

regist.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/regist.css">
<script type="text/javascript" src="js/jquery-1.5.1.js"></script>
<script type="text/javascript" src="js/regist.js"></script>

<title>注册页面</title>
<style>
/*这些在css页面写了没有作用,所以拿到这里,原因未知*/
.errorClass {background:url(img/error.png) no-repeat; color: #f40000; font-size: 10pt; border:1px solid #ffb8b8; background-color: #fef2f2; padding: 8px 8px 8px 35px;}
#divTitle {line-height: 30px; width: 880px; height: 30px; border: 1px solid #d0d0d0; background: url(img/bg_btns.png) repeat-x 0px -132px;}

</style>
</head>
<body>
<br><br><br>
<div id="divBody"  >
<div id="divTitle">
<span id="spanTitle">新用户注册</span>
</div>
<div id="divTable">
<form  method="post" action="RegistServlet" id="registForm">
	<table id="tableForm">
		<tr>
			<td class="tdText">用户名:</td>
			<td class="tdInput">
			<input class="inputClass" type="text" name="loginname" id="loginname">
			</td>
			<td class="tdError">
			<label class="errorClass" id="loginnameError"></label>
			</td>
		</tr>
		<tr>
			<td class="tdText">登陆密码:</td>
			<td ><input class="inputClass" type="password" name="loginpass" id="loginpass"></td>
			<td ><label class="errorClass" id="loginpassError"></label></td>
		</tr>
		<tr>
			<td class="tdText">确认密码:</td>
			<td><input class="inputClass" type="password" name="reloginpass" id="reloginpass"></td>
			<td><label class="errorClass" id="reloginpassError"></label></td>
		</tr>
		<tr>
			<td class="tdText">Email:</td>
			<td><input class="inputClass" type="text" name="email" id="email"></td>
			<td><label class="errorClass" id="emailError"></label></td>
		</tr>
		<tr>
			<td class="tdText">图形验证码:</td>
			<td><input class="inputClass" type="text" name="verifyCode" id="verifyCode"></td>
			<td><label class="errorClass" id="verifyCodeError"></label></td>
		</tr>
		<tr>
			<td ></td>
			<td><div id="divVerifyCode" align="center"><img id="imgVerifyCode" src="VerifyCode"></div></td>
			<td><label><a href="javascript:_hyz()">换一张</a></label></td>
		</tr>
		<tr>
			<td></td>
			<td><input type="image" src="img/regist1.jpg" id="submitBtn" ></td>
			<td></td>
		</tr>
</table>
</form>
</div>
</div>
</body>
</html>
regist.css
@CHARSET "UTF-8";
#divBody {margin-left: 240px; align:center}
#spanTitle {margin-left: 18px; font-weight: 900;}
#divBody {width: 880px; height: 400px; border-left: 1px solid #d0d0d0;border-bottom: 1px solid #d0d0d0;border-right: 1px solid #d0d0d0;}
.tdText {width: 300px; text-align: right;}
.tdInput{width: 250px;}
.tdError {width: 300px;}
#tableForm {line-height: 50px;}
.inputClass {width: 240px; height: 32px; border: 1px solid #7f9db9; line-height: 32px; padding-left: 10px;}
#imgVerifyCode {width: 100px;}
#divVerifyCode {align:center; border: 1px solid #e2e2e2;height:30px;width:80px;}

各输入框的校验实现js

$(function(){
	$(".errorClass").each(function(){
		showError($(this));
	});
	$("#submitBtn").hover(//切换图片
	function(){
		$("#submitBtn").attr("src","img/regist1.jpg")
		},
	function(){
		$("#submitBtn").attr("src","img/regist2.jpg");
	});
	$(".inputClass").focus(function(){//得到焦点隐藏
		var labelId=$(this).attr("id")+"Error";
		$("#"+labelId).text("");
		showError($("#"+labelId));
	});
	$(".inputClass").blur(function(){
		var id=($(this).attr("id"));
		var funName="validate"+id.substring(0,1).toUpperCase()+id.substring(1)+"()";
		eval(funName);
	});
	$("#registForm").submit(function(){
		var bool=true;
		if(!validateLoginname()){bool=false;}
		if(!validateLoginpass()){bool=false;}
		if(!validateReloginpass()){bool=false;}
		if(!validateEmail()){bool=false;}
		if(!validateVerifyCode()){bool=false;}
		return bool;
	})
});
//登录名校验
function validateLoginname(){
	var id="loginname";
	var value=$("#"+id).val();
	if(!value){
		$("#"+id+"Error").text("用户名不能为空");
		showError($("#"+id+"Error"));
		return false;
	}
	if(value.length<3||value.length>10){
		$("#"+id+"Error").text("用户名长度必须在3~10");
		showError($("#"+id+"Error"));
		return false;
	}
	$.ajax({
		url:"NameExistServlet",
		data:{method:"loginName",val:value},
		async:true,
		cache:false,
		type:"post",
		datatype:"json",
		error:function(){
			alert("name error");
		},
		success:function(result){
			if(result){
				$("#"+id+"Error").text("该用户名已存在");
				showError($("#"+id+"Error"));
				return false;
			}
		}
	})
	return true;
}

//登录密码校验
function validateLoginpass(){
	var id="loginpass";
	var value=$("#"+id).val();
	if(!value){
		$("#"+id+"Error").text("登录密码不能为空");
		showError($("#"+id+"Error"));
		return false;
	}
	if(value.length<3||value.length>6){
		$("#"+id+"Error").text("登录密码长度必须在3~6");
		showError($("#"+id+"Error"));
		return false;
	}
	return true;
}
//登录密码确认校验
function validateReloginpass(){
	var id="reloginpass";
	var value=$("#"+id).val();
	if(!value){
		$("#"+id+"Error").text("登录确认密码不能为空");
		showError($("#"+id+"Error"));
		return false;
	}
	if(value.length<3||value.length>6){
		$("#"+id+"Error").text("登录确认密码长度必须在3~6");
		showError($("#"+id+"Error"));
		return false;
	}
	if(value!=$("#loginpass").val()){
		$("#"+id+"Error").text("两次密码不同");
		showError($("#"+id+"Error"));
		return false;
	}
	return true;
}
//Email
function validateEmail(){
	var id="email";
	var value=$("#"+id).val();
	if(!value){
		$("#"+id+"Error").text("Email不能为空");
		showError($("#"+id+"Error"));
		return false;
	}
	if(!/^([a-zA-Z0-9_-])[email protected]([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(value)){
		$("#"+id+"Error").text("Email格式不对");
		showError($("#"+id+"Error"));
		return false;
	}
	return true;
}
//图形验证码
function validateVerifyCode(){
	var id="verifyCode";
	var value=$("#"+id).val();
	if(!value){
		$("#"+id+"Error").text("验证码不能为空");
		showError($("#"+id+"Error"));
		return false;
	}
	if(value.length!=4){
		$("#"+id+"Error").text("验证码长度必须为4");
		showError($("#"+id+"Error"));
		return false;
	}
	$.ajax({
		url:"UserServlet",
		data:{method:"ajaxValidateVerifyCode",verifyCode:value},
		type:"POST",
		dataType:"json",
		async:true,
		cache:false,
		error:function(){
			alert("false");
		},
		success:function(result){
			if(!result){
			$("#"+id+"Error").text("验证码有误");
			showError($("#"+id+"Error"));
			return false;
			}
		}
	});
	return true;
}
function showError(ele){//检测到有毛病,有文字,就显示,,,
	var text=ele.text();
	if(!text){
		ele.css("display","none");
	}else{
		ele.css("display","");
	}
}
//换一张
function _hyz(){
	document.getElementById("imgVerifyCode").src = document  
    .getElementById("imgVerifyCode").src  
    + "?nocache=" + new Date().getTime();  
}
生成验证码的VerifyCodeservlet

package fourkings;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class VerifyCode
 */
@WebServlet("/VerifyCode")
public class VerifyCode extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VerifyCode() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Color getRandColor(int s,int e){
    	Random random = new Random();
    	if(s>255){s=255;}
    	if(e>255){e=255;}
    	int r,g,b;
    	r=s+random.nextInt(e-s);
    	g=s+random.nextInt(e-s);
    	b=s+random.nextInt(e-s);
    	return new Color(r,g,b);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setHeader("Pragma", "No-cache");//设置不缓存图片
		response.setHeader("Cache-Control","No-cache");
		response.setDateHeader("Expires",0);
//指定相应的是图片
		response.setContentType("image/jpeg");
		int width=80,height=30;//验证码宽高
		BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//创建BufferedImage对象
		Graphics g=image.getGraphics();//创建Graphics对象,相当于画笔
		Graphics2D g2d=(Graphics2D)g;//创建Graphics2D对象
		Random random=new Random();
		Font mfont=new Font("楷体",Font.BOLD,16);//字体样式
		g.setColor(getRandColor(200,250));
		g.fillRect(0,0,width,height);//绘制背景
		g.setFont(mfont);//设置字体
		g.setColor(getRandColor(180,200));
		//绘制100条颜色和位置全部随机产生的线条,该线条为2f
		for(int i=0;i<100;i++){
			int x=random.nextInt(width-1);
			int y=random.nextInt(height-1);
			int x1=random.nextInt(6)+1;
			int y1=random.nextInt(12)+1;
			BasicStroke bs =new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);
			Line2D line = new Line2D.Double(x,y,x+x1,y+y1);
			g2d.setStroke(bs);
			g2d.draw(line);
	}
		String sRand="";
		String ctmp="";
		int itmp=0;
		for(int i=0;i<4;i++){
			String [] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
			ctmp=rBase[random.nextInt(4)];
			
			//注释掉的部分是中文验证码。。。太难了,不认识,学别人写的
//			switch(random.nextInt(3)){
//			case 1:
//				itmp=random.nextInt(26)+65;
//				ctmp=String.valueOf((char)itmp);
//				break;
//			case 2:
//				String [] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
//				//生成第一位区码
//				int r1=random.nextInt(3)+11;
//				String str_r1=rBase[r1];
//				//生成第二位区码
//				int r2;
//				if(r1==13){
//					r2=random.nextInt(7);
//				}else{
//					r2=random.nextInt(16);
//				}
//				String str_r2=rBase[r2];
//				//生成第一位位码
//				int r3=random.nextInt(6)+10;
//				String str_r3=rBase[r3];
//				//生成第二位位码
//				int r4;
//				if(r3==10){
//					r4=random.nextInt(15)+1;
//				}else if(r3==15){
//					r4=random.nextInt(15);
//				}else{
//					r4=random.nextInt(16);
//				}
//				String str_r4=rBase[r4];
////				//将生成的区码转换为汉字
////				byte[] bytes=new byte[2];
////				//将生成的区码保存到字节数组的第一个元素中
//				String str_r12=str_r1+str_r2;
////				int tempLow=Integer.parseInt(str_r12,16);
////				bytes[0]=(byte)tempLow;
////				//将生成的位码保存到字节数组的第二个元素中
//				String str_34=str_r3+str_r4;
//				int tempHigh=Integer.parseInt(str_34,16);
////				bytes[1]=(byte)tempHigh;
////				ctmp=new String(bytes);
//				System.out.print(ctmp);
//				break;
//			default:
//				itmp=random.nextInt(10)+48;
//				ctmp=String.valueOf((char)itmp);
//				break;
//			}
			sRand+=ctmp;
			Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
			g.setColor(color);
			//将文字旋转指定角度
			Graphics2D g2d_word=(Graphics2D)g;
			AffineTransform trans=new AffineTransform();
			trans.rotate((10)*3.14/180, 15*i+8, 7);
			//缩放文字
			float scaleSize=random.nextFloat()+0.8f;
			if(scaleSize>1f){scaleSize=1f;}
			trans.scale(scaleSize, scaleSize);
			g2d_word.setTransform(trans);
			g.drawString(ctmp, 15*i+18, 14);
		}
		HttpSession session=request.getSession(true);
		System.out.println(sRand);
		session.setAttribute("randCheckCode", sRand);
		g.dispose();//释放g所占的系统资源
		ImageIO.write(image, "JPEG",response.getOutputStream());//输出图片
	}
}
与ajax实现异步校验的servlet

用户名是否存在于数据库校验

数据库语句已经封装在我的DBConnection,前面javaweb那篇里有代码

package fourkings;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DBC.DBConnection;

/**
 * Servlet implementation class NameExistServlet
 */
@WebServlet("/NameExistServlet")
public class NameExistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NameExistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
  		String loginname=request.getParameter("val");
		Connection conn = DBConnection.getConnection();
		try{
			String sql="select*from user where username="+"'"+loginname+"'";
			System.out.println(sql);
			Statement stmt=conn.createStatement();
			ResultSet rs=stmt.executeQuery(sql);
			System.out.println("get "+loginname);
			while(rs.next()){
				String dName=rs.getString("username");
				if(dName.equals(loginname)){
					System.out.print("false");
					response.getWriter().print(false);
				}
				else{
					System.out.print("true");
					response.getWriter().print(true);
				}
			}
		}catch(Exception e){e.printStackTrace();}
	}
}
验证码和输入内容相等校验

package fourkings;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DBC.DBConnection;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		String jvalidateCode=request.getParameter("verifyCode");
		String vvalidateCode=(String) request.getSession().getAttribute("randCheckCode");
		System.out.print(vvalidateCode);
		boolean b=jvalidateCode.equals(vvalidateCode);
		response.getWriter().print(b);
	}		
}
还有web.xml

<servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>fourkings.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>NameExistServlet</servlet-name>
    <servlet-class>fourkings.NameExistServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>NameExistServlet</servlet-name>
    <url-pattern>/NameExistServlet</url-pattern>
  </servlet-mapping>
最经常出问题的就是路径问题,404-404-404

还有最想说的:出现404问题时不能慌,不用说80%可能性是路径问题,就改web,xml

但是每次改完都要等tomcat重新部署reload,然后再刷新页面开工,肺腑之言啊

很多时候做过的更改还没reload,急的上火

还有。。讲真chrome的开发者调试真不错、、、











版权声明:本文为Damionew原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Damionew/article/details/73048150