画一个验证码
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bd09f7bd44e2dad2160b70588cf62639.png)
创建一个文本word.txt,验证码库
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/57e804e6755d4745c66d71c9a7b9f10a.png)
创建一个前台,目的是为了点击二维码可以切换二维码;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function code(jpg) {
jpg.src = "/web03/responseCode?zz=" + new Date().getTime();
}
</script>
</head>
<body>
<img onclick="code(this)" src="/web03/responseCode" />
</body>
</html>
创建一个Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得word.txt的路径
String realPath = getServletContext().getRealPath("WEB-INF/word.txt");
//创建一个集合
List arrayList = new ArrayList();
//使用字符缓冲流,readLine()读一行的方法
BufferedReader bufferedReader = new BufferedReader(new FileReader(realPath));
String readLine = bufferedReader.readLine();
while (readLine != null) {
arrayList.add(readLine);
readLine = bufferedReader.readLine();
}
// 画一个验证码 随机验证码
int height = 30;
int width = 110;
// 内存中 画一个图片
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 画笔
Graphics graphics = bufferedImage.getGraphics();
// 给图片添加背景颜色
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
// 边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 2, height - 2);
// 写入验证码
// 设置字体
graphics.setFont(new Font("楷体", Font.BOLD, 20));
Random random = new Random();
Graphics2D graphics2D = (Graphics2D) graphics;
//从arrayList集合中随机取出一行数据
String mess = (String) arrayList.get(random.nextInt(arrayList.size()));
graphics2D.setColor(new Color(random.nextInt(255), random.nextInt(255),
random.nextInt(255)));
// 弧度
int jiaodu = random.nextInt(15) - 7;
double theta = jiaodu * Math.PI / 180;
graphics2D.rotate(theta, (width / 6), 20);
graphics2D.drawString(mess, (width / 7), 22);
graphics2D.rotate(-theta, (width / 6), 20);
// 画干扰线
for (int i = 0; i < 5; i++) {
graphics2D.setColor(new Color(random.nextInt(255), random
.nextInt(255), random.nextInt(255)));
graphics2D.drawLine(random.nextInt(width), random.nextInt(height),
random.nextInt(width), random.nextInt(height));
graphics2D.drawOval(random.nextInt(width), random.nextInt(height),
2, 3);
}
// 给客户端响应图片
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}