controller包下的代码如下
@RequestMapping(value = "yzm")
public void getAdmin(HttpServletRequest request, HttpServletResponse response) {
// 设置响应为图片
response.setContentType("image/jpeg");
//定义画布的宽高
int width = 85;
int height = 30;
//创建画板
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//定义验证码的范围
char word[] = "0123456789abcdefghijklmnopqrstuvwsyz".toCharArray();
//随机选取 创建随机对象
Random r = new Random();
String yzm = "";
//画4次
for (int i = 0; i < 4; i++) {
//设置画笔的颜色 随机一个颜色 rnd.nextInt(256) 随机一个0-255的int
g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
//设置字体
g.setFont(new Font("宋体", Font.BOLD, 35));
//画验证码
String s = word[r.nextInt(word.length)] + "";
yzm += s;
//调整位置
g.drawString(s, i * 20 + 6, 25);
}
request.getSession().setAttribute("yzm", yzm);
System.out.println(yzm);
// 画干扰点
for (int i = 0; i < 50; i++) {
g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
g.drawOval(r.nextInt(width), r.nextInt(height), 1, 2);
}
OutputStream out;
try {
//将画布图片响应给页面 通过流
out = response.getOutputStream();
ImageIO.write(image, "jpeg", out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
前端JS需添加点击事件完成换验证码的操作
<script type="text/javascript">
function changeimg() {
document.getElementById("yzm").setAttribute("src", "yzm?num="+Math.random());
}
</script>
HTML直接就是一个img标签
<img src="yzm" style="width: 85px;height: 30px;" onclick="changeimg()" id="yzm" />