protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.建立一個對象,在記憶體中圖檔(驗證碼的圖檔對象)
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);
String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZqwertyuiopasdfghjklzxcvbnm0123456789";
//生成随機角标
Random ran = new Random();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//擷取字元
char ch = str.charAt(index);//随機字元
//2.3寫驗證碼
g.drawString(ch+"", width/5*i, height/2);
}
//2.4畫幹擾線
g.setColor(Color.GREEN);
//随機生成坐标點
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());
}
再綁定注冊頁面,實作單機圖檔即可換一張的功能。
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/*
分析:
點選超連結或者圖檔,需要換一張
1.給超連結和圖檔綁定單機時間
2.重新設定圖檔的src屬性值
*/
window.onload = function (){
//1.擷取圖檔對象
var img = document.getElementById("checkCode");
//2.綁定單擊事件
img.onclick = function () {
//加時間戳
var date = new Date().getTime(); //擷取毫秒值
img.src = "/day15_response_war_exploded/CheckCodeServlet?" + date;
}
}
</script>
</head>
<body>
<img id = "checkCode" src="/day15_response_war_exploded/CheckCodeServlet" />
<a id="change" href="">看不清換一張</a>
</body>
</html>