验证码技术

在Javaweb项目开发的时候,要做的几乎都会有用户登录功能,那么这个验证码是怎么生成的?

下面我解释一下原理,源码是别人的,忘了从哪copy的了,所以就不写转载的地址了!!!

什么是验证码?

说白了就是从一个容器中随机抽取四个字母数字进行组合,这个容器是自己定义的,然后将抽取到的验证码存到session中,登陆的时候进行验证。

如何将验证码做成图片

这个都是死套路,网上各种各样的源码都有。

下面是一个完整的验证码的代码

html代码

<div class="form-group">
		<div class="field">
			<input type="text" class="input input-big" name="usercode" id="usercode" placeholder="填写右侧的验证码" data-validate="required:请填写右侧的验证码" />
			<span></span>
			<img src="valid.do" alt="" width="100" height="32" class="passcode" style="height:43px;cursor:pointer;" onclick="this.src=this.src+'?'">
		</div>
</div>

验证码的 servlet代码

package servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
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;

/**
 * 
 * @author 浪子一秋
 *
 */
@WebServlet("/valid.do")
public class ValidateCodeServlet extends HttpServlet {
	// 图形验证码的字符集,系统将随机从这个字符串中选择一些字符作为验证码
	private static String codeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获得验证码集合的长度
		int charsLength = codeChars.length();
		// 下面3条记录是关闭客户端浏览器的缓冲区
		// 这3条语句都可以关闭浏览器的缓冲区,但是由于浏览器的版本不同,对这3条语句的支持也不同
		// 因此,为了保险起见,同时使用这3条语句来关闭浏览器的缓冲区
		response.setHeader("ragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		// 设置图形验证码的长和宽
		int width = 90, height = 30;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandomColor(180, 250));

		g.fillRect(0, 0, width, height);

		g.setFont(new Font("Times New Roman", Font.ITALIC, height));

		g.setColor(getRandomColor(120, 180));
		// 用户保存最后随机生成的验证码
		StringBuffer validationCode = new StringBuffer();
		// 验证码的随机字体
		String[] fontNames = { "Times New Roman", "Book antiqua", "Arial" };

		// 随机生成4个验证码
		for (int i = 0; i < 4; i++) {
			// 随机设置当前验证码的字符的字体
			g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC,
					height));
			// 随机获得当前验证码的字符
			char codeChar = codeChars.charAt(random.nextInt(charsLength));
			validationCode.append(codeChar);
			// 随机设置当前验证码字符的颜色
			g.setColor(getRandomColor(10, 100));
			// 在图形上输出验证码字符,x和y都是随机生成的
			g.drawString(String.valueOf(codeChar), 16 * i + random.nextInt(7),
					height - random.nextInt(6));
		}

		// 获得HttpSession对象

		HttpSession session = request.getSession();

		// 设置session对象5分钟失效

		session.setMaxInactiveInterval(5 * 60);

		// 将验证码保存在session对象中,key为validation_code

		session.setAttribute("code", validationCode.toString());
		//关闭Graphics对象

		g.dispose();

		OutputStream outS = response.getOutputStream();

		ImageIO.write(image, "JPEG", outS);
	}


	private Color getRandomColor(int minColor, int maxColor) {
		Random random = new Random();
		if(minColor > 255){
			minColor = 255;
		}
		if(maxColor > 255){
			maxColor = 255;
		}
		//获得r的随机颜色值
		int red = minColor+random.nextInt(maxColor-minColor);
		int green = minColor + random.nextInt(maxColor-minColor);
		int blue = minColor + random.nextInt(maxColor-minColor);
		return new Color(red,green,blue);
	}
}

登录验证的servlet

            //获取html输入的验证码
            String validationCode = req.getParameter("usercode");
			//获取服务器的验证码
			HttpSession session = req.getSession();
			String validation_code = (String)session.getAttribute("code");
            //验证验证码,不分大小写
            if(validationCode.equalsIgnoreCase(validation_code)){
					resp.getWriter().print("1000");
					//验证码正确
			}else{			
                    //验证码错误!!!	
					resp.getWriter().print("1001");
					return;
			}

猜你喜欢

转载自blog.csdn.net/qq_41534115/article/details/83268143