Ajax—验证码部分实现

1、概念
Ajax不是一种新的编程语言, 而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。

2、使用原因
传统的网页(即不用ajax技术的网页) , 想要更新内容或者提交一个表单, 都需要重新加载整个网页。
使用Ajax技术的网页,通过在后台服务器进行少量的数据交换, 就可以实现异步局部更新。

3、验证码,前端代码

<script src="js/jQuery.js"></script>
<script type="text/javascript">
	$(function(){	
		//实现点击更换图片
		$("#imgCode").click(function(){
			$(this).attr("src","${pageContext.request.contextPath}/codeImage.action?"+new Date());
		});	
		
		//点击登录时
		$("#loginBtn").click(function(){
			if($("#username").val()==""){ alert("用户名不能为空");return;}
			if($("#password").val()==""){alert("密码不能为空");return;}
			if($("#code").val()==""){alert("验证码不能为空");return;}
			//通过ajax获取数据
			$.ajax({
				type:"POST",
				url:"${pageContext.request.contextPath}/codeValue.action",
				success:function(returnDate){
					if($("#code").val().toLowerCase()==returnDate.code.toLowerCase()){
						if($("#username").val()!="" && $("#password").val()!=""){
							$("#form1").submit();
						}
					}else{
						alert("验证码错误");
					}			
				}
			});				
		});	
	});			
</script>

//from表单部分
<form action="${pageContext.request.contextPath}/login.action" method="post" id= "form1">
	<table>
		<tr><td>用户名:</td><td colspan="2"><input type="text" name="username" id="username" /></td></tr>
		<tr><td>密码:</td><td colspan="2"><input type="password" name="password" id="password"/></td></tr>
		<tr>
			<td>验证码:</td>
			<td colspan="1"><input type="text" name="code" id="code"/></td>
			<td colspan="1">
				<img id="imgCode" src="${pageContext.request.contextPath}/codeImage.action" title="看不清楚,点击更换验证码"/>
			</td>
		</tr>
		
		<tr><td colspan="3" style="color: red">${requestScope.loginErr}</td></tr>
							
		<tr><td><input type="button" value="登录" name="login" id = "loginBtn" /></td></tr>
	</table>
</form>

4、验证码,后端代码

@WebServlet("/codeImage.action")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	CodeImage random =new CodeImage();
	random.getRandCode(request, response);//获取验证码
}

//Ajax部分
@WebServlet("/codeValue.action")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();
	Object mm = session.getAttribute("imageCode");

	response.setContentType("application/json");
	Code code = new Code(mm.toString());
	Gson gson = new Gson();//maven中引入依赖
	String jString = gson.toJson(code);
	
	response.getWriter().println(jString);
}

//自己写的验证码类
public class CodeImage {
	private int height = 40;
	private int width = 80;
	private int lineNum = 40;
	private int stringNum = 4;
	private Random random = new Random();
	private String randomString = "123456789ABCDEFHIJKLMNPQRSTUVWXYZ";
	private Font getFont(){
		Font font = new Font("宋体",Font.CENTER_BASELINE,25);
		return font;
}
private Color getColor(){
	Color color = new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
	return color;
}	
private void drawLine(Graphics gh){
	int x = random.nextInt(width);
	int y = random.nextInt(height);
	int x1 = random.nextInt(13);
	int y1 = random.nextInt(15);
	gh.drawLine(x, y, x+x1, y+y1);
}
private String drawData(Graphics gh,String data,int num){
	gh.setFont(getFont());
	gh.setColor(getColor());
	String randData = String.valueOf(randomString.charAt(random.nextInt(randomString.length())));
		data = data + randData;
		gh.drawString(randData, num*18, 16);
		return data;		
}
public void getRandCode(HttpServletRequest request,HttpServletResponse response){
	HttpSession session = request.getSession();
	BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
	Graphics gh = image.getGraphics();
	gh.fillRect(0, 0, width, height);
	gh.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
	gh.setColor(getColor());
	for(int i=0;i<lineNum;i++){
		drawLine(gh);
	}
	gh.translate(3, 10);
	String data = "";
	for(int i=0;i<stringNum;i++){
		data = drawData(gh,data,i);
	}
	session.setAttribute("imageCode", data);
	gh.dispose();
	try {
		ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (IOException e) {
		e.printStackTrace();
		}
	}
}
采用ajax技术实现的图形验证码,在前端进行验证。验证码信息为图片。每一行代码均有注释,通俗易懂。 实现步骤: 1、创建web工程 2、在jsp页面,编写一个 3、编写一个servlet,在servlet中产生图形验证码 ------------------------------------------------------------ //1、给客户端作出的回应是以图片的方式来回应 response.setContentType("image/jpeg"); //2、创建一个图形缓冲区,用于绘制图形 (宽度,高度,颜色的生成方案) BufferedImage image = new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB); //3、创建一支画笔(图形设备接口)用于绘图 Graphics g = image.getGraphics(); //4、指定图笔的颜色 g.setColor(getColor(200,256)); //5、绘制一个矩形框,作为验证码的背景 g.fillRect(0,0, 800,600); //产生一个输出流,准备把图片以流的方式,输出到客户端 OutputStream out = response.getOutputStream(); //输出在图形缓冲区中,绘制的图片 ImageIO.write(image,"jpg",out); //关闭流 out.close(); //随机生成背景颜色 private Random rd = new Random(); //产生随机数类 public Color getColor(int start,int end){ int r = start+rd.nextInt(end-start); int g = start+rd.nextInt(end-start); int b = start+rd.nextInt(end-start); return new Color(r, g, b);//根据三原色的值,随机在指定范围内,生成一种颜色 } --------------------------------------------------------------------------- 0-120 比较适合文字的颜色 100-200 适合干扰线条的颜色 200-255 适合背景颜色 --------------------------------------------------------------------------- 生成图片中的文字: 1、先编写一个字符串,包含:数字,大小字母 private String s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 2、在产生背景之后,编写如下代码,产生四个字符(并且,把生成字符,保存在session中,在登录的时候用来做判断) String code=""; //用于保存生成的四个字符 for(int i=0;i<4;i++){ //生成一个随机数,它的取值范围,一定要在s这个字符串的长度范围之内 int index = rd.nextInt(s.length()); //2 //把index作为下标,来取得字符串的中某一个字符 char c = s.charAt(index); //指定文字的颜色----深色段 g.setColor(getColor(0,120)); //创建一个字体 Font f = new Font("隶书",Font.ITALIC|Font.BOLD,60+rd.nextInt(60)); //把字体关联到画笔 g.setFont(f); code+=c; //把生成的字符连接成一个字符串 //把文字输出到图片上 g.drawString(String.valueOf(c), 100+i*80+rd.nextInt(100),200+rd.nextInt(150)); } request.getSession().setAttribute("code",code);//把生成的验证码信息,存储到session中,登录的时候,用来作判断 ------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值