Java 图形验证码是一种使用图片来验证用户身份的方法,它可以有效地防止恶意破解密码。它通常包含一张随机生成的图片,用户必须输入图片中的文字才能登录或注册。
Java 图形验证码是一种使用图片来验证用户身份的方法,它可以有效地防止恶意破解密码。它通常包含一张随机生成的图片,用户必须输入图片中的文字才能登录或注册。
以下是一个 Java 图形验证码的示例代码:
// 生成随机字符串
String randomString = RandomStringUtils.randomAlphanumeric(6);
// 将随机字符串放入session中
session.setAttribute("captcha", randomString);
// 设置响应头
response.setContentType("image/jpeg");
// 生成图片
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
// 设置背景色
graphics.setColor(Color.white);
graphics.fillRect(0, 0, width, height);
// 设置字体
Font font = new Font("Arial", Font.BOLD, 20);
graphics.setFont(font);
// 画边框
graphics.setColor(Color.black);
graphics.drawRect(0, 0, width-1, height-1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
graphics.setColor(Color.gray);
Random random = new Random();
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);
}
// 将生成的随机字符串写入图片
graphics.setColor(Color.black);
graphics.drawString(randomString, 10, 25);
// 将图片输出到页面
ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(81条)