js
function changeImage(img){
img.src="/service/image/getImage?"+Math.random() //表示 每次访问的URL 都不一样,防止二维码缓存
}
function checkCode(img){
$.ajax({
type: "POST",
url:'/service/image/checkImageCode',
data:{'imageCode':$("#code").val().trim()},
dataType: "json",
success: function(data){
if(data==0){
alert("验证码错误");
changeImage(img);
return false;
}else{
return true;
}
}
}
);
}
jsp页面调用
<label class="col-xs-2 control-label">验证码<span class="required">*</span></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="code"
name="code" value="" placeholder="五位验证码" οnblur="checkCode(captcha)"/>
</div>
<div class="col-sm-5" id="imageCode">
<img id="captcha" src="/service/image/getImage" style="cursor:hand" title="点击刷新图片" οnclick="changeImage(this)">
</div>
java后台方法
public void getImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 画画
String url = request.getRequestURI();
BufferedImage image = new BufferedImage(95, 30,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random r = new Random();
Font font = new Font("Arial", Font.BOLD, 18);
g.setFont(font);
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.fillRect(0, 0, 95, 30);
// 生成一个随机数,并且画到内存映射对象上
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String imageCode = "";
for (int i = 0; i < 5; i++) {
imageCode += str.charAt(r.nextInt(str.length()));
}
HttpSession session = request.getSession();
session.setAttribute("imageCode", imageCode);
g.setColor(new Color(0, 0, 0));
g.drawString(imageCode, 20, 20);
// 加一些干扰线
for (int i = 0; i < 5; i++) {
g.drawLine(r.nextInt(60), r.nextInt(20), r.nextInt(60), r
.nextInt(20));
}
// 2 将图片压缩并输出到客户端
response.setContentType("image/jpeg");
OutputStream ops = response.getOutputStream();
javax.imageio.ImageIO.write(image, "jpeg", ops);
}
@ResponseBody
@RequestMapping(value = "/checkImageCode")
public int checkImageCode(HttpServletRequest request, String imageCode) throws ServletException, IOException {
String code=(String) request.getSession().getAttribute("imageCode");
if (code.equalsIgnoreCase(imageCode))
return 1;
return 0;
}