第一步:生成随机数或者英文
public class VerifyCodeUtils {
private static final Logger logger = LoggerFactory.getLogger(VerifyCodeUtils.class);
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
public static String generateVerifyCode(int verifySize){
String verifyCode = generateVerifyCode(verifySize, VERIFY_CODES);
logger.info("生成的验证码为[{}]",verifyCode);
return verifyCode;
}
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
}
第二步:构建图片
package com.yeex.app.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.yeepay.g3.utils.common.log.Logger;
import com.yeepay.g3.utils.common.log.LoggerFactory;
public class BuildVerifyCodeImg extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(BuildVerifyCodeImg.class);
public static final String SESSION_KEY_SECURITY_CODE = "SecurityCode";
private int strWidth = 60;
private int strHeight = 20;
private int strLength = 4;
private int fontWeight = 3;
private int fontSize = 13;
private String fontName = "Verdana";
private InputStream inputStream;
public void setFontName(String fontName) {
this.fontName = fontName;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
public void setFontWeight(int fontWeight) {
this.fontWeight = fontWeight;
}
/**
* 处理Get请求
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doExecute(req, resp);
}
/**
* 处理Post请求
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doExecute(req, resp);
}
public void doExecute(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/gif");
HttpSession session = request.getSession();
ServletOutputStream vout = response.getOutputStream();
final String verifyCode = VerifyCodeUtils.generateVerifyCode(strLength);
int size = (width - width / 10) / length;
int vlign = (height + size) / 2;
// 创建内存图像
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 创建随机类的实例
Random random = new Random();
// 设定图像背景色(因为是做背景,所以偏淡)
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, width, height);
// 备选字体
String[] fontTypes = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53",
"\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
int fontTypesLength = fontTypes.length;
/*
* // 在图片背景上增加噪点 g.setColor(new Color(255, 255, 255));
* g.setFont(new Font("Times New Roman", Font.PLAIN, 12)); for
* (int i = 0; i < 8; i++) { g.drawString(
* "*********************************************", 0, 5 * (i +
* 2)); }
*/
String sRand = verifyCode;
for (int i = 0; i < length; i++) {
// 设置字体的颜色
g.setColor(getRandColor(random, 10, 150));
// 设置字体
Font f = new Font(
fontTypes[random.nextInt(fontTypesLength)],
Font.BOLD, 22);
g.setFont(f);
// 将此汉字画到图片上
g.drawString(sRand.charAt(i) + "", size * i + size / 8
* (random.nextInt(3) + 2), vlign);
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(vout);
encoder.encode(image);
vout.close();
if (session.getAttribute(SESSION_KEY_SECURITY_CODE) != null)
session.removeAttribute(SESSION_KEY_SECURITY_CODE);
session.setAttribute(SESSION_KEY_SECURITY_CODE, verifyCode);
logger.debug("验证码是:" + verifyCode);
}
private Color getRandColor(Random random, int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(255, 0, 0);
}
boolean refresh = true;
// 图像长度
int width = 65;
// session的存放key
String key = null;
// 图像宽度
int height = 20;
// 字符个数
int length = 4;
// 随机码类型(type,1-字母,2-数字,3-简单汉字,4-随机汉字,允许多种同时使用,如下即表示字母与数字混合)
int mode[] = new int[] { 2 };
public InputStream getInputStream() {
return inputStream;
}
public void setStrLength(int strLength) {
this.strLength = strLength;
}
}
第三步:在web.xml中配置请求servlet
<servlet>
<servlet-name>Code</servlet-name>
<servlet-class>com.yeex.app.util.BuildVerifyCodeImg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Code</servlet-name>
<url-pattern>/verifyCode.jsp</url-pattern>
</servlet-mapping>
第四步:界面请求servlet
<input type="text" name="verifyCode" id="verifyCode" style="padding:0 0;" placeholder="请输入验证码" />
<a href="javascript:void(0);" onclick="refreshCode();" ><img id="code" alt="验证码" src="../verifyCode.jsp"></a>
第五步:刷新图片 js方法
function refreshCode() {
$("#code").attr("src", "../verifyCode.jsp?timestamp=" + Math.random());
}
注意第五步的时候一定要加上math.random 这样在界面图片会及时变化