您的位置:首页 > 其它

图形验证码实例

2015-10-21 17:08 239 查看
html代码

<div class="white_txta_div_yzm">
<img src="images/login/yanzheng.png" class="white_img">
<input type="text" name="kaptcha" id="r_yanYzm_id" class="white_txta_yzm" placeholder = "图片验证码" maxLength=4>
<img src="captchaImage" width="110px" height="40px" id="kaptchaImage" class="white_btka1" />
</div>


js代码

$(function(){
$('#kaptchaImage').click(function () {//生成验证码
$(this).attr('src', 'login/captchaImage?' + Math.floor(Math.random()*100) ).fadeIn(); });
});


java代码

首先导入kaptcha-2.3.2.jar

/**
* 生成验证码
*/
public String captchaImage() {
ServletOutputStream out = null;
this.getResponse().setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
this.getResponse().setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
this.getResponse().addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
this.getResponse().setHeader("Pragma", "no-cache");
// return a jpeg
this.getResponse().setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
Captcha = capText;
// store the text in the session
this.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
try {
out = this.getResponse().getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//校验验证码
public void checkCaptcha() throws Exception{
String kaptchaExpected = (String)getRequest().getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
if (StringUtils.isNotBlank(kaptchaExpected)) {
if (kaptchaExpected.equals(kaptcha)) {//定义变量kaptcha
setJsonString("true");
} else {
setJsonString("false");
}
} else {
setJsonString("false");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: