java语言实现登录验证码功能

雨点打透心脏的1/2处 2022-05-10 14:04 365阅读 0赞

先上效果。

70

生成验证码后端逻辑

  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics2D;
  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.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RequestMethod;
  14. @Controller
  15. @RequestMapping("/verificationCode")
  16. public class VerifyCodeController {
  17. private static final long serialVersionUID = 1L;
  18. /**
  19. * 这里用作存入session的名称
  20. */
  21. private static final String SESSION_KEY_OF_RAND_CODE = "randCode";
  22. /**
  23. *
  24. */
  25. private static final int count = 200;
  26. /**
  27. * 定义图形大小(宽)
  28. */
  29. private static final int width = 105;
  30. /**
  31. * 定义图形大小(高)
  32. */
  33. private static final int height = 35;
  34. /**
  35. * 干扰线的长度=1.414*lineWidth
  36. */
  37. private static final int lineWidth = 1;
  38. @RequestMapping(value= "/generate", method={ RequestMethod.POST,RequestMethod.GET })
  39. public void VerificationCode( HttpServletRequest request,
  40. HttpServletResponse response) throws ServletException,
  41. IOException {
  42. // 设置页面不缓存
  43. response.setHeader("Pragma", "No-cache");
  44. response.setHeader("Cache-Control", "no-cache");
  45. response.setDateHeader("Expires", 0);
  46. // response.setContentType("image/png");
  47. // 在内存中创建图象
  48. final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  49. // 获取图形上下文
  50. final Graphics2D graphics = (Graphics2D) image.getGraphics();
  51. // 设定背景颜色
  52. graphics.setColor(Color.WHITE); // ---1.Color.WHITE为白色
  53. graphics.fillRect(0, 0, width, height);//填充衍射
  54. // 设定边框颜色
  55. //graphics.setColor(getRandColor(100, 200)); // ---2.这是以数字型来设置颜色,颜色模式是指使用三种基色:红、绿、蓝,通过三种颜色的调整得出其它各种颜色,这三种基色的值范围为0~255
  56. graphics.drawRect(0, 0, width - 1, height - 1);
  57. final Random random = new Random();
  58. // 随机产生干扰线,使图象中的认证码不易被其它程序探测到
  59. for (int i = 0; i < count; i++) {
  60. graphics.setColor(getRandColor(150, 200)); // ---3.
  61. final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内
  62. final int y = random.nextInt(height - lineWidth - 1) + 1;
  63. final int xl = random.nextInt(lineWidth);
  64. final int yl = random.nextInt(lineWidth);
  65. graphics.drawLine(x, y, x + xl, y + yl);
  66. }
  67. // 取随机产生的认证码(4位数字)
  68. final String resultCode = exctractRandCode();
  69. for (int i = 0; i < resultCode.length(); i++) {
  70. int num=(int)(Math.random()*4+1);
  71. switch (num) {
  72. case 1:
  73. graphics.setColor(Color.green);
  74. break;
  75. case 2:
  76. graphics.setColor(Color.black);
  77. break;
  78. case 3:
  79. graphics.setColor(Color.blue);
  80. break;
  81. case 4:
  82. graphics.setColor(Color.red);
  83. break;
  84. default:
  85. graphics.setColor(Color.green);
  86. break;
  87. }
  88. graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
  89. // 设置字符,字符间距,上边距
  90. //System.out.print(resultCode.charAt(i));
  91. graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
  92. }
  93. // System.out.println("直接输出:"+resultCode);
  94. // 将认证码存入SESSION
  95. request.getSession().setAttribute(SESSION_KEY_OF_RAND_CODE, resultCode);
  96. // 图象生效
  97. graphics.dispose();
  98. // 输出图象到页面
  99. ImageIO.write(image, "JPEG", response.getOutputStream());
  100. }
  101. /**
  102. * @return 随机码
  103. */
  104. private String exctractRandCode() {
  105. int randCodeLength = 4;
  106. return RandCodeImageEnum.ALL_CHAR.generateStr(randCodeLength);
  107. }
  108. /**
  109. * 描述:根据给定的数字生成不同的颜色
  110. * @param 这是以数字型来设置颜色,颜色模式是指使用三种基色:红、绿、蓝,通过三种颜色的调整得出其它各种颜色,这三种基色的值范围为0~255
  111. * @param 这是以数字型来设置颜色,颜色模式是指使用三种基色:红、绿、蓝,通过三种颜色的调整得出其它各种颜色,这三种基色的值范围为0~255
  112. * @return 描述:返回颜色
  113. */
  114. private Color getRandColor(int fc, int bc) { // 取得给定范围随机颜色
  115. final Random random = new Random();
  116. if (fc > 255) {
  117. fc = 255;
  118. }
  119. if (bc > 255) {
  120. bc = 255;
  121. }
  122. final int r = fc + random.nextInt(bc - fc);
  123. final int g = fc + random.nextInt(bc - fc);
  124. final int b = fc + random.nextInt(bc - fc);
  125. return new Color(r, g, b);
  126. }
  127. /**
  128. * 验证码辅助类
  129. */
  130. enum RandCodeImageEnum {
  131. /**
  132. * 混合字符串
  133. */
  134. ALL_CHAR("0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), // 去除小写的l和o这个两个不容易区分的字符;
  135. /**
  136. * 字符
  137. */
  138. LETTER_CHAR("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"),
  139. /**
  140. * 小写字母
  141. */
  142. LOWER_CHAR("abcdefghijklmnopqrstuvwxyz"),
  143. /**
  144. * 数字
  145. */
  146. NUMBER_CHAR("0123456789"),
  147. /**
  148. * 大写字符
  149. */
  150. UPPER_CHAR("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  151. /**
  152. * 待生成的字符串
  153. */
  154. private String charStr;
  155. /**
  156. * @param charStr
  157. */
  158. private RandCodeImageEnum(final String charStr) {
  159. this.charStr = charStr;
  160. }
  161. /**
  162. * 生产随机验证码
  163. *
  164. * @param codeLength
  165. * 验证码的长度
  166. * @return 验证码
  167. */
  168. public String generateStr(final int codeLength) {
  169. final StringBuffer sb = new StringBuffer();
  170. final Random random = new Random();
  171. final String sourseStr = getCharStr();
  172. for (int i = 0; i < codeLength; i++) {
  173. sb.append(sourseStr.charAt(random.nextInt(sourseStr.length())));
  174. }
  175. return sb.toString();
  176. }
  177. /**
  178. * @return the {@link #charStr}
  179. */
  180. public String getCharStr() {
  181. return charStr;
  182. }
  183. }
  184. }

前端代码:

  1. function login(){
  2. //window.location.href = "index.jsp";
  3. var code= $("#verifyCode").val();
  4. var name = $("#username").val();
  5. var pas = $("#pas").val();
  6. if(name==""||pas==""){
  7. alert("用户名或密码不能为空!");
  8. return ;
  9. }
  10. if(code==""){
  11. alert("验证码不能为空!");
  12. return ;
  13. }
  14. $.ajax({
  15. type:'post',
  16. url:'../rest/auth/login',
  17. data:{"name":name,"pas":pas,"code":code},
  18. success:function(data){//返回json结果
  19. if(data==1){//登录成功
  20. window.location.href = "index2.jsp";
  21. }
  22. var rad = Math.floor(Math.random() * Math.pow(10, 8));
  23. var path="<%=basePath%>";
  24. if(data==0){
  25. alert("验证码错误!");
  26. $("#randCodeImage").attr("src", path+"xtts/bpm/rest/verificationCode/generate?uuuy="+rad);
  27. $("#VerificationCode").val("").focus(); // 清空并获得焦点
  28. }
  29. if(data==-1){
  30. alert("账号或密码错误!");
  31. $("#randCodeImage").attr("src", path+"xtts/bpm/rest/verificationCode/generate?uuuy="+rad);
  32. $("#username").focus(); // 清空并获得焦点
  33. }
  34. }
  35. });
  36. }
  37. /*更换验证码*/
  38. function changeCode(){
  39. var rad = Math.floor(Math.random() * Math.pow(10, 8));
  40. var path="<%=basePath%>";
  41. //uuuy是随便写的一个参数名称,后端不会做处理,作用是避免浏览器读取缓存的链接
  42. $("#randCodeImage").attr("src", path+"xtts/bpm/rest/verificationCode/generate?uuuy="+rad);
  43. }

登录操作controller层代码。登录前先判断验证码是否输入错误。

  1. HttpSession session = request.getSession();
  2. String sessionCode=session.getAttribute("randCode")==null?"":session.getAttribute("randCode").toString();
  3. if(!sessionCode.equalsIgnoreCase(code)){//验证码错误
  4. return 0;
  5. }

end~

发表评论

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

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

相关阅读

    相关 javaJava验证功能实现

    一、前言       验证码可以说在我们生活中已经非常普遍了,任何一个网站,任何一个App都会有这个功能,但是为啥要有这个呢?如何做才能做出来呢?下面小编会带领大家一起用