利用java技术生成验证码的多种方法及遇到问题的解决

1、利用HTML+JS技术,直接在前端产生验证码并且进行检验。

index.html描绘输入框和验证码的布局。


	
		验证码
		
		
	
	
		

checkCode.js对输入框与验证码是否匹配的验证。

			var code ; //在全局定义验证码 
			//产生验证码
			window.onload = function createCode(){
				 code = ""; 
				 var codeLength = 4;//验证码的长度
				 var checkCode = document.getElementById("code"); 
				 var random = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
				 'S','T','U','V','W','X','Y','Z');//随机数
				 for(var i = 0; i < codeLength; i++) {//循环操作
					var index = Math.floor(Math.random()*36);//取得随机数的索引(0~35)
					code += random[index];//根据索引取得随机数加到code上
				}
				checkCode.value = code;//把code值赋给验证码
			}
			//校验验证码
			function validate(){
				var inputCode = document.getElementById("input").value.toUpperCase(); //取得输入的验证码并转化为大写      
				if(inputCode.length <= 0) { //若输入的验证码长度为0
					alert("请输入验证码!"); //则弹出请输入验证码
				}       
				else if(inputCode != code ) { //若输入的验证码与产生的验证码不一致时
					alert("验证码输入错误!@_@"); //则弹出验证码输入错误
					createCode();//刷新验证码
					document.getElementById("input").value = "";//清空文本框
				}       
				else { //输入正确时
					alert("^-^"); //弹出^-^
				}           
			}


2、利用jsp+js+servlet技术,前端显示布局图片和进行验证码的匹配,后台产生验证码图片。

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>




验证码测试









	

jsp+js+servlet实现验证码


用户名:
请输入验证码: 看不清,换一张!

CodeServlet.java

package com.hthk.iisz.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

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

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CodeServlet extends HttpServlet {

	/**
	 * 产生验证码图片
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0L);
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width, height, 1);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Arial", 0, 25));
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width + 100);
			int y = random.nextInt(height + 100);
			int xl = random.nextInt(10);
			int yl = random.nextInt(12);
			g.drawOval(x, y, x + xl, y + yl);
		}
		String code = request.getParameter("code");
		String sRand = code;
		for (int i = 0; i < sRand.length(); i++) {
			String rand = sRand.substring(i, i + 1);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 14 * i + 5, 25);
		}
		g.dispose();
		javax.servlet.ServletOutputStream imageOut = response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut);
		encoder.encode(image);
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

}

web.xml

 
    CodeServlet
    com.action.CodeServlet
  
  
    CodeServlet
    /CodeServlet
  

2、利用jsp+js+ajax技术。jsp显示布局和生成验证码图片,js进行验证,ajax解决jsp中的验证码与session验证码不一致的问题。

index.jsp(部分代码)


 

						
 

image.jsp

<%@ page contentType="image/JPEG"
	import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"
	pageEncoding="GBK"%>
	
	<%!Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}%>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", 0);

	int width = 60, height = 20;
	BufferedImage image = new BufferedImage(width, height,
			BufferedImage.TYPE_INT_RGB);

	Graphics g = image.getGraphics();

	Random random = new Random();

	g.setColor(getRandColor(200, 250));
	g.fillRect(0, 0, width, height);

	g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

	g.setColor(getRandColor(160, 200));
	for (int i = 0; i < 100; i++) {
		int x = random.nextInt(width);
		int y = random.nextInt(height);
		int xl = random.nextInt(12);
		int yl = random.nextInt(12);
		g.drawLine(x, y, x + xl, y + yl);
	}

	String sRand = "";
	for (int i = 0; i < 4; i++) {
		String rand = String.valueOf(random.nextInt(10));
		sRand += rand;

		g.setColor(new Color(20 + random.nextInt(110), 20 + random
				.nextInt(110), 20 + random.nextInt(110)));
		g.drawString(rand, 13 * i + 6, 16);
	}

	session.setAttribute("code", sRand);

	g.dispose();

	ImageIO.write(image, "JPEG", response.getOutputStream());
%>

capcha_validate.jsp(ajax验证)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	String capchaInput = request.getParameter("capchaInput");
	String randomCode = (String) session.getAttribute("code");

	String resultCode = "";
	if (capchaInput.equals(randomCode)) {
		resultCode = "0";

	} else {
		resultCode = "-1";

	}
	response.getWriter().write(resultCode);
%>


遇到的最常见的两个问题:

1、验证码图片没显示

 原因是src=“”这里的图片位置没写对,用这个request.getContextPath()试下或者是在web.xml配置servlet的路径要一致。

2、验证码总是上一次的。

原因是因为加载jsp页面要比session页面要快一些,所以总是拿到上一次session的值。

解决办法输入框的值和验证码的值同时传到后台servlet处理再反馈到前端,或者参考案例3利用ajax请求传到一个jsp页面处理,在利用 response.getWriter().write(resultCode)反馈到前台,搞掂!







你可能感兴趣的:(利用java技术生成验证码的多种方法及遇到问题的解决)