原创 java实现登录验证码

原创

java实现登录验证码

java实现登录验证码:用兴趣的同学

    可以参考一下:

VerifyCodeServlet.java类:


 
 
  1. package com.spring.controller;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics2D;
  5. import java.awt.image.BufferedImage;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.ServletOutputStream;
  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 org.springframework.stereotype.Controller;
  15. import org.springframework.web.bind.annotation.RequestMapping;
  16. import org.springframework.web.bind.annotation.RequestMethod;
  17. @Controller
  18. public class VerifyCodeServlet extends HttpServlet {
  19. // 验证码图片的宽度。
  20. private int width = 60;
  21. // 验证码图片的高度。
  22. private int height = 20;
  23. // 验证码字符个数
  24. private int codeCount = 4;
  25. private int x = 0;
  26. // 字体高度
  27. private int fontHeight;
  28. private int codeY;
  29. char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
  30. 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  31. 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  32. /**
  33. * 初始化验证图片属性
  34. */
  35. public void initxuan() throws ServletException {
  36. // 从web.xml中获取初始信息
  37. // 宽度
  38. String strWidth = "80";
  39. // 高度
  40. String strHeight = "30";
  41. // 字符个数
  42. String strCodeCount = "4";
  43. // 将配置的信息转换成数值
  44. try {
  45. if (strWidth != null && strWidth.length() != 0) {
  46. width = Integer.parseInt(strWidth);
  47. }
  48. if (strHeight != null && strHeight.length() != 0) {
  49. height = Integer.parseInt(strHeight);
  50. }
  51. if (strCodeCount != null && strCodeCount.length() != 0) {
  52. codeCount = Integer.parseInt(strCodeCount);
  53. }
  54. } catch (NumberFormatException e) {
  55. }
  56. x = width / (codeCount + 1);
  57. fontHeight = height - 2;
  58. codeY = height - 4;
  59. }
  60. @RequestMapping(value= "xuan/verifyCode",method=RequestMethod.GET)
  61. public void service(HttpServletRequest req, HttpServletResponse resp)
  62. throws ServletException, java.io.IOException {
  63. initxuan();
  64. // 定义图像buffer
  65. BufferedImage buffImg = new BufferedImage(width, height,
  66. BufferedImage.TYPE_INT_RGB);
  67. Graphics2D g = buffImg.createGraphics();
  68. // 创建一个随机数生成器类
  69. Random random = new Random();
  70. // 将图像填充为白色
  71. g.setColor(Color.WHITE);
  72. g.fillRect( 0, 0, width, height);
  73. // 创建字体,字体的大小应该根据图片的高度来定。
  74. Font font = new Font( "Fixedsys", Font.PLAIN, fontHeight);
  75. // 设置字体。
  76. g.setFont(font);
  77. // 画边框。
  78. g.setColor(Color.BLACK);
  79. g.drawRect( 0, 0, width - 1, height - 1);
  80. // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
  81. g.setColor(Color.BLACK);
  82. for ( int i = 0; i < 10; i++) {
  83. int x = random.nextInt(width);
  84. int y = random.nextInt(height);
  85. int xl = random.nextInt( 12);
  86. int yl = random.nextInt( 12);
  87. g.drawLine(x, y, x + xl, y + yl);
  88. }
  89. // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
  90. StringBuffer randomCode = new StringBuffer();
  91. int red = 0, green = 0, blue = 0;
  92. // 随机产生codeCount数字的验证码。
  93. for ( int i = 0; i < codeCount; i++) {
  94. // 得到随机产生的验证码数字。
  95. String strRand = String.valueOf(codeSequence[random.nextInt( 36)]);
  96. // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
  97. red = random.nextInt( 255);
  98. green = random.nextInt( 255);
  99. blue = random.nextInt( 255);
  100. // 用随机产生的颜色将验证码绘制到图像中。
  101. g.setColor( new Color(red, green, blue));
  102. g.drawString(strRand, (i + 1) * x, codeY);
  103. // 将产生的四个随机数组合在一起。
  104. randomCode.append(strRand);
  105. }
  106. // 将四位数字的验证码保存到Session中。
  107. HttpSession session = req.getSession();
  108. session.setAttribute( "validateCode", randomCode.toString());
  109. // 禁止图像缓存。
  110. resp.setHeader( "Pragma", "no-cache");
  111. resp.setHeader( "Cache-Control", "no-cache");
  112. resp.setDateHeader( "Expires", 0);
  113. resp.setContentType( "image/jpeg");
  114. // 将图像输出到Servlet输出流中。
  115. ServletOutputStream sos = resp.getOutputStream();
  116. ImageIO.write(buffImg, "jpeg", sos);
  117. sos.close();
  118. }
  119. }

ResultServlet.java:


 
 
  1. package com.spring.controller;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind. annotation.RequestMapping;
  9. import org.springframework.web.bind. annotation.RequestMethod;
  10. @Controller
  11. public class ResultServlet {
  12. @RequestMapping(value="resultServlet/validateCode",method=RequestMethod.POST)
  13. public void doPost(HttpServletRequest request, HttpServletResponse response)
  14. throws ServletException, IOException {
  15. response.setContentType( "text/html;charset=utf-8");
  16. String validateC = (String) request.getSession().getAttribute( "validateCode");
  17. String veryCode = request.getParameter( "c");
  18. PrintWriter out = response.getWriter();
  19. if(veryCode== null|| "".equals(veryCode)){
  20. out.println( "验证码为空");
  21. } else{
  22. if(validateC.equals(veryCode)){
  23. out.println( "验证码正确");
  24. } else{
  25. out.println( "验证码错误");
  26. }
  27. }
  28. out.flush();
  29. out.close();
  30. }
  31. }

jsp页面:


 
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding= "UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>test verify code </title>
  8. </head>
  9. <body>
  10. <input id="veryCode" name="veryCode" type="text"/>
  11. <img id="imgObj" alt="" src="xuan/verifyCode"/>
  12. <a href="#" οnclick="changeImg()">换一张 </a>
  13. <input type="button" value="验证" οnclick="isRightCode()"/>
  14. <div id="info"> </div>
  15. </body>
  16. </html>
  17. <script type="text/javascript">
  18. function changeImg(){
  19. var imgSrc = $( "#imgObj");
  20. var src = imgSrc.attr( "src");
  21. imgSrc.attr( "src",chgUrl(src));
  22. }
  23. //时间戳
  24. //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
  25. function chgUrl(url){
  26. var timestamp = ( new Date()).valueOf();
  27. urlurl = url.substring( 0, 17);
  28. if((url.indexOf( "&")>= 0)){
  29. urlurl = url + "×tamp=" + timestamp;
  30. } else{
  31. urlurl = url + "?timestamp=" + timestamp;
  32. }
  33. return url;
  34. }
  35. function isRightCode(){
  36. var code = $( "#veryCode").attr( "value");
  37. code = "c=" + code;
  38. $.ajax({
  39. type: "POST",
  40. url: "resultServlet/validateCode",
  41. data:code,
  42. success:callback
  43. });
  44. }
  45. function callback(data){
  46. $( "#info").html(data);
  47. }
  48. </script>



运行效果:



0 个人打赏
文章最后发布于: 2013-10-15 21:14:13
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值