生成验证码的Action

/***********************************************************************
	  * 1.方法说明 * 生成验证码. 
	  * 2.使用方法 * jsp页面,验证码长度大小等见注释 *
	*/  
	public ActionForward validateNumber(ActionMapping mapping, ActionForm form,    HttpServletRequest request, HttpServletResponse response) {   
		// 设置页面不缓存
		response.setHeader("Pragma", "No-cache");   
		response.setHeader("Cache-Control", "no-cache");   
		response.setDateHeader("Expires", 0);   
		// 设置图片的长宽
		int width = 176, height = 30;   
		// 设置备选字母
		String base = "abcdefghijklmnopqrstuvwxyz1234567890";   
		// 备选汉字的长度
		int length = base.length();
		// 创建内存图像
		BufferedImage image = new BufferedImage(width, height,     BufferedImage.TYPE_INT_RGB);   
		// 获取图形上下文
		Graphics g = image.getGraphics();   
		// 创建随机类的实例
		Random random = new Random();
		// 设定图像背景色(因为是做背景,所以偏淡)
		g.setColor(getRandColor(random, 200, 250));   
		g.fillRect(0, 0, width, height);

		  // 备选字体
		String[] fontTypes = { "/u5b8b/u4f53", "/u65b0/u5b8b/u4f53",     "/u9ed1/u4f53", "/u6977/u4f53", "/u96b6/u4e66" };   
		int fontTypesLength = fontTypes.length;

		  // 在图片背景上增加噪点
		g.setColor(getRandColor(random, 160, 200));   
		g.setFont(new Font("Times New Roman", Font.PLAIN, 14));   
		for (int i = 0; i < 6; i++) {    
			g.drawString("*********************************************", 0,      5 * (i + 2));   }   
		// 取随机产生的认证码(6个)

		// 保存生成的字符串
		String sRand = "";   
		for (int i = 0; i < 6; i++) {    
			int start = random.nextInt(length);    
			String rand = base.substring(start, start + 1);    
			sRand += rand;
		}

		// 设置字体的颜色
		g.setColor(getRandColor(random, 10, 150));    
		// 设置字体
		g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)],Font.BOLD, 18 + random.nextInt(6)));    
		// 将此汉字画到图片上
		g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);   }
	

		  // 将认证码存入
		session   HttpSession session = request.getSession();   
		session.setAttribute("rand", sRand);

		g.dispose();

		try {    
			ImageIO.write(image, "JPEG", response.getOutputStream());   
		}catch (IOException e) {    
			e.printStackTrace();   
		}
		  return null; 
	}  
	// 生成随机颜色
	private Color getRandColor(Random random, int fc, int bc) {
		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);  
		} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值