java 生成验证码

项目中看到验证码的生成不是直接用的图片,而是根据自己的properties属性文件用java开发的。
我在这里做一个记录:
一个很简单的应用,就是一个jsp页面来展示一个生成的验证码的图片。
首先来看一下效果:



这个验证码的长度可以根据自己的需要设置成指定的长度。当然,那样的话,图片长高也要相应的做修改。

1.开发环境:IDE:MyEclipse 10 + jdk1.6.0_43 + tomcat-7.0.53
2.新建一个动态的web project。
3.主要涉及到了这么几个文件:
  验证码属性配置文件:imgCode.properties
  获取配置文件通用类:Config.java
  登录验证码配置:RandomConf.java
以及生成验证码的servlet类:VerifyCodeServlet.java

4.主要servlet处理类源码:VerifyCodeServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
	ServletException, IOException  {
		System.setProperty("java.awt.headless", "true");
        BufferedImage buffImg = new BufferedImage(RandomConf.getWidth(), RandomConf.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
//        g.setColor(Color.WHITE);
        g.setColor(new Color(
        		RandomConf.getRed(),
        		RandomConf.getGreen(),
        		RandomConf.getBlue()));
        g.fillRect(0, 0, RandomConf.getWidth()-2, RandomConf.getHeight()-2);

        Font font = new Font(RandomConf.getFontType(), Font.PLAIN, RandomConf.getFontSize());
        g.setFont(font);
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, RandomConf.getWidth() - 2, RandomConf.getHeight() - 2);

        g.setColor(Color.GRAY);

		Random random = new Random();

        for (int i = 0; i < RandomConf.getComplex(); i++) {
            int x1 = random.nextInt(RandomConf.getWidth()-2);
            int y1 = random.nextInt(RandomConf.getHeight()-2);

            int x2 = random.nextInt(10);
            int y2 = random.nextInt(10);

            g.drawLine(x1, y1, x1 + x2, y1 + y2);//在点(x1, y1)与点(x1 + x2, y1 + y2)之间画一条线
        }

        StringBuffer randomCode = new StringBuffer();
        int red = 0;
        int green = 0;
        int blue = 0;
        // 设置备选验证码:包括"A-Z","a-z","0-9"
        int size = RandomConf.getRandomChar().length();
        Random rand = new Random();
        for (int i = 0; i < RandomConf.getLen(); i++) {
        	int start = rand.nextInt(size);
        	String tmpStr = RandomConf.getRandomChar().substring(start, start + 1);

        	red = random.nextInt(110);
			green = random.nextInt(50);
			blue = random.nextInt(255);
			g.setColor(new Color(red,green,blue));

			randomCode.append(tmpStr);
        	g.drawString(tmpStr, 13 * i + 6 + rand.nextInt(5), 14 + rand.nextInt(6));
        }

        HttpSession session = request.getSession();
        session.setAttribute("randomImgCode", randomCode.toString());

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", outputStream);

        outputStream.close();
	}


后面附上整个项目代码,直接解压,导入myeclipse即可运行

你可能感兴趣的:(java)