本文實例為大家分享了java制作簡單驗證碼的具體代碼,供大家參考,具體內容如下
在這里我們需要用到java的畫筆工具,所以我們需要導入以下包
import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*"
然后我就使用java腳本來實現一個小小的驗證碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
<%@ page contentType="image/jpeg; charset=utf-8" language="java" import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" pageEncoding="UTF-8"%> <!-- 以上導入awt和awt.image包 --> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html > < head > < base href="<%=basePath%>" rel="external nofollow" > < title >驗證碼</ title > < meta http-equiv = "pragma" content = "no-cache" > < meta http-equiv = "cache-control" content = "no-cache" > < meta http-equiv = "expires" content = "0" > < meta http-equiv = "keywords" content = "keyword1,keyword2,keyword3" > < meta http-equiv = "description" content = "This is my page" > </ head > < body > <%! //獲取隨機顏色 public Color getColor(){ Random random = new Random(); //使用rgb()隨機產生顏色 int r = random.nextInt(256); int g = random.nextInt(256); int b = random.nextInt(256); return new Color(r,g,b); } //獲取隨機數字 產生一個4位數 public String getNum(){ String str = ""; Random random = new Random(); for(int i = 0;i < 4 ;i++){ str += random.nextInt(10); //0-9 } return str; } %> <% /* 清除緩存 */ response.setHeader("pragma", "mo-cache"); response.setHeader("cache-control", "no-cache"); response.setDateHeader("expires", 0); //產生矩形框 BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB); //獲取畫筆工具 Graphics g = image.getGraphics(); //設置矩形框的顏色 g.setColor(new Color(200,200,200)); //設置坐標和寬高 g.fillRect(0, 0, 80, 30); //隨機產生干擾線 for(int i = 0;i < 30 ;i++){ Random random = new Random(); int x = random .nextInt(80); int y = random .nextInt(30); int x1 = random .nextInt(x + 10); int y1 = random .nextInt(y + 10); //設置隨機顏色 g.setColor(getColor()); //畫出來 g.drawLine(x, y, x1, y1); } //字的顏色和數字 g.setFont(new Font("Microsoft YaHei",Font.BOLD,16)); g.setColor(Color.BLACK); //獲取隨機數字 String checkNum = getNum (); //給字拼接空格 StringBuffer sb = new StringBuffer(); for(int i = 0 ;i < checkNum.length();i++){ sb.append(checkNum.charAt(i) + " "); } //畫出數字 g.drawString(sb.toString(), 15, 20); //存入session域中 session.setAttribute("CHECKNUM", checkNum); //例如1010 //將圖像以jpeg的形式通過字節流輸出 ImageIO.write(image, "jpeg", response.getOutputStream()); //清除緩存 out.clear(); //放入body中 out = pageContext .pushBody(); %> </ body > </ html > |
結果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/evan_qb/article/details/78473285