package cn.figo.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.ArrayList;
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.建立一對象,在記憶體中圖檔(驗證碼圖檔對象)
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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成随機角标
Random ran = new Random();
ArrayList<Character> chars = new ArrayList<Character>();
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);
chars.add(ch);
}
System.out.println(chars);
//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());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
輸出
并且我們可以寫一個簡單的網頁,來實作點選更新驗證碼
<!DOCTYPE html>
<html >
<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();
//浏覽器會緩存圖檔,url不變,圖檔不會變,是以需要加一個date來欺騙浏覽器,實作圖檔的重新整理
img.src = "/servlet_learn/checkCodeServlet?"+date;
}
}
</script>
</head>
<body>
<img id="checkCode" src="/servlet_learn/checkCodeServlet" />
<a id="change" href="" target="_blank" rel="external nofollow" >看不清換一張?</a>
</body>
</html>