中文驗證碼因筆畫複雜,提高自動識別難度,增強安全性。
<%@ page pageEncoding="gb2312" contentType="image/jpeg" import="javax.imageio.*,java.util.*,java.awt.image.*,java.awt.*" %>
<%!
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(r, g, b);
}
%>
<%
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 130, height = 30;
String base = "\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u538b\u6162\u53d4\u80cc\u7ec6..."; // 大量中文字
int length = base.length();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(random, 188, 235));
g.fillRect(0, 0, width, height);
String[] fontTypes = {"\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66"};
// 畫干擾字符
g.setColor(getRandColor(random, 180, 199));
g.setFont(new Font("Times New Roman", Font.PLAIN, 14));
for (int i = 0; i < 4; i++) {
g.drawString("@*@*@*@*@*@*@*", 0, 5 * (i + 2));
}
String sRand = "";
for (int i = 0; i < 4; i++) {
int start = random.nextInt(length);
String rand = base.substring(start, start + 1);
sRand += rand;
g.setColor(getRandColor(random, 10, 150));
g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD, 18 + random.nextInt(6)));
g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);
}
session.setAttribute("rand", sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
下文將說明調用方式與亂碼解決。