`

验证码

    博客分类:
  • java
 
阅读更多

 

package com.kcls.oasystem.tools;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Validate extends HttpServlet{
	private static final long serialVersionUID = 1L;
	public String suijima(){
		   char [] str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
		   Random rd=new Random();
		   String suiji="";
		   int temp=0;
		   for(int i=0;i<4;i++){
		    temp=rd.nextInt(36);//随机生成验证码数据
		     suiji+=str[temp];
		   }
		   return suiji; 
		}


		public void service(HttpServletRequest request, HttpServletResponse response)
		    throws ServletException, IOException {

		   String sjm=suijima();
		   HttpSession session=request.getSession();
		     session.setAttribute("check",sjm); 
		     
//构造一个类型为预定义图像类型之一的 BufferedImagewidth - 所创建图像的宽度 height - 所创建图像的高度 imageType - 所创建图像的类型
		   BufferedImage buffimg=new BufferedImage(60,20,
		                BufferedImage.TYPE_INT_RGB);
//Graphics 类是所有图形上下文的抽象基类
		   Graphics g=buffimg.createGraphics();
		   Random rd=new Random();
		   int cr,cg,cb;
		   cr=rd.nextInt(255);
		   cg=rd.nextInt(255);
		   cb=rd.nextInt(255);
		   Color mycolor=new Color(cr,cg,cb);
//将此图形上下文的当前颜色设置为指定颜色。
		   g.setColor(mycolor);
		     for (int i = 0; i < 10; i++)
		        {
		            int x1 = rd.nextInt(60);
		            int x2 = rd.nextInt(60);
		            int y1 = rd.nextInt(20);
		            int y2 = rd.nextInt(20);
//在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1)(x2, y2) 之间画一条线。
		            g.drawLine(x1, y1, x2, y2);
		        } 
		   Font myfont=new Font("times new roman",Font.PLAIN,19);
// 将此图形上下文的字体设置为指定字体。
		   g.setFont(myfont);   
		   g.setColor(Color.WHITE);
//使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。str - 要绘制的 string。x - x 坐标。y - y 坐标。
		   g.drawString(sjm,5,15);
		        ServletOutputStream sos=response.getOutputStream();
//使用支持给定格式的任意 ImageWriter 将一个图像写入 OutputStream
		        ImageIO.write(buffimg, "jpeg",sos);
		        sos.close();
//释放此图形的上下文以及它使用的所有系统资源。
		        g.dispose();
		  }
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics