SpringMVC生成4位随机验证码

/*
 * 
 * 生成4位随机验证码(字母+数字)
 */
@Controller
@RequestMapping("/")
public class CheckCodeHandler {

	
	
	//产生随机的字体
			private Font getFont(){
				//创建random对象,用于生产随机数
				Random random = new Random();
				//创建字体数组,用于封装不同字体的Font对象
				Font font[] = new Font[5];
				font[0] = new Font("Ravie", Font.PLAIN, 24);
				font[1] = new Font("Antique Olive Compact", Font.PLAIN, 24);
				font[2] = new Font("Forte", Font.PLAIN, 24);
				font[3] = new Font("Wide Latin", Font.PLAIN, 24);
				font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 24);
				
				return font[random.nextInt(5)];
			}
			
			
			
			@RequestMapping("/code")
			public String code(HttpServletRequest request, HttpServletResponse response) throws IOException{
				
				//设置响应头类型
				response.setContentType("image/jpeg");
				OutputStream os = response.getOutputStream();
				int width = 83,  height = 30;
				//建立指定宽高和BufferedImage 对象
				BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				Graphics g = image.getGraphics();   //该画笔绘制于image上
				Color c = g.getColor();   //保存当前画笔颜色
				//填充矩形
				g.fillRect(0, 0, width, height);
				char [] ch = "abcdefghjkmnpqrstuvwxyz2345678901".toCharArray();
				//随机产生的字符串,不包括字母i、o、(小写), 数字0,1
				int length = ch.length;       //随机字符串的长度
				String sRand = "";            // 保存随机产生的字符串
				Random random = new Random();
				for (int i = 0; i < 4; i++) {
					//设置字体
					g.setFont(getFont());
					//随机生成0-9的数字
					String rand = new Character(ch[random.nextInt(length)]).toString();
					sRand += rand;
					//设置随机颜色
					g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
					g.drawString(rand, 20*i+6, 25);
				}
				//产生随机干扰点
				for (int i = 0; i < 20; i++) {
					int x1 = random.nextInt(width);
					int y1 = random.nextInt(height);
					g.drawOval(x1, y1, 2, 2);
				}
				//重设画笔的颜色
				g.setColor(c);
				//释放此图形的上下文及其使用的所有系统资源
				g.dispose();
				//将验证码记录到session中
				request.getSession().setAttribute("safeCode", sRand);
				//输出图像到页面中
				ImageIO.write(image, "JPEG", os);
				return null;
				/*
				 * 此处只能return null ,
				 * 写成 return "LIManager/login" 会导致多次响应,
				 * java.lang.IllegalStateException: getOutputStream() has already been called response
				 */
			}
			
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值