package com.hopetesting.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 newcityman
* @date 2019/9/1 - 20:42
*/
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、创建一个对象,在内存中存放图片(验证码图片对象)
int width=100;
int height=50;
BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
// 2、美化图片
// 2.1、填充背景色
Graphics g = image.getGraphics();
g.setColor(Color.PINK);
g.fillRect(0,0,width,height);
// 2.2、画矩形边框
g.setColor(Color.blue);
g.drawRect(0,0,width-1,height-1);
// 2.3、随机生成角标
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghighjklmnopqrstuvwxyz0123456789";
Random ran = new Random();
// 获取字符
g.setColor(Color.RED);
for (int i = 1; i <=4 ; i++) {
int index = ran.nextInt(str.length());
char c = str.charAt(index);
g.drawString(c+"",width/5*i,height/2);
}
// 2.4 设置干扰线
g.setColor(Color.BLACK);
for(int i=0;i<10;i++){
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
// 3、将图片输送到页面显示
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script>
window.onload = function () {
// 1、获取图片对象
var img =document.getElementById("checkCode");
// 2、绑定事件
img.onclick= function () {
var date = new Date().getTime();
img.src="/day15/checkCode?"+date;
}
}
</script>
</head>
<body>
<img src="/day15/checkCode" id="checkCode">
<a id="change" href="">看不清,换一张</a>
</body>
</html>