java使用验证码进行登录验证

时间:2023-03-08 22:08:51
java使用验证码进行登录验证

随机生成4位验证码,将生成的4位数字字母数字放入session

private static void outputVerifyCode(HttpServletRequest request,
HttpServletResponse response) throws Exception {
BufferedImage img = new BufferedImage(68, 22, 1); Graphics g = img.getGraphics();
Random r = new Random();
Color c = new Color(200, 150, 255);
g.setColor(c); g.fillRect(0, 0, 68, 22); StringBuffer sb = new StringBuffer();
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
int len = ch.length; for (int i = 0; i < 4; i++) {
int index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.setFont(new Font("Arial", 2, 22));
g.drawString(String.valueOf(ch[index]), i * 15 + 3, 18);
sb.append(ch[index]);
}
request.getSession().setAttribute("verifypic", sb);
ImageIO.write(img, "JPG", response.getOutputStream());
}

比对将登录提交的验证码和session里的验证码同时转为小写并比较

private boolean chekcVerifycode(String inputStr, String correctStr) {
return inputStr.toLowerCase().equals(correctStr.toLowerCase());
}