好记性不如赖笔头……
1、生成验证码
//设置验证码的宽度
int width = 120;
//设置验证码的调度
int height = 30;
//创建对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//创建画笔
Graphics graphics = image.getGraphics();
//设置颜色
graphics.setColor(Color.GREEN);
//填充背景颜色(要除去边框)
graphics.fillRect(1, 1, width-2, height-2);
//设置颜色
graphics.setColor(Color.red);
//画边框
graphics.drawRect(0, 0, width-1, height-1);
//设置颜色
graphics.setColor(Color.BLACK);
//设置字体
graphics.setFont(new Font("黑体", Font.BOLD, 20));
//创建随机数对象
Random random = new Random();
//循环生成四个随机数
for (int i = 0; i < 4; i++) {
//将四个随机数写入到图片中
graphics.drawString(random.nextInt(10)+"", 20*(i+1), 20);
}
//设置颜色
graphics.setColor(Color.PINK);
//设置干扰线数量
for (int i = 0; i < 9; i++) {
//随机生成9条不同位置的干扰线
graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
//将图片以jpg格式输出到resp中
ImageIO.write(image, "jpg", resp.getOutputStream());
2、调用验证码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证码</title>
<script type="text/javascript">
function changeCode(){
//根据ID获取img标签
var code = document.getElementById("checkCode");
//给img标签的src属性重新赋值并发送请求
code.src="/httpServletResponse/index3?timestamp="+new Date().getTime();
}
</script>
</head>
<body>
<form action="#" method="post">
用户名:<input type="text" name="userName"/><br/>
密 码:<input type="password" name="userPwd"/><br/>
验证码:<input type="text" name="code"/><img src="/httpServletResponse/index3" id="checkCode" onclick="changeCode();" ><a href="javascript:changeCode();">换一张</a><br/>
<input type="submit" value="登陆"/>
</form>
</body>
</html>