方法1:kaptcha开源组件。

  1. 导入maven依赖
<!--  引入kaptcha依赖  -->
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
   <groupId>com.github.penggle</groupId>
   <artifactId>kaptcha</artifactId>
   <version>2.3.2</version>
</dependency>
  1. index.jsp页面
<form action="check.jsp">

   <div>
      <label>验证码</label>
      <input 
         required name="VerificationCode" 
         type="text" 
         placeholder="请输入验证码" 
         autocomplete="off" 
      />
   </div>

   <div>
      <img alt="验证码" id="imageCode" src="randomCode.jpg" />
      <button onclick="reload()">看不清?</a>
   </div>

   <div>
      <button type="submit">进行验证</button>
   </div>

</form>

<script type="text/javascript">
   function reload() {
      document.getElementById("imageCode").src = "randomCode.jpg";
   }
</script>
  1. check.jsp页面
<body>
   <%
      // 验证码校验
      String k = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
      String str = request.getParameter("VerificationCode");
      String msg;
      if(k.equalsIgnoreCase(str)) {
         msg = "验证成功";
      } else {
         msg = "验证失败";
      }
   %>
   <p><%=msg%></p>
</body>

方法2:servlet手动实现。

  1. 验证码生成
public class ImageServlet extends HttpServlet {
   public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
      BufferedImage img = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
      // 创建画布
      Graphics canvas = img.getGraphics();
      // 初始化颜色
      Color color = new Color(200,150,255);
      canvas.setColor(color);
      canvas.fillRect(0,0,68,22);

      // 验证码中可能出现的字符
      char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
      // 初始化随机
      Random random = new Random();
      int len = ch.length;
      // 将生成出来的验证码缓存成字符串,方便传到session中进行验证
      StringBuffer stringBuffer = new StringBuffer();
      for(int i = 0; i < 4; i++) {
            int index = random.nextInt(len);
            // 颜色随机
            canvas.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
            canvas.drawString(ch[index] + "", (i * 15) + 3, 18);
            // 缓存验证码文字
            stringBuffer.append(ch[index]);
      }
      // 将验证码传入session
      request.getSession().setAttribute("picCode", stringBuffer.toString());
      // 展示验证码
      ImageIO.write(img, "JPG", response.getOutputStream());
   }
}
  1. 验证码校验
public class CheckServlet extends HttpServlet {
   public void check(HttpServletRequest request, HttpServletResponse response) throws IOException {
      // 从session获取生成出来的验证码
      String picCode = (String)request.getSession().getAttribute("picCode");
      // 通过http协议从前端获取用户输入的验证码
      String VerificationCode = request.getParameter("VerificationCode");
      // 设置输出的编码格式
      response.setContentType("text/html;charset=UTF-8");
      // 初始化输出流
      PrintWriter out = response.getWriter();

      // 验证码校验,无视大小写
      if(VerificationCode.equalsIgnoreCase(picCode)) {
            out.println("验证成功");
      } else {
            out.println("验证失败");
      }

      // 释放
      out.flush();
      out.close();
   }
}