java的动态验证码单线设计

1.java的动态验证码我这里将介绍两种方法:

根据java本身提供的一种验证码的写法,这种呢只限于大家了解就可以了,因为java自带的模式编写的在实际开发中是没有意义的,所以只供学习一下就可以了,待会讲解的第二种呢就是我们需要掌握的一种模式了:

第一种的代码如下:

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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class inde
 */
@WebServlet("/inde")
public class inde extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public inde() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
            this.doPost(request, response);            
    }

    /**动态生成图片验证码
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //创建图像
        int width=100;
        int height=40;
        //图片的大小设置
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //创建画板        
        Graphics g=image.getGraphics();    
        
         setSquareBackGround(g,width,height,5);
        //确定画笔颜色
        g.setColor(Color.black);
        //填充矩形
        g.fillRect(0, 0, width, height);
            //在大矩形中放小矩形
            g.setColor(Color.WHITE);
            g.fillRect(1, 1, width-2, height-2);                
        //填充字符
        String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
        StringBuffer sb=new StringBuffer();
         //画随机干扰框
        setSquareBackGround(g,width,height,3); 
       //画干扰点
       CreateRandomPoint(width, height,100,g,100);       
       //随机画几条线
       CreateRandomLine(width, height,8,g,100);    
        //随机获取4个字符
        Random random=new Random();
        for (int i = 0; i < 4; i++) {
            //62个填充字符里面随机的随机的收取字符
            int index=random.nextInt(62);
            //截取一个字符
            String st=str.substring(index, index+1);
            //把字符放到图片中去
            g.setColor(Color.red);
            //设置字体
            g.setFont(new Font("宋体",Font.BOLD,30));
            g.drawString(st, 20*i, 30);//防止4个字符在一起
            sb.append(st);
        }
        
        //把StringBuffer中的验证码放到session里面,目的是让Login调用
        HttpSession se=request.getSession();
        se.setAttribute("number", sb.toString());
        
        
        //发送图片到浏览器 指定发送的图片 和格式
        response.setContentType("image/jpeg");
        //图片,图片的格式,输出的方式
        ImageIO.write(image, "jpg", response.getOutputStream());
                
    }
    Random rand = new Random();
    private void CreateRandomPoint(int width,int height,int many,Graphics g,int alpha)
    {  // 随机产生干扰点
        for (int i=0;i<many;i++) {
            int x = rand.nextInt(width); 
            int y = rand.nextInt(height); 
            g.setColor(getColor(alpha));
            g.drawOval(x,y,rand.nextInt(3),rand.nextInt(3)); 
        } 
    }
/**
 * 随机产生干扰线条
 * @param width
 * @param height
 * @param minMany 最少产生的数量
 * @param g
 * @param alpha 透明度0~255 0表示全透
 */
    private void CreateRandomLine(int width,int height,int minMany,Graphics g,int alpha)
    {  // 随机产生干扰线条
        for (int i=0;i<getIntRandom(minMany, minMany+6);i++) { 
            int x1 =getIntRandom(0,(int)(width*0.6)); 
            int y1 =getIntRandom(0,(int)(height*0.6)); 
            int x2 =getIntRandom((int)(width*0.4),width); 
            int y2 =getIntRandom((int)(height*0.2),height);  
            g.setColor(getColor(alpha));
            g.drawLine(x1, y1, x2, y2);
        } 
    }
    
    /**
     * 由随机产生的方块来作为干扰背景
     */
    private void setSquareBackGround(Graphics g,int width,int height,int count){
        // 随机产生干扰线条
        for (int i=0;i<getIntRandom(count, count+2);i++) { 
            int x1 =getIntRandom(0,(int)(width*0.3)); 
            int y1 =getIntRandom(0,(int)(height*0.3)); 
            int x2 =getIntRandom((int)(width*0.5),width); 
            int y2 =getIntRandom((int)(height*0.55),height);  
            g.setColor(getColor(100));
            int w=x2-x1;
            int h=y2-y1;
            if(w<0) w=-w;
            if(h<0) h=-h;
            g.drawRect(x1, y1, w, h);
            g.setColor(getColor(25));
            g.fillRect(x1, y1, w, h);
        } 
    }
    private int getIntRandom(double start,double end)
    {   if(end<start)
        {
          double t=end;
          end=start;
          start=t;
        }
        double i=start+(int) (Math.random()*(end-start));
        return (int)i;
    }
    
   

上面的代码呢写的很详细了,这里我就不重复了,这里的干扰线条是有很多写法的,我这里就没有全写出来,有需要的话可以私聊我哦!

下面介绍第二种:

这种呢是我们开发中是可以用得到的,使用在的是网页端的交互,我们在登录网站的时候有很多的验证码就可以用这个来写了

import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class inde
 */
@WebServlet("/inde")
public class inde extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public inde() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
            this.doPost(request, response);            
    }

    /**动态生成图片验证码
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //创建图像
        int width=100;
        int height=40;
        //图片的大小设置
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //创建画板        
        Graphics g=image.getGraphics();    
        
         setSquareBackGround(g,width,height,5);
        //确定画笔颜色
        g.setColor(Color.black);
        //填充矩形
        g.fillRect(0, 0, width, height);
            //在大矩形中放小矩形
            g.setColor(Color.WHITE);
            g.fillRect(1, 1, width-2, height-2);                
        //填充字符
        String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
        StringBuffer sb=new StringBuffer();
//随机获取4个字符
        Random random=new Random();
        for (int i = 0; i < 4; i++) {
            //62个填充字符里面随机的随机的收取字符
            int index=random.nextInt(62);
            //截取一个字符
            String st=str.substring(index, index+1);
            //把字符放到图片中去
            g.setColor(Color.red);
            //设置字体
            g.setFont(new Font("宋体",Font.BOLD,30));
            g.drawString(st, 20*i, 30);//防止4个字符在一起
            sb.append(st);
        }
//把StringBuffer中的验证码放到session里面,目的是让Login调用
        HttpSession se=request.getSession();
        se.setAttribute("number", sb.toString());
        
        
        //发送图片到浏览器 指定发送的图片 和格式
        response.setContentType("image/jpeg");
        //图片,图片的格式,输出的方式
        ImageIO.write(image, "jpg", response.getOutputStream());
                
    }



这样就可以运行了,当然了我们可以在这里面加入第一种的干扰模块给拿过来这样就可以实现整体的一个效果了

以上的代码我都实验过了,都是可以运行的,今天就想到这里了,感谢大家的欣赏

猜你喜欢

转载自www.cnblogs.com/shuiqian/p/9352161.html