本質:圖片
目的:防止惡意表單註冊
一、基本實現
@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();
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());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
結果如圖:
二、配合 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");
var change = document.getElementById("change");
//2.綁定單擊事件
img.onclick = function(){
//加時間戳,是爲了防止圖片由於瀏覽器優先讀取瀏覽器緩存而不更新
var date = new Date().getTime();
img.src = "/day15/checkCodeServlet?"+date;
}
//
change.onclick = function () {
var time = new Date().getTime();
image.src = "/code?" + time;
}
}
</script>
</head>
<body>
<img id="checkCode" src="/day15/checkCodeServlet" />
<a id="change" href="/code">看不清換一張?</a>
</body>
</html>
這裏爲了達到點擊圖片自動更換的效果,加了個時間戳
image.src = "/code?" + time;
這裏的?和 time
,沒有任何意義,效果是讓瀏覽器認爲這是次新的刷新,不會去讀取瀏覽器緩存
但是這裏也存在個問題,點擊圖片實現自動更改,但是實際上是跳轉到了另外一個註冊碼的頁面,沒有停留在 register.html 頁面,所以點擊文字"看不清,換一張",只會出現一次效果
所以實際上,<a>
標籤實現的是本頁面的一個跳轉,可以用以前學的一個
<a id="change" href="javascript:void(0);">看不清換一張</a>
然後通過 id ,添加事件即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>驗證碼</title>
<script>
window.onload = function () {
var image = document.getElementById("checkCode");
var change = document.getElementById("change");
image.onclick = function () {
var time = new Date().getTime();
image.src = "/code?" + time;
}
change.onclick = function () {
var time = new Date().getTime();
image.src = "/code?" + time;
}
}
</script>
</head>
<body>
<img id="checkCode"src="/code"/>
<a id="change" href="javascript:void(0);">看不清換一張</a>
</body>
</html>