话不多说上代码:
首先登场的是获取验证码的工具类,工具类返回的是一个map对象,key是生成的验证码字符,value是图片缓冲对象。
package com.soft.util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @ClassName CodeUtil
* @Description: TODO
* @Author admin
* @Date 2019/11/14 上午 11:09
* @Version V1.0
**/
public class CodeUtil {
/**
* 生成验证码图片
* @param width 图片宽度,默认:130
* @param height 图片高度,默认:40
* @param count 验证码字符个数,默认:4
* @return Map<String, BufferedImage> 键:生成的验证码;值:图片缓冲对象
* @throws Exception
*/
public static Map<String, BufferedImage> getCode(int width, int height, int count) {
// 定义图片的宽高
width = width == 0 ? 130 : width;
height = height == 0 ? 40 : height;
// 验证码的个数
count = count == 0 ? 4 : count;
// 字符库
char[] codes = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0'};
// 图片缓冲区,定义宽高和颜色的编码
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取画板
Graphics graphics = bi.getGraphics();
// 设置颜色
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
// 从字符库中获取内容
Random random = new Random();
// 存储验证码
StringBuffer sb = new StringBuffer();
// 循环获取随机的字符
for(int i = 1; i <= count; i++){
// 随机数
int temp = random.nextInt(codes.length);
// 从字符库中获取字符
String code = codes[temp] + "";
sb.append(code);
// 设置画笔颜色
graphics.setColor(new Color(getRandomColor(), getRandomColor(), getRandomColor()));
// 设置字体样式
Font font = new Font("微软雅黑", Font.ITALIC, height / 2 + 5);
graphics.setFont(font);
// 把字符画到画布上
graphics.drawString(code, width / (count + 2) * i, height / 2 + 5);
}
// 线条干扰项
// 设置画笔颜色
graphics.setColor(new Color(getRandomColor(), getRandomColor(), getRandomColor()));
// 画线
graphics.drawLine(10, 10, 120, 30);
graphics.drawLine(10, 30, 120, 10);
// 随机麻点干扰项
for(int j = 0; j < 150; j++){
// 设置画笔颜色
graphics.setColor(Color.RED);
int x = random.nextInt(width);
int y = random.nextInt(height);
// 画线
graphics.drawLine(x, y, x, y);
}
Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
map.put(sb.toString(), bi);
return map;
}
/**
* 随机生成颜色代码,范围是0-255的rgb颜色
* @return
*/
public static int getRandomColor(){
return new Random().nextInt(255);
}
}
第二个上场的是使用方,这里使用Servlet写了一个小案例,把验证码加载到浏览器
package com.soft.servlet;
import com.soft.util.CodeUtil;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
/**
* @ClassName GetCodeServlet
* @Description: TODO
* @Author admin
* @Date 2019/11/14 上午 10:21
* @Version V1.0
**/
@WebServlet("/getCode")
public class GetCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 通过工具类获取验证码map,图片的宽高可以从前台页面获取
Map<String, BufferedImage> code = CodeUtil.getCode(130, 40, 4);
// 遍历map
Iterator<String> iterator = code.keySet().iterator();
if(iterator.hasNext()){
// 获取key
String key = iterator.next();
// 把key存储到Session中便于登录时获取校验
req.getSession().setAttribute("yzmCode", key);
// 通过key获取字符缓冲对象,写入浏览器输出对象
ImageIO.write(code.get(key), "JPEG", resp.getOutputStream());
}
}
}
第三位上场的是jsp页面,用于展示验证码图片
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<meta charset="UTF-8">
<link href="${pageContext.request.contextPath}/css/index.css" type="text/css" rel="stylesheet">
</head>
<body>
<div class="main">
<form action="${pageContext.request.contextPath}/login" method="post">
<input type="text" name="sno" placeholder="请输入账号" value="1000">
<input type="password" name="pass" placeholder="请输入密码" value="000000">
<input type="text" name="code" placeholder="请输入验证码" value="" class="yzm"><img src="${pageContext.request.contextPath}/getCode" οnclick="changeCode(this)" class="yzmImg">
<input type="submit" value="登录"/>
<input type="button" value="注册" οnclick="location.href='regist.jsp'"/>
<span class="msg">${msg}</span>
</form>
</div>
</body>
<script>
function changeCode(obj){
obj.src = "${pageContext.request.contextPath}/getCode?time=" + new Date().getTime();
}
</script>
</html>
最后登场的是效果图,点击验证码图片可以切换验证码。