网上看了很多jsp实现验证码的例子

大多数实现思路是:

1.在一个java(继承了HttpServlet)类 里面生成验证码,把验证码放到session里(验证用户输入的验证码是否正确时取出)

 

2.根据生成的验证码画出一个有干扰线或干扰点的图片

 

3.在WEB-INF/web.xml中配置 servlet

 

4.在jsp页面调用配置好的servlet,一般是通过<img src="servlet名" id="code"/>调用

 

5.验证的时候提交数据,在本页面或另外一个servlet或者另外一个页面取出 session里存放的验证码,来验证用户的输入

 

这样做的话,用户就会因为验证码输入错误 而重新输入大量的 需要提交的 注册信息或其他信息,效率不高,不适用

 

不这样的话,加载jsp页面时 提前取session里的验证码放到页面

---------------------------------------------------------------------------------------------------

jsp:String code=(String)session.getAttribute("code");
  html:<input type="hide" value="<%=code%>" id="scode">:方便通过js验证

---------------------------------------------------------------------------------------------------

却不可行,第一次执行时取出的cde==null,和我们预期的不一样,更不用说验证了

经过n次baidu,google得知应该是因为加载jsp页面要比加载session快一些

 

那怎么办………………………………

 

怎么办………………

 

怎么办………

 

怎么办…

 

怎么办?

 

 

 

又经过多次搜索,思考,实践,终于想出了个好办法

1.在jsp页面用js生成验证码并保存在变量中,验证码作为参数传到java(继承了HttpServlet)类

 

 

2.根据jsp页面中传过来的验证码画出一个有干扰线或干扰点的图片

 

3.在WEB-INF/web.xml中配置 servlet

 

4.在jsp页面调用配置好的servlet,一般是通过<img src="servlet名" id="code"/>调用

 

5.提交数据之前验证

<form οnsubmit="return validate();"……/>
 
局部刷新验证码:<a href="#" οnclick="javascript:show();return false;">看不清,换一张!</a>-----return false;很重要啊

 

 

不多说了,代码示意如下,希望能对和我一样遇到过这方面问题的有所帮助

java类 CodeServlet

 


[java]  view plain copy


1. package com.zou.servlet;  
2. import java.awt.Color;  
3. import java.awt.Font;  
4. import java.awt.Graphics;  
5. import java.awt.image.BufferedImage;  
6. import java.io.IOException;  
7. import java.util.Random;  
8.   
9. import javax.servlet.ServletException;  
10. import javax.servlet.http.HttpServlet;  
11. import javax.servlet.http.HttpServletRequest;  
12. import javax.servlet.http.HttpServletResponse;  
13. //import javax.servlet.http.HttpSession;  
14. import com.sun.image.codec.jpeg.JPEGCodec;  
15. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
16. @SuppressWarnings("serial")  
17. public class CodeServlet extends HttpServlet {  
18. /**
19.      * 产生验证码图片
20.      */  
21. public void doGet(HttpServletRequest request, HttpServletResponse response)  
22. throws ServletException, IOException {  
23. "image/jpeg");  
24. "Cache-Control", "no-cache");  
25. "Pragma", "No-cache");  
26. "Expires", 0L);  
27. //HttpSession session = request.getSession(true);  
28. int width = 80;  
29. int height = 30;  
30. new BufferedImage(width, height, 1);  
31.         Graphics g = image.getGraphics();  
32. new Random();  
33. 200, 250));  
34. 0, 0, width, height);  
35. new Font("Arial", 0, 25));  
36. 160, 200));  
37. for (int i = 0; i < 155; i++) {  
38. int x = random.nextInt(width + 100);  
39. int y = random.nextInt(height + 100);  
40. int xl = random.nextInt(10);  
41. int yl = random.nextInt(12);  
42.             g.drawOval(x, y, x + xl, y + yl);  
43.         }  
44. "code");  
45. //System.out.println(code);  
46.         String sRand=code;  
47. for (int i = 0; i < sRand.length(); i++) {  
48. //String rand = getRandChar(random.nextInt(36));  
49. 1);  
50. //sRand = sRand + rand;  
51. new Color(20 + random.nextInt(110), 20 + random  
52. 110), 20 + random.nextInt(110)));  
53. 14 * i + 5, 25);  
54.         }  
55. //session.setAttribute("rand", sRand);  
56. //request.setAttribute("rand", sRand);  
57.         g.dispose();  
58.         javax.servlet.ServletOutputStream imageOut = response.getOutputStream();  
59.         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut);  
60.         encoder.encode(image);  
61.     }  
62. private Color getRandColor(int fc, int bc) {  
63. new Random();  
64. if (fc > 255)  
65. 255;  
66. if (bc > 255)  
67. 255;  
68. int r = fc + random.nextInt(bc - fc);  
69. int g = fc + random.nextInt(bc - fc);  
70. int b = fc + random.nextInt(bc - fc);  
71. return new Color(r, g, b);  
72.     }  
73.   
74. /*  private String getRandChar(int randNumber) {
75.         return CHARARRAY[randNumber];
76.     }*/  
77. //private static final String CONTENT_TYPE = "image/jpeg";  
78. /*  private static final String CHARARRAY[] = { "0", "1", "2", "3", "4", "5",
79.             "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i",
80.             "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
81.             "w", "x", "y", "z" };*/  
82.     }


 

web.xml

 


[xhtml]  view plain copy

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <web-app version="2.5"   
3. xmlns="http://java.sun.com/xml/ns/javaee"   
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
6. >  
7. <welcome-file-list>  
8. <welcome-file>index.jsp</welcome-file>  
9. </welcome-file-list>  
10. <servlet>   
11. <servlet-name>code</servlet-name>   
12. <servlet-class>com.zou.servlet.CodeServlet</servlet-class>   
13. </servlet>    
14. <servlet-mapping>  
15. <servlet-name>code</servlet-name>  
16. <url-pattern>/codeServlet</url-pattern>  
17. </servlet-mapping>  
18. </web-app>

 

index.jsp

 


[java]  view plain copy


1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
3. <html>  
4.     <head>  
5.         <title>验证码测试</title>  
6. <mce:script language="javascript" type="text/javascript"><!--  
7. var code ; //在全局 定义验证码  
8. function createCode()  
9. {  
10. "";  
11. 5;//验证码的长度  
12. //所有候选组成验证码的字符,可以用中文  
13. new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');  
14. for(var i=0;i<codeLength;i++)  
15.     {  
16. 60);  
17.         code +=selectChar[charIndex];  
18.     }  
19. return code;  
20. }  
21. function validate ()  
22. {  
23. "vcode").value.toLowerCase();  
24. if(inputCode.length <=0)  
25.     {  
26. "请输入验证码!");  
27. return false;  
28.     }  
29. else if(inputCode != code.toLowerCase())  
30.     {  
31. "验证码输入错误!");  
32. //刷新验证码  
33. return false;  
34.     }  
35. else  
36.     {  
37. "^-^ OK");  
38. return true;  
39.     }  
40. }  
41. function show(){  
42. //显示验证码  
43. "code").src="codeServlet?code="+createCode();  
44. }  
45. window.onload = function() {//document.οnlοad=show();  
46. //页面加载时加载验证码  
47. //这时无论在ie还是在firefox中,js没有加载完,页面的东西是不会被执行的;  
48.     }  
49.       
50. // --></mce:script>          
51.     </head>  
52.     <body>  
53. "return validate();" action="" method="post">  
54.                             <h3>jsp+js+servlet实现验证码</h3><br/>  
55. "text" name=""/><br/>  
56.                             请输入验证码:  
57. "text" id="vcode" style="width: 60;" maxLength="5" />  
58.                                
59. "" id="code"/>  
60. "#" mce_href="#"  
61. "javascript:show();return false;">看不清,换一张!</a>  
62.                             <br/>  
63. "submit"/>  
64.             </form>  
65.     </body>  
66. </html>