工具類:
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
101
102
|
package com.lhy.web.servlet; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; public class VerifyCode { private int w = 70 ; //圖片長 private int h = 35 ; //圖片寬 private Random r = new Random(); //Random類 生成隨機數 // 列舉驗證圖片中驗證碼的字體類型 //{"宋體", "華文楷體", "黑體", "華文新魏", "華文隸書", "微軟雅黑", "楷體_GB2312"} private String[] fontNames = { "宋體" , "華文楷體" , "黑體" , "微軟雅黑" , "楷體_GB2312" }; // 驗證碼可選字符 private String codes= "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ" ; // 背景色 private Color bgColor = new Color( 255 , 255 , 255 ); // 驗證碼上的文本 private String text ; // 生成隨機的顏色 private Color randomColor () { int red = r.nextInt( 150 ); int green = r.nextInt( 150 ); int blue = r.nextInt( 150 ); return new Color(red, green, blue); } // 生成隨機的字體 private Font randomFont () { int index = r.nextInt(fontNames.length); String fontName = fontNames[index]; //生成隨機的字體名稱 int style = r.nextInt( 4 ); //生成隨機的樣式, 0(無樣式), 1(粗體), 2(斜體), 3(粗體+斜體) int size = r.nextInt( 5 ) + 24 ; //生成隨機字號, 24 ~ 28 return new Font(fontName, style, size); } // 畫干擾線 private void drawLine (BufferedImage image) { int num = 3 ; //一共畫3條 Graphics2D g2 = (Graphics2D)image.getGraphics(); for ( int i = 0 ; i < num; i++) { //生成兩個點的坐標,即4個值 int x1 = r.nextInt(w); int y1 = r.nextInt(h); int x2 = r.nextInt(w); int y2 = r.nextInt(h); g2.setStroke( new BasicStroke( 1 .5F)); g2.setColor(Color.BLUE); //干擾線是藍色 g2.drawLine(x1, y1, x2, y2); //畫線 } } // 隨機生成一個字符 private char randomChar () { int index = r.nextInt(codes.length()); return codes.charAt(index); } // 創建BufferedImage private BufferedImage createImage () { //寬,高,圖片的類型 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setColor( this .bgColor); g2.fillRect( 0 , 0 , w, h); return image; } // 返回驗證碼圖片上的文本 public String getText () { return text; } // 保存圖片到指定的輸出流 public static void output (BufferedImage image, OutputStream out) throws IOException { ImageIO.write(image, "JPEG" , out); } // 調用這個方法得到驗證碼 public BufferedImage getImage () { BufferedImage image = createImage(); //創建圖片緩沖區 Graphics2D g2 = (Graphics2D)image.getGraphics(); //得到繪制環境 StringBuilder sb = new StringBuilder(); //用來裝載生成的驗證碼文本 // 向圖片中畫4個字符 for ( int i = 0 ; i < 4 ; i++) { //循環四次,每次生成一個字符 String s = randomChar() + "" ; //隨機生成一個字母 sb.append(s); //把字母添加到sb中 float x = i * 1 .0F * w / 4 ; //設置當前字符的x軸坐標 g2.setFont(randomFont()); //設置隨機字體 g2.setColor(randomColor()); //設置隨機顏色 g2.drawString(s, x, h- 5 ); //畫圖 } this .text = sb.toString(); //把生成的字符串賦給了this.text drawLine(image); //添加干擾線 return image; } public static void main(String[] args) throws FileNotFoundException, IOException { VerifyCode vc = new VerifyCode(); //創建VerifyCode類的對象 BufferedImage bi = vc.getImage(); //調用getImge()方法獲得一個BufferedImage對象 VerifyCode.output(bi, new FileOutputStream( "C:/驗證碼3.jpg" )); //調用靜態方法output()方法將圖片保存在文件輸出流中 System.out.println(vc.getText()); //在控制臺上打印驗證碼的文本值 } } |
VerifyCodeServlet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package com.lhy.web.servlet; import java.awt.image.BufferedImage; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class VerifyCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. 生成圖片 * 2. 保存圖片上的文本到session域中 * 3. 把圖片響應給客戶端 */ VerifyCode vc = new VerifyCode(); BufferedImage image = vc.getImage(); request.getSession().setAttribute( "session_vcode" , vc.getText()); //保存圖片上的文本到session域 VerifyCode.output(image, response.getOutputStream()); } } |
LoginServlet:
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
|
package com.lhy.web.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 校驗驗證碼 * 1. 從session中獲取正確的驗證碼 * 2. 從表單中獲取用戶填寫的驗證碼 * 3. 進行比較! * 4. 如果相同,向下運行,否則保存錯誤信息到request域,轉發到login.jsp */ String sessionCode = (String) request.getSession().getAttribute("session_vcode"); String paramCode = request.getParameter("verifyCode"); if(!paramCode.equalsIgnoreCase(sessionCode)) { request.setAttribute("msg", "驗證碼錯誤!"); request.getRequestDispatcher("/login.jsp").forward(request, response); return; } /* * 1. 獲取表單數據 */ // 處理中文問題 request.setCharacterEncoding("utf-8"); // 獲取 String username = request.getParameter("username"); String password = request.getParameter("password"); /* * 2. 校驗用戶名和密碼是否正確 */ if("itcast".equalsIgnoreCase(username)) {//登錄成功 /* * 附加項:把用戶名保存到cookie中,發送給客戶端瀏覽器 * 當再次打開login.jsp時,login.jsp中會讀取request中的cookie,把它顯示到用戶名文本框中 */ Cookie cookie = new Cookie("uname", username);//創建Cookie cookie.setMaxAge(60*60*24);//設置cookie命長為1天 response.addCookie(cookie);//保存cookie /* * 3. 如果成功 * > 保存用戶信息到session中 * > 重定向到succ1.jsp */ HttpSession session = request.getSession();//獲取session session.setAttribute("username", username);//向session域中保存用戶名 response.sendRedirect("/Test/succ1.jsp"); } else {//登錄失敗 /* * 4. 如果失敗 * > 保存錯誤信息到request域中 * > 轉發到login.jsp */ request.setAttribute( "msg" , "用戶名或密碼錯誤!" ); RequestDispatcher qr = request.getRequestDispatcher( "/login.jsp" ); //得到轉發器 qr.forward(request, response); //轉發 } } } |
login.jsp:
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
|
<%@ page language= "java" import = "java.util.*" pageEncoding= "UTF-8" %> <%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>My JSP 'login.jsp' starting page</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" > <!-- <link rel= "stylesheet" type= "text/css" href= "styles.css" rel= "external nofollow" > --> <script type= "text/javascript" > function _change() { /* 1. 得到img元素 2. 修改其src */ var imgEle = document.getElementById("img"); imgEle.src = "<%=basePath%>servlet/VerifyCodeServlet?a=" + new Date().getTime(); } </script> </head> <body> <%-- 本頁面提供登錄表單,還要顯示錯誤信息 --%> <h1>登錄</h1> <% /* 讀取名為uname的Cookie! 如果為空顯示:"" 如果不為空顯示:Cookie的值 */ String uname = "" ; Cookie[] cs = request.getCookies(); //獲取請求中所有的cookie if (cs != null ) { // 如果存在cookie for (Cookie c : cs) { //循環遍歷所有的cookie if ( "uname" .equals(c.getName())) { //查找名為uname的cookie uname = c.getValue(); //獲取這個cookie的值,給uname這個變量 } } } %> <% String message = "" ; String msg = (String)request.getAttribute( "msg" ); //獲取request域中的名為msg的屬性 if (msg != null ) { message = msg; } %> <font color= "red" ><b><%=message %> </b></font> <form action= "servlet/LoginServlet" method= "post" > <%-- 把cookie中的用戶名顯示到用戶名文本框中 --%> 用戶名:<input type= "text" name= "username" value= "<%=uname%>" /><br/> 密 碼:<input type= "password" name= "password" /><br/> 驗證碼:<input type= "text" name= "verifyCode" size= "3" /> <img id= "img" src= "<%=basePath%>servlet/VerifyCodeServlet" /> <a href= "javascript:_change()" rel= "external nofollow" >換一張</a> <br/> <input type= "submit" value= "登錄" /> </form> </body> </html> |
loginsuccess:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<body> <h1>succ1</h1> <% String username = (String)session.getAttribute( "username" ); if (username == null ) { /* 1. 向request域中保存錯誤信息,轉發到login.jsp */ request.setAttribute( "msg" , "您還沒有登錄!請先登錄!" ); request.getRequestDispatcher( "/login.jsp" ).forward(request, response); return ; } %> |
歡迎歡迎,熱烈歡迎,歡迎<%=username %>
領導指導工作!
1
2
|
</body> </html> |
配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet- class >com.lhy.web.servlet.LoginServlet</servlet- class > </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet- class >com.lhy.web.servlet.VerifyCodeServlet</servlet- class > </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/servlet/VerifyCodeServlet</url-pattern> </servlet-mapping> |
建議:生成驗證碼的Servlet最好設置成不緩存,這樣就不用再頁面請求驗證碼圖片的時候加上時間戳了,加上時間戳就是欺騙瀏覽器防止瀏覽器讀取緩存里的驗證碼圖片,而點擊換一張后沒反應。 這樣的不是很好的一點就是,每次點擊換一張,瀏覽器都會把新獲取的圖片緩存到本地,而在Servlet里設置不緩存,就不會緩存到本地了。
總結
以上所述是小編給大家介紹的JAVA驗證碼工具實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/lihaoyang/p/7131512.html