1:html页面
<body>
<image id="code" src="DemoServlet"></image>
<input type="button" value="看不清,换一张" id="btn" οnclick="changeCode(this)" >
<script type="text/javascript">
function changeCode(obj){
document.getElementById("btn").isDisabled=true;
document.getElementById("code").src='DemoServlet?ts='+new Date().getTime();
}
</script>
</body>
2:后台java代码(servlet doGet方法中
//生成图片中的字符
String str = "abcdefghjklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//创建随机对象
Random rand = new Random();
//设置验证码图片展示的宽高
int width = 100;
int height = 30;
//创建图片缓冲对象
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取出作图对象
Graphics graphics = img.getGraphics();
//设置背景颜色
graphics.setColor(Color.gray);
//设置填充一个矩形
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.black);
//参数1,2是线条起点坐标,3,4是线条终点坐标
graphics.drawLine(5, 10, 100, 25);
graphics.setColor(Color.blue);
graphics.drawLine(10, 30, 100, 30);
graphics.setColor(Color.red);
graphics.drawLine(15, 15, 100, 20);
graphics.setColor(Color.white);
graphics.drawLine(20, 10, 100, 18);
for (int i = 0; i < 4; i++) {
graphics.setColor(Color.black);
int nextInt = rand.nextInt(str.length());
String substring = str.substring(nextInt, nextInt+1);
//填充文字及文字所在的xy坐标的起点
graphics.drawString(substring, width/5*(i+1), 15);
}
//输出
ImageIO.write(img, "jpg", resp.getOutputStream());
通过上边的方法可以派生出加减乘除的验证码:将随机字符全部改为数字(0-9),添加加减乘除符号字符串,
随机获取出数字和符号即可