java验证码生成

 在JavaWeb开发中常会用到生成验证码的代码,采用Struts2开发框架,验证码的实现如下:
 1 controller层代码
	public String pic() throws Exception{
		HttpServletResponse response=ServletActionContext.getResponse();
		HttpServletRequest request=ServletActionContext.getRequest();
		response.setContentType("image/png");
		BufferedImage image=new BufferedImage(108, 40, BufferedImage.TYPE_INT_RGB);
		Graphics2D g=image.createGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, 108, 40);
		Random r=new Random();
		for (int i = 0; i < 50; i++) {
			g.setColor(getColor());
			int x=r.nextInt(108);
			int y=r.nextInt(40);
			int x1=x+r.nextInt(10);
			int y1=y+r.nextInt(10);
			g.drawLine(x, y, x1, y1);
		}
		
		for (int i = 0; i <100; i++) {
			int x=r.nextInt(108);
			int y=r.nextInt(40);
			g.setColor(getColor());
			g.drawOval(x, y, 1, 1);
		}
		g.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
		String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		StringBuffer buff=new StringBuffer();
		for (int i = 0; i < 5; i++) {
			String ch=String.valueOf(str.charAt(r.nextInt(str.length())));
			buff.append(ch);
			g.setColor(getColor());
			g.drawString(ch, i*22+2, 20+r.nextInt(12));
		}
		HttpSession session=request.getSession();
		session.setAttribute("checkcode", buff.toString());
		OutputStream out=response.getOutputStream();
		ImageIO.write(image, "PNG", out);
		return "pic";
	}
	
	public Color getColor(){
		Random r=new Random();
		return new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
	}

2 在 Struts.xml 的配置

  <result name="pic" type="stream">
	           <param name="contentType">image/jpeg</param>
	           <param name="inputName">inputStream</param>
  </result>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值