登录界面中验证码的使用
- 第一次页面加载时,就显示出验证码的图片,在HTML中设置好图片的src(访问哪一个action)
- 点击图片时会刷新验证码,刷新时要定义一个函数,重新发送获取验证码的请求(加上时间挫,这样浏览器才会重新发送请求)
- 点击后边的“换一张”时,原理和2中相同(所用的方法也相同)
HTML中代码
<li>
<label for="captcha">验证码:</label>
<span class="bg_text small">
<input type="text" id="captcha" name="captcha" maxLength="7" vld="{required:true}" />
</span>
<img id="captchaImage" src="${path }/user/getImage.do" onclick="changeImage()" class="code" alt="换一张" /><a href="javascript:void(0);" onclick="changeImage()" title="换一张">换一张</a>
</li>
–
js中代码
//当再次点击 时 会 重新发送请求
function changeImage(){
var path = "${path}/user/getImage.do?date="+new Date();
$("#captchaImage").attr("src",path);
}
生成验证码的代码
/**
* 生成 验证码
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/getImage.do")
public void getImage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("#######################生成数字和字母的验证码#######################");
BufferedImage img = new BufferedImage(68, 22,
BufferedImage.TYPE_INT_RGB);
// 得到该图片的绘图对象
Graphics g = img.getGraphics();
Random r = new Random();
Color c = new Color(200, 150, 255);
g.setColor(c);
// 填充整个图片的颜色
g.fillRect(0, 0, 68, 22);
// 向图片中输出数字和字母
StringBuffer sb = new StringBuffer();
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
int index, len = ch.length;
for (int i = 0; i < 4; i++) {
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt
(255)));
g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));
// 输出的 字体和大小
g.drawString("" + ch[index], (i * 15) + 3, 18);
// 写什么数字,在图片 的什么位置画
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(img, "JPG", response.getOutputStream());
}