Java实现图形验证码功能
1、首先根据随机数生成图片,我们先生成验证码,创建ValidateCode类,包含code和expireTime,即验证码的数字和失效时间。创建ImageCode类继承ValidateCode。


2、接下来我们创建一个生成验证码的方法。
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) {
ImageCode imageCode = createImageCode(request);
}

3、接下来我来写createImageCode方法。
/**
* 生成验证码
* @param request
* @return
*/
private ImageCode createImageCode(HttpServletRequest request) {
int width = 67;
int height = 23;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
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);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
// 60秒的失效时间
return new ImageCode(image, sRand, 60);
}
/**
* 生成随机背景条纹
*
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
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);
}

4、将随机数存到session中。
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
sessionStrategy.setAttribute(new ServletWebRequest(request),
SESSION_KEY, imageCode);

5、再将生成的图片写到接口的响应中。
ImageIO.write(imageCode.getImage(), "JPEG",
response.getOutputStream());
这个方法会抛出IO异常,我们继续将异常抛出即可。

6、最后我们再来介绍一下验证码校验的功能,这个功能通过过滤器Filter来实现。我们创建ValidateCodeFilter过滤器,在doFilterInternal方法中处理验证码的校验。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:86
阅读量:118
阅读量:99
阅读量:108
阅读量:108