package cn.kkforhai.web.servlet;
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.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* @author KuKaFei.Hai
* @date 2020/5/24 : 17:24
*/
@WebServlet("/VrificationCode")
public class VrificationCode extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.定义验证码的长,宽
int width = 100;
int height = 50;
//2.创建一个对象,在内存中画图(验证码图像)
BufferedImage vriImageCode = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//3.美化图片
//3.1 获取画笔对象
Graphics pen = vriImageCode.getGraphics();
//3.2 用画笔颜色
pen.setColor(Color.pink);
//3.3 用画笔填充背景色
pen.fillRect(0, 0, width, height);
//3.4 重新设置画颜色,用来画边框
pen.setColor(Color.blue);
//3.5 画边框
pen.drawRect(0, 0, width - 1, height - 1);
//4 生成 4个随机的字符,并写入图片中
//4.1 定义字符串
String strCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//4.2 生成随机坐标并取值
Random ranNum = new Random();
//4.3 循环4次
for (int i = 1; i <= 4; i++) {
//生成随机数角标
int index = ranNum.nextInt(strCode.length());
//获取字符
char indexChar = strCode.charAt(index);
//写入图片
pen.drawString(String.valueOf(indexChar) + " ", width / 5 * i, height / 2);
}
//5 画干扰线
//5.1设置画笔颜色
pen.setColor(Color.green);
for (int i = 0; i <= 4; i++) {
//5.2 随机设置每条线起点,终点,坐标,
int x1 = ranNum.nextInt(width);
int y1 = ranNum.nextInt(height);
int x2 = ranNum.nextInt(width);
int y2 = ranNum.nextInt(height);
//画线
pen.drawLine(x1,y1,x2,y2);
}
//6.将图片输出到展示的页面
ImageIO.write(vriImageCode, "jpg", resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
页面引用:
<script>
window.onload =function () {
//网页加载完后,获取图片对象
let img =document.getElementById("checkCode");
// 梆定单击事件
img.onclick =function () {
//获取时间
let time = new Date().getTime();
img.src ="${pageContext.request.contextPath}/VrificationCode?"+time;
};
let el_a = document.getElementById("change");
el_a.onclick=function () {
let img =document.getElementById("checkCode");
}
img.onclick =function () {
//获取时间
let time = new Date().getTime();
img.src ="${pageContext.request.contextPath}/VrificationCode?"+time;
}
}
</script>