目录
1、效果
可以不停的变
变
2、代码(有可能不全)
(1)验证码随机字符
import java.awt.*;
import java.util.Random;
//生成验证码随机字符
public class RandomUtils extends org.apache.commons.lang3.RandomUtils {
private static final char[] CODE_SEQ = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j',
'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9'};
private static final char[] NUMBER_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static Random random = new Random();
public static String randomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)]));
}
return sb.toString();
}
public static String randomNumberString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)]));
}
return sb.toString();
}
public static Color randomColor(int fc, int bc) {
int f = fc;
int b = bc;
Random random = new Random();
if (f > 255) {
f = 255;
}
if (b > 255) {
b = 255;
}
return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
}
public static int nextInt(int bound) {
return random.nextInt(bound);
}
}
(2)工具类
public class VerifyCode {
private String code;
private byte[] imgBytes;
private long expireTime;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public byte[] getImgBytes() {
return imgBytes;
}
public void setImgBytes(byte[] imgBytes) {
this.imgBytes = imgBytes;
}
public long getExpireTime() {
return expireTime;
}
public void setExpireTime(long expireTime) {
this.expireTime = expireTime;
}
}
(3)验证码生成接口
import java.io.IOException;
import java.io.OutputStream;
//验证码生成接口
public interface IVerifyCodeGen {
/**
* 生成验证码并返回code,将图片写的os中
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
String generate(int width, int height, OutputStream os) throws IOException;
/**
* 生成验证码对象
*
* @param width
* @param height
* @return
* @throws IOException
*/
VerifyCode generate(int width, int height) throws IOException;
}
(4)Service
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
@Service
public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen {
private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class);
private static final String[] FONT_TYPES = {"\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66"};
private static final int VALICATE_CODE_LENGTH = 4;
/**
* 生成随机字符
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
@Override
public String generate(int width, int height, OutputStream os) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
fillBackground(graphics, width, height);
String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
createCharacter(graphics, randomStr);
graphics.dispose();
//设置JPEG格式
ImageIO.write(image, "JPEG", os);
return randomStr;
}
/**
* 验证码生成
*
* @param width
* @param height
* @return
*/
@Override
public VerifyCode generate(int width, int height) {
VerifyCode verifyCode = null;
try (
//将流的初始化放到这里就不需要手动关闭流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
String code = generate(width, height, baos);
verifyCode = new VerifyCode();
verifyCode.setCode(code);
verifyCode.setImgBytes(baos.toByteArray());
} catch (IOException e) {
logger.error(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
}
/**
* 设置字符颜色大小
*
* @param g
* @param randomStr
*/
private void createCharacter(Graphics g, String randomStr) {
char[] charArray = randomStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
//设置RGB颜色算法参数
g.setColor(new Color(50 + RandomUtils.nextInt(100),
50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
//设置字体大小,类型
g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
//设置x y 坐标
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
}
}
/**
* 设置背景颜色及大小,干扰线
*
* @param graphics
* @param width
* @param height
*/
private static void fillBackground(Graphics graphics, int width, int height) {
// 填充背景
System.setProperty("myColor", "#BBDAEE");
graphics.setColor(Color.getColor("myColor"));
//设置矩形坐标x y 为0
graphics.fillRect(0, 0, width, height);
// 加入干扰线条
for (int i = 0; i < 8; i++) {
//设置随机颜色算法参数
graphics.setColor(RandomUtils.randomColor(40, 150));
Random random = new Random();
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x, y, x1, y1);
}
}
}
(5)LoginController
@Controller
@RequestMapping("login")
@ResponseBody
public class LoginController {
@Resource
private UserService userService;
/**
* 获取验证码controller
* @param response
* @param request
*/
@RequestMapping(value = "verifyCode",method = RequestMethod.GET)
public void verifyCode(HttpServletResponse response, HttpServletRequest request){
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
//设置长宽
try {
VerifyCode verifyCode = iVerifyCodeGen.generate(120, 28);
String code = verifyCode.getCode();
request.getSession().setAttribute("VerifyCode",code);
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
response.setContentType("image/jpeg");
response.getOutputStream().write(verifyCode.getImgBytes());
response.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
(6)前端
<script>
$(function () {
// 页面加载时先请求验证码
getvCode();
});
//登录请求接口
$("#btnLogin").click(function () {
$.ajax({
type:"POST",
url:"/login",
data:$("#myForm").serialize(),
dataType:"json",
success:function (vo) {
if(vo.code === 200){
window.location.href = "/pages/index.html";
}else {
alert(vo.msg);
}
}
});
});
/**
* 获取验证码
* 将验证码写到login.html页面的id = verifyimg 的地方
*/
function getvCode() {
var getTimestamp = new Date().getTime();
let requestUrl = "/login/verifyCode?timestamp="+getTimestamp;
$("#verifyImg").attr('src', requestUrl);
}
/**
* 点击图片刷新验证码
*/
$("#verifyImg").click(function () {
getvCode();
});
</script>