前端頁(yè)面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>驗(yàn)證碼</title>
<script>
window.onload = function () {
//1.獲取圖片對(duì)象
var img = document.getElementById("checkCode");
//2.綁定單擊事件
img.onclick = function () {
//加時(shí)間戳
var time = new Date().getTime();
img.src = "/day02/checkCodeServlet?"+time;
}
//獲取a標(biāo)簽對(duì)象
var a = document.getElementById("checkCode2");
a.onclick = function () {
//加時(shí)間戳
var time = new Date().getTime();
img.src = "/day02/checkCodeServlet?"+time;
}
}
</script>
</head>
<body>
<img src="/day02/checkCodeServlet" alt="" id="checkCode">
<a id="checkCode2" href="">看不清例朱,換一張</a>
</body>
</html>
CheckCodeServlet實(shí)現(xiàn)
package cn.day02.web.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.創(chuàng)建對(duì)象,內(nèi)存中的圖片(驗(yàn)證碼圖片對(duì)象)
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.美化圖片
//2.1填充背景色
Graphics g = image.getGraphics();//畫筆對(duì)象
g.setColor(Color.PINK);//設(shè)置畫筆顏色
g.fillRect(0,0,width,height);
//2.2畫邊框
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);
String str = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";
//生成隨機(jī)角標(biāo)
Random random = new Random();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(str.length());
//獲取字符
char ch = str.charAt(index);//隨機(jī)字符
//2.3寫驗(yàn)證碼
g.drawString(ch+"",width/5*i,height/2);
}
//2.4畫干擾線
g.setColor(Color.GREEN);
//隨機(jī)生成左邊點(diǎn)
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1,x2,y1,y2);
}
//3.把圖片輸出頁(yè)面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}