欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生成验证码

程序员文章站 2022-05-13 16:01:37
...


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.SecureRandom;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("serial")
public class ValidateCodeServlet extends HttpServlet
{
private static Log logger = LogFactory.getLog(ValidateCodeServlet.class);

private static final String CONTENT_TYPE = "image/jpeg";

private static final int WIDTH = 64;

private static final int HEIGHT = 22;

private static final char[] PARAM = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'L', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'};

public ValidateCodeServlet()
{
super();
}

public void destroy()
{
super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(CONTENT_TYPE);

try
{
SecureRandom ran = new SecureRandom();
StringBuilder sb = new StringBuilder();

// 产生验证码
for (int i = 0; i < 4; i++)
{
char temp = PARAM[Math.abs((ran.nextInt()) % 62)];
while (sb.indexOf(String.valueOf(temp)) != -1)
{
temp = PARAM[Math.abs((ran.nextInt()) % 62)];
}
sb.append(temp).append("");
}

// 将验证码保存到Session中
request.getSession().setAttribute(TUSConstant.SESSION_VERIFICODE, sb.toString());

// 输出图片到页面
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)image.getGraphics();
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, WIDTH, HEIGHT);

for (int i = 0; i < 18; i++)
{
g.setColor(new Color(ran.nextInt(100) + 110, ran.nextInt(100) + 110, ran.nextInt(100) + 110));
int x_b = ran.nextInt(WIDTH);
int x_e = ran.nextInt(WIDTH);
int y_b = ran.nextInt(HEIGHT + 1);
int y_e = ran.nextInt(HEIGHT + 1);
g.drawLine(x_b, y_b, x_e, y_e);
}

g.setFont(new Font("System", Font.BOLD, 18));
// g.setColor(new Color(0, 0, 255));
g.setColor(new Color(ran.nextInt(100) + 110, ran.nextInt(100) + 110, ran.nextInt(100) + 110));
g.drawString(sb.toString(), 5, 15);
g.dispose();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(image);
}
catch (Exception ex)
{
logger.error("doPost error.", ex);
}
}
}