Servlet 实现验证码

广告也精彩

分析

生成图片实现类

ImageServlet

① 定义BufferedImage 对象

② 获得 Graphics 对象

③ 通过 Random 产生随机验证码信息

④ 使用 Graphics 绘制图片

⑤ 记录验证码信息到 session 中

⑥ 使用 ImageIO 输出图片

代码实现

1、新建 web 项目 CheckCode,在 WebContent 下新建 index.jsp

index.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>Insert title here</title>
  8. <script type="text/javascript">
  9.     function reloadCode() {
  10.         //传个时间参数,防止缓存
  11.         var time = new Date().getTime();
  12.         document.getElementById("imageCode").src="<%=request.getContextPath()%>/ImageServlet?d="+time;
  13.     }
  14. </script>
  15. </head>
  16. <body>
  17. <form action="<%=request.getContextPath()%>/LoginServlet" method="post">
  18.     验证码:<input type="text" name="checkcode" />
  19.     <img id="imageCode" src="<%=request.getContextPath()%>/ImageServlet" alt="验证码" />
  20.     <a href="javascript:reloadCode();">看不清楚</a> <br />
  21.     <input type="submit"  value="提交"/>
  22.     </form>
  23. </body>
  24. </html>

2、在 src 下新建 com.liuyanzhao 包,然后分别新建用于动态画图的 ImageServlet 类和用于判断验证码是否正确的 LoginServlet

ImageServlet.java

  1. package com.liuyanzhao;
  2. import java.awt.Color;
  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. /*
  13.  * @author LiuYanzhao
  14.  */
  15. public class ImageServlet extends HttpServlet {
  16.     @Override
  17.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  18.         BufferedImage bi = new BufferedImage(6822, BufferedImage.TYPE_INT_RGB);
  19.         Graphics g = bi.getGraphics();
  20.         Color c = new Color(200,155,255);
  21.         g.setColor(c);
  22.         g.fillRect(006822);
  23.         char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
  24.         Random r = new Random();
  25.         int len = ch.length,index;
  26.         StringBuffer sb = new StringBuffer();
  27.         for(int i=0;i<4;i++) {
  28.             index = r.nextInt(len);
  29.             g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
  30.             g.drawString(ch[index]+"", (i*15)+318);
  31.             sb.append(ch[index]);
  32.         }
  33.         request.getSession().setAttribute("piccode", sb.toString());
  34.         ImageIO.write(bi, "JPG", response.getOutputStream());
  35.     }
  36.     @Override
  37.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  38.         doGet(request, response);
  39.     }
  40. }

LoginServlet.java

  1. package com.liuyanzhao;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. /*
  9.  * @author LiuYanzhao
  10.  */
  11. public class LoginServlet extends HttpServlet{
  12.     @Override
  13.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14.         String piccode = (String)request.getSession().getAttribute("piccode");
  15.         String checkcode = request.getParameter("checkcode");
  16.         checkcode = checkcode.toUpperCase();//不区分大小写
  17.         response.setContentType("text/html;charset=utf-8");
  18.         PrintWriter out = response.getWriter();
  19.         if(piccode.equals(checkcode)) {
  20.             out.println("验证码输入正确");
  21.         } else {
  22.             out.println("验证码输入错误");
  23.         }
  24.         out.flush();
  25.         out.close();
  26.     }
  27.     @Override
  28.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  29.         doPost(request, response);
  30.     }
  31. }

3、在 web.xml 里添加 Servlet 映射

  1. <servlet>
  2.      <servlet-name>ImageServlet</servlet-name>
  3.      <servlet-class>com.liuyanzhao.ImageServlet</servlet-class>
  4.  </servlet>
  5.  <servlet-mapping>
  6.      <!-- 映射为 ImageServlet -->
  7.      <servlet-name>ImageServlet</servlet-name>
  8.      <url-pattern>/ImageServlet</url-pattern>
  9.  </servlet-mapping>
  10.  <servlet>
  11.      <servlet-name>LoginServlet</servlet-name>
  12.      <servlet-class>com.liuyanzhao.LoginServlet</servlet-class>
  13.  </servlet>
  14.  <servlet-mapping>
  15.      <!-- 映射为 IndexServlet -->
  16.      <servlet-name>LoginServlet</servlet-name>
  17.      <url-pattern>/LoginServlet</url-pattern>
  18.  </servlet-mapping>

4、运行 Tomcat 服务器,打开浏览器,访问 http://localhost:8080/CheckCode

效果如下

Servlet 实现验证码

验证码不区分大小写,点击 “看不清楚”可以更换

 

本文链接:https://liuyanzhao.com/5344.html

  • 微信
  • 赶快加我聊天吧
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
言曌
广告也精彩

发表评论

:?::razz::sad::evil::!::smile::oops::grin::eek::shock::???::cool::lol::mad::twisted::roll::wink::idea::arrow::neutral::cry::mrgreen: