总体思路是写一个控制器,在控制器里生成图片验证码,前端html页面直接调用这个控制器生成图片验证码。
controller的代码:
package com.xiao.controller;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("code")
public class CodeController {
private int width = 120; //定义图片的宽
private int height = 50;//定义图片的高
private int codeCount = 4;//定义图片上显示验证码的个数
private int xx = 20;
private int fontHeight = 30;
private int codeY = 30;
char[] ch="ABCDEGHIJKlLMNOPQRSTU0123VWXYZabcde789fghijklmnopqrstuvwxyz456".toCharArray();
@RequestMapping("getCode")
public void getCode(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws
IOException{
//定义图像buffer
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics gd = buffImg.getGraphics();
//创建一个随机数生成器类
Random random = new Random();
gd.setColor(java.awt.Color.WHITE);
gd.fillRect(0, 0, width, height);
//创建字体,字体的大小应该根据图片的高度来定
Font font = new Font("Fixedsys",Font.BOLD,fontHeight);
//设置字体
gd.setFont(font);
//画边框
gd.setColor(java.awt.Color.BLACK);
gd.drawRect(0, 0, width-1, height-1);
//随机产生40条干扰线,图像中的认证码不易被其他程序探测
gd.setColor(java.awt.Color.BLACK);
for(int i = 0;i < 40;i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(20);
int y1 = random.nextInt(20);
gd.drawLine(x, y, x+x1, y+y1);
}
//randomCode用于保存随机产生的验证码,以便用户登录验证
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0,len = ch.length,index;
//随机产生验证码
for(int i = 0;i < codeCount; i++){
index = random.nextInt(len);
char code = ch[index];
/*
// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用随机产生的颜色将验证码绘制到图像中。
*/
gd.setColor(new java.awt.Color(0,0,0));
gd.drawString(code+"", (i + 1) * xx, codeY);
// 将产生的四个随机数组合在一起。
randomCode.append(code);
}
// 将四位数字的验证码保存到Session中。
// System.out.print(randomCode);
session.setAttribute("code", randomCode.toString());
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 将图像输出到Servlet输出流中。
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
前端调用:
<div class="form-group">
<div class="field">
<input id="codeInputId" type="text" class="input" name="code" placeholder="填写右侧的验证码" data-validate="required:请填写右侧的验证码" />
<img id="getImg" onclick="changeImg()" src=<c:url value="/code/getCode"></c:url> width="80" height="32" class="passcode" />
</div>
点击切换图片验证js:
function changeImg() {
var imgSrc = $("#getImg");
var src = imgSrc.attr("src");
imgSrc.attr("src", chgUrl(src));
$('#codeInputId').val("");
}
//时间戳
//为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
function chgUrl(url) {
var timestamp = (new Date()).valueOf();
url = url.substring(0, url.length);
if ((url.indexOf("&") >= 0)) {
url = url + "×tamp=" + timestamp;
} else {
url = url + "?timestamp=" + timestamp;
}
return url;
}