自己的Servlet代码
/**
* 写一个关于验证码的更换小案例
*/
//定义好图片的宽度和高度
int width=100;
int height=50;
//首先要创建一个对象,可以在内存里面画图对象(相当于验证码的图片)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //这里面应该有三个参数, int width(图片的宽度) int height(图片的高度) P(图片的类型)
//然后就把画图对象美化成验证码的样子
Graphics graphics = image.getGraphics(); //画笔对象 可以画画的
graphics.setColor(java.awt.Color.PINK);//设置背景色
graphics.fillRect(0,0,width,height); // 画出一个图形
//花边框
graphics.setColor(java.awt.Color.BLUE);
graphics.drawRect(0,0,width-1,height-1);
//开始写验证码里面的字母.
String string = "ABCDEFGHIZKLMNOPQRSTUVWSYZabcdefghigklmnopqrstuvwsyz0123456789";
//生成一个随机的位置
Random random = new Random();
//几个字母就循环几次
for (int i = 1; i <= 4; i++) {
int index = random.nextInt(string.length());
//获取一个随机字符
char charAt = string.charAt(index);
graphics.drawString(String.valueOf(charAt),width/5*i,height/2);
}
//画出来干扰线
graphics.setColor(java.awt.Color.CYAN);
for (int i =0;i<10;i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,x2,y1,y2);
}
//把美化的图输出到验证码
ImageIO.write(image, "jpg", response.getOutputStream()); //它可以把内存的图片写到任意的地方去
}
然后Html页面的代码 ,通过Jquery实现的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script>
$(function () {
$("#imgs").click(function () {
var date=new Date().getTime();
$("#imgs").prop("src", "/Java_Web/Image_Update?" + date);
});
$("#hre").click(function () {
var date=new Date().getTime();
$("#imgs").prop("src", "/Java_Web/Image_Update?" + date);
});
});
</script>
</head>
<body>
<img id="imgs" src="/Java_Web/Image_Update">
<a id="hre" href="#">看不清楚,换一张?</a>
<input type="text">
</body>
</html>