查看: 1315|回复: 0

[Java语言] JAVA验证码工具实例代码

发表于 2018-4-16 08:00:05

工具类:

  1. package com.lhy.web.servlet;
  2. import java.awt.BasicStroke;
  3. import java.awt.Color;
  4. import java.awt.Font;
  5. import java.awt.Graphics2D;
  6. import java.awt.image.BufferedImage;
  7. import java.io.FileNotFoundException;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.OutputStream;
  11. import java.util.Random;
  12. import javax.imageio.ImageIO;
  13. public class VerifyCode {
  14. private int w = 70;//图片长
  15. private int h = 35;//图片宽
  16. private Random r = new Random();//Random类 生成随机数
  17. // 列举验证图片中验证码的字体类型
  18. //{"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
  19. private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
  20. // 验证码可选字符
  21. private String codes="23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
  22. // 背景色
  23. private Color bgColor = new Color(255, 255, 255);
  24. // 验证码上的文本
  25. private String text ;
  26. // 生成随机的颜色
  27. private Color randomColor () {
  28. int red = r.nextInt(150);
  29. int green = r.nextInt(150);
  30. int blue = r.nextInt(150);
  31. return new Color(red, green, blue);
  32. }
  33. // 生成随机的字体
  34. private Font randomFont () {
  35. int index = r.nextInt(fontNames.length);
  36. String fontName = fontNames[index];//生成随机的字体名称
  37. int style = r.nextInt(4);//生成随机的样式, 0(无样式), 1(粗体), 2(斜体), 3(粗体+斜体)
  38. int size = r.nextInt(5) + 24; //生成随机字号, 24 ~ 28
  39. return new Font(fontName, style, size);
  40. }
  41. // 画干扰线
  42. private void drawLine (BufferedImage image) {
  43. int num = 3;//一共画3条
  44. Graphics2D g2 = (Graphics2D)image.getGraphics();
  45. for(int i = 0; i < num; i++) {//生成两个点的坐标,即4个值
  46. int x1 = r.nextInt(w);
  47. int y1 = r.nextInt(h);
  48. int x2 = r.nextInt(w);
  49. int y2 = r.nextInt(h);
  50. g2.setStroke(new BasicStroke(1.5F));
  51. g2.setColor(Color.BLUE); //干扰线是蓝色
  52. g2.drawLine(x1, y1, x2, y2);//画线
  53. }
  54. }
  55. // 随机生成一个字符
  56. private char randomChar () {
  57. int index = r.nextInt(codes.length());
  58. return codes.charAt(index);
  59. }
  60. // 创建BufferedImage
  61. private BufferedImage createImage () {
  62. //宽,高,图片的类型
  63. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  64. Graphics2D g2 = (Graphics2D)image.getGraphics();
  65. g2.setColor(this.bgColor);
  66. g2.fillRect(0, 0, w, h);
  67. return image;
  68. }
  69. // 返回验证码图片上的文本
  70. public String getText () {
  71. return text;
  72. }
  73. // 保存图片到指定的输出流
  74. public static void output (BufferedImage image, OutputStream out)
  75. throws IOException {
  76. ImageIO.write(image, "JPEG", out);
  77. }
  78. // 调用这个方法得到验证码
  79. public BufferedImage getImage () {
  80. BufferedImage image = createImage();//创建图片缓冲区
  81. Graphics2D g2 = (Graphics2D)image.getGraphics();//得到绘制环境
  82. StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本
  83. // 向图片中画4个字符
  84. for(int i = 0; i < 4; i++) {//循环四次,每次生成一个字符
  85. String s = randomChar() + "";//随机生成一个字母
  86. sb.append(s); //把字母添加到sb中
  87. float x = i * 1.0F * w / 4; //设置当前字符的x轴坐标
  88. g2.setFont(randomFont()); //设置随机字体
  89. g2.setColor(randomColor()); //设置随机颜色
  90. g2.drawString(s, x, h-5); //画图
  91. }
  92. this.text = sb.toString(); //把生成的字符串赋给了this.text
  93. drawLine(image); //添加干扰线
  94. return image;
  95. }
  96. public static void main(String[] args) throws FileNotFoundException, IOException {
  97. VerifyCode vc = new VerifyCode();//创建VerifyCode类的对象
  98. BufferedImage bi = vc.getImage();//调用getImge()方法获得一个BufferedImage对象
  99. VerifyCode.output(bi, new FileOutputStream("C:/验证码3.jpg"));//调用静态方法output()方法将图片保存在文件输出流中
  100. System.out.println(vc.getText());//在控制台上打印验证码的文本值
  101. }
  102. }
复制代码

VerifyCodeServlet:

  1. package com.lhy.web.servlet;
  2. import java.awt.image.BufferedImage;
  3. import java.io.IOException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. public class VerifyCodeServlet extends HttpServlet {
  9. public void doGet(HttpServletRequest request, HttpServletResponse response)
  10. throws ServletException, IOException {
  11. /*
  12. * 1. 生成图片
  13. * 2. 保存图片上的文本到session域中
  14. * 3. 把图片响应给客户端
  15. */
  16. VerifyCode vc = new VerifyCode();
  17. BufferedImage image = vc.getImage();
  18. request.getSession().setAttribute("session_vcode", vc.getText());//保存图片上的文本到session域
  19. VerifyCode.output(image, response.getOutputStream());
  20. }
  21. }
复制代码

LoginServlet:

  1. package com.lhy.web.servlet;
  2. import java.io.IOException;
  3. import javax.servlet.RequestDispatcher;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.Cookie;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import javax.servlet.http.HttpSession;
  10. public class LoginServlet extends HttpServlet {
  11. public void doPost(HttpServletRequest request, HttpServletResponse response)
  12. throws ServletException, IOException {
  13. /*
  14. * 校验验证码
  15. * 1. 从session中获取正确的验证码
  16. * 2. 从表单中获取用户填写的验证码
  17. * 3. 进行比较!
  18. * 4. 如果相同,向下运行,否则保存错误信息到request域,转发到login.jsp
  19. */
  20. String sessionCode = (String) request.getSession().getAttribute("session_vcode");
  21. String paramCode = request.getParameter("verifyCode");
  22. if(!paramCode.equalsIgnoreCase(sessionCode)) {
  23. request.setAttribute("msg", "验证码错误!");
  24. request.getRequestDispatcher("/login.jsp").forward(request, response);
  25. return;
  26. }
  27. /*
  28. * 1. 获取表单数据
  29. */
  30. // 处理中文问题
  31. request.setCharacterEncoding("utf-8");
  32. // 获取
  33. String username = request.getParameter("username");
  34. String password = request.getParameter("password");
  35. /*
  36. * 2. 校验用户名和密码是否正确
  37. */
  38. if("itcast".equalsIgnoreCase(username)) {//登录成功
  39. /*
  40. * 附加项:把用户名保存到cookie中,发送给客户端浏览器
  41. * 当再次打开login.jsp时,login.jsp中会读取request中的cookie,把它显示到用户名文本框中
  42. */
  43. Cookie cookie = new Cookie("uname", username);//创建Cookie
  44. cookie.setMaxAge(60*60*24);//设置cookie命长为1天
  45. response.addCookie(cookie);//保存cookie
  46. /*
  47. * 3. 如果成功
  48. * > 保存用户信息到session中
  49. * > 重定向到succ1.jsp
  50. */
  51. HttpSession session = request.getSession();//获取session
  52. session.setAttribute("username", username);//向session域中保存用户名
  53. response.sendRedirect("/Test/succ1.jsp");
  54. } else {//登录失败
  55. /*
  56. * 4. 如果失败
  57. * > 保存错误信息到request域中
  58. * > 转发到login.jsp
  59. */
  60. request.setAttribute("msg", "用户名或密码错误!");
  61. RequestDispatcher qr = request.getRequestDispatcher("/login.jsp");//得到转发器
  62. qr.forward(request, response);//转发
  63. }
  64. }
  65. }
复制代码

login.jsp:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%String path = request.getContextPath();
  3. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  4. %>
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  6. <html>
  7. <head>
  8. <base href="<%=basePath%>" rel="external nofollow" >
  9. <title>My JSP 'login.jsp' starting page</title>
  10. <meta http-equiv="pragma" content="no-cache">
  11. <meta http-equiv="cache-control" content="no-cache">
  12. <meta http-equiv="expires" content="0">
  13. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  14. <meta http-equiv="description" content="This is my page">
  15. <!--
  16. <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
  17. -->
  18. <script type="text/javascript">
  19. function _change() {
  20. /*
  21. 1. 得到img元素
  22. 2. 修改其src
  23. */
  24. var imgEle = document.getElementById("img");
  25. imgEle.src = "<%=basePath%>servlet/VerifyCodeServlet?a=" + new Date().getTime();
  26. }
  27. </script>
  28. </head>
  29. <body>
  30. <%-- 本页面提供登录表单,还要显示错误信息 --%>
  31. <h1>登录</h1>
  32. <%
  33. /*
  34. 读取名为uname的Cookie!
  35. 如果为空显示:""
  36. 如果不为空显示:Cookie的值
  37. */
  38. String uname = "";
  39. Cookie[] cs = request.getCookies();//获取请求中所有的cookie
  40. if(cs != null) {// 如果存在cookie
  41. for(Cookie c : cs) {//循环遍历所有的cookie
  42. if("uname".equals(c.getName())) {//查找名为uname的cookie
  43. uname = c.getValue();//获取这个cookie的值,给uname这个变量
  44. }
  45. }
  46. }
  47. %>
  48. <%
  49. String message = "";
  50. String msg = (String)request.getAttribute("msg");//获取request域中的名为msg的属性
  51. if(msg != null) {
  52. message = msg;
  53. }
  54. %>
  55. <font color="red"><b><%=message %> </b></font>
  56. <form action="servlet/LoginServlet" method="post">
  57. <%-- 把cookie中的用户名显示到用户名文本框中 --%>
  58. 用户名:<input type="text" name="username" value="<%=uname%>"/><br/>
  59. 密 码:<input type="password" name="password"/><br/>
  60. 验证码:<input type="text" name="verifyCode" size="3"/>
  61. <img id="img" src="<%=basePath%>servlet/VerifyCodeServlet"/>
  62. <a href="javascript:_change()" rel="external nofollow" >换一张</a>
  63. <br/>
  64. <input type="submit" value="登录"/>
  65. </form>
  66. </body>
  67. </html>
复制代码

loginsuccess:

  1. <body>
  2. <h1>succ1</h1>
  3. <%
  4. String username = (String)session.getAttribute("username");
  5. if(username == null) {
  6. /*
  7. 1. 向request域中保存错误信息,转发到login.jsp
  8. */
  9. request.setAttribute("msg", "您还没有登录!请先登录!");
  10. request.getRequestDispatcher("/login.jsp").forward(request, response);
  11. return;
  12. }
  13. %>
复制代码

欢迎欢迎,热烈欢迎,欢迎<%=username %>领导指导工作!

  1. </body>
  2. </html>
复制代码

配置文件:

  1. <servlet>
  2. <servlet-name>LoginServlet</servlet-name>
  3. <servlet-class>com.lhy.web.servlet.LoginServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>LoginServlet</servlet-name>
  7. <url-pattern>/servlet/LoginServlet</url-pattern>
  8. </servlet-mapping>
  9. <servlet>
  10. <servlet-name>VerifyCodeServlet</servlet-name>
  11. <servlet-class>com.lhy.web.servlet.VerifyCodeServlet</servlet-class>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>VerifyCodeServlet</servlet-name>
  15. <url-pattern>/servlet/VerifyCodeServlet</url-pattern>
  16. </servlet-mapping>
复制代码

建议:生成验证码的Servlet最好设置成不缓存,这样就不用再页面请求验证码图片的时候加上时间戳了,加上时间戳就是欺骗浏览器防止浏览器读取缓存里的验证码图片,而点击换一张后没反应。 这样的不是很好的一点就是,每次点击换一张,浏览器都会把新获取的图片缓存到本地,而在Servlet里设置不缓存,就不会缓存到本地了。

总结

以上所述是小编给大家介绍的JAVA验证码工具实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对程序员之家网站的支持!



回复

使用道具 举报