验证码

验证码的验证是我们登陆网页时经常进行的操作,我也做了一个简单的验证码,包括颜色以及噪线等等

@RequestMapping(value = "/Frame/VerifyCode", method = RequestMethod.GET)
	public @ResponseBody ModelAndView VerifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
		int codeW = 80;
		int codeH = 22;
		int fontSize = 16;
		// 颜色列表,用于验证码、噪线、噪点
		Color[] color = { Color.BLACK, Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.GRAY, Color.YELLOW };
		// 字体列表,用于验证码
		String[] font = { "Verdana" };
		// 验证码的字符集,去掉了一些容易混淆的字符
		String[] character = { "2", "3", "4", "5", "6", "8", "9", "a", "b", "d", "e", "f", "h", "k", "m", "n", "r", "x",
				"y", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "W", "X",
				"Y" };
		Random rnd = new Random();
		String chkCode[] = new String[4];
		// 生成验证码字符串
		for (int i = 0; i < 4; i++) {
			chkCode[i] = character[rnd.nextInt(character.length)];
		}
		// 创建画布
		BufferedImage image = new BufferedImage(codeW, codeH, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Color clr = color[rnd.nextInt(color.length)];
		// 设置背景色  
		g.setColor(Color.DARK_GRAY);
		g.setFont(new Font("Verdana",0,26));
		g.fillRect(0, 0, codeW, codeH);
		// g.setColor(clr);
		// 画噪线
		for (int i = 0; i < 1; i++) {
			int x1 = rnd.nextInt(codeW);
			int y1 = rnd.nextInt(codeH);
			int x2 = rnd.nextInt(codeW);
			int y2 = rnd.nextInt(codeH);
			clr = color[rnd.nextInt(color.length)];
		    g.setColor(clr);
			g.drawLine(x1, y1, x2, y2);
		}
		String codeCheck = "";
		// 画验证码字符串
		for (int i = 0; i < chkCode.length; i++) {
			clr = color[rnd.nextInt(color.length)];
		    g.setColor(clr);
			g.drawString(chkCode[i], 20*i, 20);
			codeCheck += chkCode[i];
		}
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			ImageIO.write(image, "JPEG", out);
			out.flush();
			out.close();
			System.out.println("生成的验证码:code="+chkCode); 
			httpSession.setAttribute("SESSION_CHECKCODE", codeCheck);
		} 
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值