Servlet生成JSP页面验证码

绝地灬酷狼 2022-08-17 14:19 316阅读 0赞

1、JSP页面调用后台的Servlet页面来生成验证码

JSP页面部分代码,点击验证码图片能够刷新验证码:

  1. function Refresh()
  2. {
  3. document.getElementById("ImgCode").src="servlet/ImgCodeServlet?now="+new Date();
  4. }
  5. <td>
  6. <img id="ImgCode" title="点击更换验证码" style="width:80px;height: 27px;cursor:pointer;padding-left: 9px;padding-top: 0px" οnclick="Refresh()" alt="点击更换验证码" src="servlet/ImgCodeServlet"></img>
  7. </td>

Servlet代码:

  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics;
  4. import java.awt.image.BufferedImage;
  5. import java.io.IOException;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;
  13. public class ImgCodeServlet extends HttpServlet
  14. {
  15. /**
  16. * 注释内容
  17. */
  18. private static final long serialVersionUID = 4596404497597968563L;
  19. /**
  20. * 设置图形验证码中字符串的字体和大小
  21. */
  22. private Font myFont = new Font("Arial Black", Font.PLAIN, 16);
  23. /**
  24. * <生成随机颜色>
  25. * <功能详细描述>
  26. * @param fc
  27. * @param bc
  28. * @return
  29. * @see [类、类#方法、类#成员]
  30. */
  31. Color getRandColor(int fc, int bc)
  32. {
  33. Random random = new Random();
  34. if (fc > 255)
  35. {
  36. fc = 255;
  37. }
  38. if (bc > 255)
  39. {
  40. bc = 255;
  41. }
  42. int r = fc + random.nextInt(bc - fc);
  43. int g = fc + random.nextInt(bc - fc);
  44. int b = fc + random.nextInt(bc - fc);
  45. return new Color(r, g, b);
  46. }
  47. @Override
  48. public void init()
  49. throws ServletException
  50. {
  51. super.init();
  52. }
  53. @Override
  54. protected void service(HttpServletRequest request, HttpServletResponse response)
  55. throws ServletException, IOException
  56. {
  57. //阻止生成的页面内容被缓存,保证每次重新生成随机验证码
  58. response.setHeader("Pragma", "No-cache");
  59. response.setHeader("Cache-Control", "no-cache");
  60. response.setDateHeader("Expires", 0);
  61. response.setContentType("image/jpeg");
  62. //指定生成图形验证码图片的大小
  63. int width = 80, height = 27;
  64. //生成一张新图片
  65. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  66. //在图片中绘制内容
  67. Graphics g = image.getGraphics();
  68. Random random = new Random();
  69. g.setColor(getRandColor(200, 250));
  70. g.fillRect(1, 1, width - 1, height - 1);
  71. g.setColor(new Color(102, 102, 102));
  72. g.drawRect(0, 0, width - 1, height - 1);
  73. g.setFont(myFont);
  74. //随机生成线条,让图片看起来更加杂乱
  75. g.setColor(getRandColor(160, 200));
  76. for (int i = 0; i < 155; i++)
  77. {
  78. int x = random.nextInt(width - 1);// 起点的x坐标
  79. int y = random.nextInt(height - 1);// 起点的y坐标
  80. int x1 = random.nextInt(6) + 1;// x轴偏移量
  81. int y1 = random.nextInt(12) + 1;// y轴偏移量
  82. g.drawLine(x, y, x + x1, y + y1);
  83. }
  84. // 随机生成线条,让图片看起来更加杂乱
  85. for (int i = 0; i < 70; i++)
  86. {
  87. int x = random.nextInt(width - 1);
  88. int y = random.nextInt(height - 1);
  89. int x1 = random.nextInt(12) + 1;
  90. int y1 = random.nextInt(6) + 1;
  91. g.drawLine(x, y, x - x1, y - y1);
  92. }
  93. //该变量用来保存随机字符
  94. String sRand = "";
  95. for (int i = 0; i < 4; i++)
  96. {
  97. String temp = getRandomChar();
  98. sRand += temp;
  99. //将系统生成的随机字符添加到图形验证码上
  100. g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
  101. g.drawString(temp, 15 * i + 10, 15);
  102. }
  103. HttpSession session = request.getSession(true);
  104. session.setAttribute("rand", sRand);
  105. g.dispose();
  106. ImageIO.write(image, "JPEG", response.getOutputStream());
  107. }
  108. /**
  109. * <生成一个随机字符>
  110. * <功能详细描述>
  111. * @return
  112. * @see [类、类#方法、类#成员]
  113. */
  114. private String getRandomChar()
  115. {
  116. //将0~2的小数四舍五入生成整数
  117. int rand = (int)Math.round(Math.random() * 2);
  118. long itmp = 0;
  119. char ctmp = '\u0000';
  120. switch (rand)
  121. {
  122. //生成大写字母
  123. case 1:
  124. itmp = Math.round(Math.random() * 25 + 65);
  125. ctmp = (char)itmp;
  126. return String.valueOf(ctmp);
  127. //生成小写字母
  128. case 2:
  129. itmp = Math.round(Math.random() * 25 + 97);
  130. ctmp = (char)itmp;
  131. return String.valueOf(ctmp);
  132. //生成数字
  133. default:
  134. itmp = Math.round(Math.random() * 9);
  135. return String.valueOf(itmp);
  136. }
  137. }
  138. }

Servlet配置:

  1. <servlet>
  2. <servlet-name>ImgCodeServlet</servlet-name>
  3. <servlet-class>com.query.ImgCodeServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>ImgCodeServlet</servlet-name>
  7. <url-pattern>/servlet/ImgCodeServlet</url-pattern>
  8. </servlet-mapping>

2、登录的Action中来利用Ajax校验 用户名、密码、验证码

Action校验:

  1. public String checkAjaxLogin()
  2. {
  3. Map session = ActionContext.getContext().getSession();
  4. String identifyCode = (String)session.get("rand");
  5. if (identifyCode.toUpperCase().equals(code.toUpperCase()))
  6. {
  7. if (!"admin".equals(userName))
  8. {
  9. //用户名不存在
  10. message = "userName_Error";
  11. }
  12. else if (!"admin".equals(passWord))
  13. {
  14. //用户名或密码错误
  15. message = "userNameandPassWord_Error";
  16. }
  17. else
  18. {
  19. message = "success";
  20. }
  21. }
  22. else
  23. {
  24. //验证码错误
  25. message = "code_error";
  26. }
  27. return SUCCESS;
  28. }

Action配置:

  1. <package name="jqueryAjax-doo" extends="json-default">
  2. <action name="queryAjaxLogin" class="com.actions.query.UseQueryAction" method="checkAjaxLogin">
  3. <result type="json">
  4. <param name="root">message</param>
  5. <param name="noCache">true</param>
  6. </result>
  7. </action>
  8. </package>

登录事件的Ajax验证:

  1. $.ajax({
  2. type:"post",
  3. url:"queryAjaxLogin.action",
  4. data:{"userName":userName,"passWord":passWord,"code":code},
  5. success:function(data)
  6. {
  7. if(data=="code_error")
  8. {
  9. alert("验证码错误。");
  10. }
  11. else if(data=="userName_Error")
  12. {
  13. alert("用户名不存在。");
  14. }
  15. else if(data=="userNameandPassWord_Error")
  16. {
  17. alert("用户名或密码错误。");
  18. }
  19. else
  20. {
  21. window.location="Login.action";
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,316人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jsp使用servlet实现验证

    在进行表单设计中,验证码的增加恰恰可以实现是否为“人为”操作,增加验证码可以防止网站数据库信息的冗杂等... 现在,小编将讲述通过servlet实现验证码: 验证码作为一个