封装了一个类,可以比较简单地生成图片验证码:
代码如下:
public class CheckCode {
private final static String CodeMap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private final static String CHECK_CODE = "CHECK_CODE";
private final static int MapLength = 62;
private final static int RGB = 255;
private BufferedImage image = null;
private Graphics graphics = null;
private Random random = null;
private Font font = null;
private int width = 100;
private int height = 30;
private int codeLength = 4;
private StringBuilder builder = null;
public CheckCode() {
init();
}
private void init() {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
graphics = image.getGraphics();
random = new Random();
font = new Font("Times New Roman", Font.BOLD, 18);
graphics.setColor(randColor());
graphics.fillRect(0, 0, width, height);
builder = new StringBuilder();
makeCode();
graphics.dispose();
}
<span style="white-space:pre"> </span>//生成随机颜色
private Color randColor() {
int r = random.nextInt(RGB);
int g = random.nextInt(RGB);
int b = random.nextInt(RGB);
return new Color(r, g, b);
}
private String randStr() {
int index = random.nextInt(MapLength);
return CodeMap.charAt(index) + "";
}
private void makeCode() {
graphics.setFont(font);
for (int i = 0; i < codeLength; i++) {
graphics.setColor(randColor());
String str = randStr();
builder.append(str);
graphics.drawString(str, i * 20 + 10, 20);
}
}
<span style="white-space:pre"> </span>//向客户端输出验证码
public void write(HttpServletRequest request, HttpServletResponse response) {
request.getSession().setAttribute(CHECK_CODE, toString());
try {
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
return;
}
}
<span style="white-space:pre"> </span>//检查请求数据中的验证码是否正确
public static boolean check(HttpServletRequest request) {
String tmp = request.getParameter(CHECK_CODE);
String code = (String) request.getSession().getAttribute(CHECK_CODE);
if (tmp == null || code == null)
return false;
tmp = tmp.trim().toUpperCase();
if (code.equals(tmp))
return true;
return false;
}
@Override
public String toString() {
return builder.toString().toUpperCase();
}
}
可以直接在Servlet里调用:
CheckCode checkCode=new CheckCode();
checkCode.write(request,resopnse);
还要设置ContentType
response.setContentType("image/png");
最好能禁用缓存:
<span style="white-space:pre"> </span>response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
在html中引用Servlet地址:
<img src="Servlet路径" alt="验证码">
这个类是给一个朋友写的,比较仓促,有些地方做得不够严谨,在需要的时候可以稍作修改