package org.hbin.demo;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
*
* 验证码图片
*
*
* 生成验证码图片。可以配置字符字典、在session中存取验证码时使用的KEY、输出图片的类型三个参数。其中输出图片类型支持GIF/gif、JPG/jpg、PNG/png三种格式,默认PNG/png格式。
*
*
* 使用该类时,你可以参考如下方式在web.xml文件中配置Servlet:
*
* <servlet>
* <servlet-name>SimpleCaptchaServlet</servlet-name>
* <servlet-class>org.hbin.demo.SimpleCaptchaServlet</servlet-class>
* <init-param>
* <param-name>map</param-name>
* <param-value>ABCDEFghijkl</param-value>
* </init-param>
* <init-param>
* <param-name>key</param-name>
* <param-value>checkcode</param-value>
* </init-param>
* <init-param>
* <param-name>imageType</param-name>
* <param-value>JPG</param-value>
* </init-param>
* </servlet>
*
* <servlet-mapping>
* <servlet-name>SimpleCaptchaServlet</servlet-name>
* <url-pattern>captcha.image</url-pattern>
* </servlet-mapping>
*
* 在你的html/jsp页面中,你可以这样写:
*
<img alt="看不清楚?点击刷新" src="captcha.image" onclick="" style="cursor: pointer;"/>
*
* @file org/hbin/demo/CheckcodeImageServlet.java
* @author hbin (
cn.binbin@qq.com)
* @version 2.0
* @date 2014/01/12
*/
public class SimpleCaptchaServlet extends HttpServlet
{
private static final long serialVersionUID = 1110943583459995271L;
protected static final String PNG = "image/png";
protected static final String JPG = "image/jpeg";
protected static final String GIF = "image/gif";
/**
* 默认字符字典。
* 删除了人眼不易识别的数字0、1以及字母i、I、l、L、o、O
*/
protected static final String DEFAULT_MAP = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
/**
* 默认的HTTP Content-Type
*/
protected static final String DEFAULT_CONTENT_TYPE = PNG;
/**
* 在session中存取验证码时默认使用的KEY
*/
protected static final String DEFAULT_KEY = "captcha";
/**
* 验证码的默认长度
*/
protected static final int LENGTH = 4;
/**
* 图片默认宽度
*/
protected static final int WIDTH = 100;
/**
* 图片默认高度
*/
protected static final int HEIGHT = 30;
/**
* 随机数生成器
*/
protected final Random r = new Random();
/**
* Log4j's Logger instance.
*/
protected static Logger log = Logger.getLogger(SimpleCaptchaServlet.class);
/**
*
* 字符字典。
*
* 最小长度是3。可以包含大小写字母及数字。
*/
protected String map;
/**
* 在session中存取验证码时使用的KEY
*/
protected String key;
/**
*
* 输出图片的类型
*
* 支持GIF/gif、JPG/jpg、PNG/png三种格式,默认PNG/png格式。
*/
protected String imageType;
/**
* HTTP Content-Type
*/
protected String contentType;
/**
* 随机生成一种颜色
*
* @return 生成的颜色
*/
protected Color generateRandomColor()
{
return new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
}
/**
* 根据指定字符字典,生成指定长度的随机字符串
*
* @param map
* 指定的字符字典
* @param length
* 指定的长度
* @return 指定长度的随机字符串
*/
protected String generateRandomString(String map, int length)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < length; i++)
{
b.append(map.charAt(r.nextInt(map.length())));
}
log.info("Generate a Image: length=" + length + ", string="
+ b.toString());
return b.toString();
}
/**
* Initialize this servlet.
*
* @throws ServletException
*/
public void init() throws ServletException
{
String value = null;
value = getServletConfig().getInitParameter("map");
if (value != null && Pattern.matches("[a-zA-Z0-9]{3,}", value))
{
map = value;
log.info("Initializing map with config value: " + map);
} else
{
map = DEFAULT_MAP;
log.info("Initializing map with default value: " + map);
}
value = getServletConfig().getInitParameter("key");
if (value != null)
{
key = value;
log.info("Initializing key with config value: " + key);
} else
{
key = DEFAULT_KEY;
log.info("Initializing key with default value: " + key);
}
value = getServletConfig().getInitParameter("imageType");
if (value != null && value.toLowerCase().matches("(gif)|(jpg)|(png)"))
{
value = value.toLowerCase();
if ("gif".equals(value))
{
contentType = GIF;
} else if ("jpg".equals(contentType))
{
contentType = JPG;
} else
{
contentType = PNG;
}
log.info("Initializing contentType with config value: "
+ contentType);
} else
{
contentType = DEFAULT_CONTENT_TYPE;
log.info("Initializing contentType with default value: "
+ contentType);
}
}
/**
* Process an HTTP "GET" request.
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doPost(req, resp);
}
/**
* Process an HTTP "POST" request.
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// 设置响应类型为图片
resp.setContentType(contentType);
// 把页面设置为不缓存,禁止浏览器缓存该验证码图像
resp.setHeader("Pragma", "No-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
log.info("Generate an Image: begin ...");
// 生成4位长度的验证码
String captcha = generateRandomString(map, LENGTH);
// 将生成的验证码字符转换成小写并存入session
req.getSession(true).setAttribute(key, captcha.toLowerCase());
log.info("Generate an Image: a String (value:" + captcha.toLowerCase()
+ ") is stored into session with key '" + key + "'.");
// 在内存中创建图象
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
// 创建该图片的绘图对象
Graphics2D g = image.createGraphics();
// 创建一个较浅的颜色作为背景色
Color c = new Color(Integer.parseInt("E6E6E6", 16));
g.setColor(c);
// 填充背景色
g.fillRect(0, 0, WIDTH, HEIGHT);
// 创建一个颜色作为边框颜色
c = new Color(Integer.parseInt("A4A4A4", 16));
g.setColor(c);
// 画边框
g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
// 随机干扰
for (int i = 0; i < 6; i++)
{
g.setColor(generateRandomColor());
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH),
r.nextInt(HEIGHT));
}
// 设置字体
Font font = new Font("Times New Roman", Font.BOLD, 20);
g.setFont(font);
// 将验证码字符绘到图象中
for (int i = 0; i < 4; i++)
{
g.setColor(generateRandomColor());
String s = Character.toString(captcha.charAt(i));
g.drawString(s, 20 * i + 10, HEIGHT - 6);
}
log.info("Generate an Image: write data to Stream ...");
// 获取页面输出流
ServletOutputStream out = resp.getOutputStream();
// 输出图像
// ImageIO.write(image, "jpeg", out);
// 输出图像(该方式比上面的ImageIO更加高效)
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
// 刷新
out.flush();
log.info("Generate an Image: completed.");
}
}