验证码
验证码的验证是我们登陆网页时经常进行的操作,我也做了一个简单的验证码,包括颜色以及噪线等等
@RequestMapping(value = "/Frame/VerifyCode", method = RequestMethod.GET)
public @ResponseBody ModelAndView VerifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
int codeW = 80;
int codeH = 22;
int fontSize = 16;
// 颜色列表,用于验证码、噪线、噪点
Color[] color = { Color.BLACK, Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.GRAY, Color.YELLOW };
// 字体列表,用于验证码
String[] font = { "Verdana" };
// 验证码的字符集,去掉了一些容易混淆的字符
String[] character = { "2", "3", "4", "5", "6", "8", "9", "a", "b", "d", "e", "f", "h", "k", "m", "n", "r", "x",
"y", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "W", "X",
"Y" };
Random rnd = new Random();
String chkCode[] = new String[4];
// 生成验证码字符串
for (int i = 0; i < 4; i++) {
chkCode[i] = character[rnd.nextInt(character.length)];
}
// 创建画布
BufferedImage image = new BufferedImage(codeW, codeH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Color clr = color[rnd.nextInt(color.length)];
// 设置背景色
g.setColor(Color.DARK_GRAY);
g.setFont(new Font("Verdana",0,26));
g.fillRect(0, 0, codeW, codeH);
// g.setColor(clr);
// 画噪线
for (int i = 0; i < 1; i++) {
int x1 = rnd.nextInt(codeW);
int y1 = rnd.nextInt(codeH);
int x2 = rnd.nextInt(codeW);
int y2 = rnd.nextInt(codeH);
clr = color[rnd.nextInt(color.length)];
g.setColor(clr);
g.drawLine(x1, y1, x2, y2);
}
String codeCheck = "";
// 画验证码字符串
for (int i = 0; i < chkCode.length; i++) {
clr = color[rnd.nextInt(color.length)];
g.setColor(clr);
g.drawString(chkCode[i], 20*i, 20);
codeCheck += chkCode[i];
}
OutputStream out = null;
try {
out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
System.out.println("生成的验证码:code="+chkCode);
httpSession.setAttribute("SESSION_CHECKCODE", codeCheck);
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
还没有评论,来说两句吧...