JavaWeb生成随机图片验证码(jsp + servlet)

在使用登陆或者注册功能的时候往往会有图片验证码的功能,那么如何实现图片验证码的功能呢?

1、生成长度可变的的随机字符,这里使用了A-Z 26位大写字母和0-9十位数字,如需其它字符可以自行添加。

public String GenerateCode(int length) {
		int rand;
		char code;
		String randomCode = "";
		Random random = new Random();
		for(int i = 0;i < length;i++) {
			rand = random.nextInt();
			if(rand % 3 == 0) {
				code = (char)('A' + (char)rand % 26);
			}
			else {
				code = (char)('0' + (char)rand % 10);
			}
			randomCode += String.valueOf(code);
		}
		return randomCode;
	}

2、将随机生成的验证码字符写入,并添加噪点、设置验证码的背景颜色,字体样式等等。

//写入随机生成的验证码,并添加噪点
	public BufferedImage Paint(String code ,int width ,int height) {

		int mapWidth = width == 0 ? (int)(code.length() * 16) : width;
		int mapHeight = height ==0 ? (int) 35 :height;
		
		BufferedImage map = new BufferedImage(mapWidth,mapHeight,BufferedImage.TYPE_INT_RGB);
		Graphics graph = map.getGraphics();

		graph.setColor(Color.WHITE);
		graph.fillRect(0, 0, mapWidth, mapHeight);
		//设置字体样式
	    graph.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,(int)(height*0.8)));
		
		//添加噪点
	    Random random = new Random();
		for(int i = 0;i < 50;i++) {
			int x = random.nextInt(map.getWidth());
			int y = random.nextInt(map.getHeight());
			int rgb = GetRandomColor().getRGB();
			map.setRGB(x, y, rgb);
		}
		
		
		//定义每个验证码字符颜色  
        Color[] c = { Color.BLACK, Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.BLACK, Color.DARK_GRAY, Color.LIGHT_GRAY };

        
 
        int fx = 0;
	    for(int i =0;i < code.length();i++) {
	    	int x = random.nextInt(7);   	
	    	graph.setColor(c[x]);
	    	graph.drawString(code.charAt(i) + "", fx, (int)(height * 0.8));	    	
	    	fx+=(width / code.length()) * (Math.random() * 0.3 + 0.8);
	    }
	    graph.dispose();
	    return map;
	}

3、随机生成颜色,以供背景、噪点、字体颜色使用

//生成随机颜色
	public Color GetRandomColor() {
		Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);

	}

4、JSP 页面 

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
  <link href="css/base.css" rel="stylesheet" type="text/css">
  <link href="css/module.css" rel="stylesheet" type="text/css">
  <script src="scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
  <script type="text/javascript" language ="javascript">
	$(function(){
		  //刷新验证码
		  $('#getCode').click(function () {
              $("#getCode").attr("src", "GenerateCodeServlet?method=" + Math.random());
          });
		  //登陆验证数据
		  $("#login").click(function(){
			  
		  });
	});
  </script>
</head>
<body>
    <div class="login">
        <div class="login-main">
            <div class="login-header">
                <em>
                </em>
                <h4>通讯录</h4>
            </div>
            <form method="post">
                <div class="login-area">
                    <div class="login-info">
                        <input autocomplete="off" type="text" id="account" name="account" placeholder="帐号" class="lgn-txt" />
                    </div>
                    <div class="login-info">
                        <input type="password" placeholder="密码" id="password" name="password" class="lgn-txt" />
                    </div>
                    <div>
                        <input type="text" placeholder="验证码" id="code" class="ipt-txt"  style="width:60%; padding: 8px 5px;background-color: #FFF;border: 1px solid #DDD;border-radius: 3px;"/>
                        <a href="javascript:void(0)" style="width:25%"><img src="GenerateCodeServlet?method=image" id="getCode" /></a>
                    </div>                 
                    <div class="login-btn">
                        <input class="lgn-btn" type="button" value="立即登录" id="login" />
                    </div>
                    <div>没有账号?</div>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

5、Servlet,这里我并没有将随机生成的验证码存入 Session,使用该功能时候须将生成的验证码加入Session,然后才可以在登陆的时候进行验证用户输入的是否一致。

package pers.demo.servlet;

import java.io.IOException;

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 pers.demo.service.LoginService;

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

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 LoginService _service = new LoginService();
		 response.setContentType("image/jpeg");
	     response.setDateHeader("expries", -1);
	     response.setHeader("Cache-Control", "no-cache");
	     response.setHeader("Pragma", "no-cache");
	     ImageIO.write(_service.Paint(_service.GenerateCode(4), 120, 39), "jpg", response.getOutputStream());
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

最终实现的效果,点击验证码图片,会刷新验证码

JavaWeb生成随机图片验证码(jsp + servlet)