JSF实现验证码

public class ImageData implements Serializable {

	private static final long serialVersionUID = -8161565799237268271L;
	private BufferedImage image;
	Integer width = 60;
	Integer height = 20;
	Color bankgroud = new Color(0xFFFFFF);
	Color drawColor = new Color(0x000000);
   Font textFont = new Font("Comic Sans ms", Font.PLAIN, 18);
   String str = "0,a,2,x,e,5,j,7,l,9,1,b,c,d,4,f,g,h,i,6,k,8,m,n,o,p,q,r,s,t,u,v,w,3,y,z";	
	Random random = new Random();
	public void paint(OutputStream out, Object data) throws IOException {
		if (data instanceof ImageData) {
			// create the image
			image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics graphics = image.getGraphics();
			graphics.setColor(bankgroud);
			graphics.fillRect(0, 0, width, height);	
			graphics.setColor(drawColor);
			graphics.drawRect(0, 0, width - 1, height - 1);
			graphics.setFont(textFont);
			//绘制干扰线
			for (int i = 0; i < 160; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int xl = random.nextInt(12);
				int yl = random.nextInt(12);
				graphics.setColor(getRandColor(100,250));
				graphics.drawLine(x, y, x + xl, y + yl);
			}
                       //绘制验证码
			graphics.setColor(drawColor);
			String code="" ;
			String[] array = str.split(",");
			for (int i = 0; i < 4; i++) {						
				String rand = array[random.nextInt(36)];
				code += rand;	
				graphics.drawString(rand, 13 * i + 6, 16);
			}	
		          FacesUtil.getSession().setAttribute("code", code);
			graphics.dispose();
		}
		ImageIO.write(image, "JPEG", out);
	}	

	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);
	}

}

 

<a4j:mediaOutput element="img" cacheable="flase" session="false"  
                   rendered="true" createContent="#{validateCodeImageData.paint}"  
                  value="#{validateCodeImageData}" mimeType="image/jpeg">
 </a4j:mediaOutput> 

 

 <managed-bean>   
             <managed-bean-name>validateCodeImageData</managed-bean-name>   
             <managed-bean-class>   
                        com.jxh.common.view.ImageData   
             </managed-bean-class>   
             <managed-bean-scope>request</managed-bean-scope>   
   </managed-bean>   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值