五分钟搞定验证码,你学会了吗?

开发 前端
我们其实很经常看到,登录一些网站其实是需要验证码的。使用验证码是现在很多网站通行的一种方式,因为计算机很难识别验证码,所以可以识别验证码的用户就可以被认为是人类。

哈喽,大家好,我是了不起。

我们其实很经常看到,登录一些网站其实是需要验证码的。使用验证码是现在很多网站通行的一种方式,因为计算机很难识别验证码,所以可以识别验证码的用户就可以被认为是人类。

今天我们讲一下在 Java 中验证码的使用。

验证码生成

本效果是利用easy-captcha工具包实现,首先需要添加相关依赖到pom.xml中,代码如下:

<dependency>
    <groupId>com.github.whvcse</groupId>
    <artifactId>easy-captcha</artifactId>
    <version>1.6.2</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

验证码格式

easy-captcha验证码工具支持GIF、中文、算术等类型,分别通过下面几个实例对象实现:

  • SpecCaptcha(PNG类型的静态图片验证码)
  • GifCaptcha(Gif类型的图片验证码)
  • ChineseCaptcha(GIF类型中文图片验证码)
  • ArithmeticCaptcha(算术类型的图片验证码)

字符类型分为以下几种:

  • TYPE_DEFAULT:数字和字母混合
  • TYPEONLYNUMBER:纯数字
  • TYPEONLYCHAR:纯字母
  • TYPEONLYUPPER:纯大写字母
  • TYPEONLYLOWER:纯小写字母
  • TYPENUMAND_UPPER:数字和大写字母混合

后端逻辑的实现

package com.yanx.controller;
 
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
@Controller
public class KapchaController {
    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setHeader("Cache-Control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/gif");
 
        //三个参数分别为宽、高、位数
        SpecCaptcha captcha=new SpecCaptcha(75,30,4);
 
        //设置类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
 
        //设置字体
        captcha.setCharType(Captcha.FONT_9);
 
        //验证码存入session
        httpServletRequest.getSession().setAttribute("verifyCode",captcha.text().toLowerCase());
 
        //输出图片流
        captcha.out(httpServletResponse.getOutputStream());
    }
 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.

这里控制器新增了defaultKaptcha()方法,该方法所拦截处理的路径为/kaptcha

前端逻辑的实现

在static目录中新建kaptcha.html页面,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
</head>
<body>
 <img src="/kaptcha" onclick="this.src='/kaptcha?t=new Date()'">
</body>
</html>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

访问后端验证码路径/kaptcha,验证码为图片形式。onclick方法为点击该标签时可以动态切换显示验证码。

启动Spring Boot项目,打开浏览器输入地址:

​http://localhost:8080/kaptcha.html​

效果如下:

图片

验证码验证

后端代码

package com.yanx.controller;
 
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
 
@Controller
public class KapchaController {
    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setHeader("Cache-Control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/gif");
 
        //三个参数分别为宽、高、位数
        SpecCaptcha captcha=new SpecCaptcha(75,30,4);
 
        //设置类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
 
        //设置字体
        captcha.setCharType(Captcha.FONT_9);
 
        //验证码存入session
        httpServletRequest.getSession().setAttribute("verifyCode",captcha.text().toLowerCase());
 
        //输出图片流
        captcha.out(httpServletResponse.getOutputStream());
    }
 
    @GetMapping("/verify")
    @ResponseBody
    public String verify(@RequestParam("code") String code, HttpSession session){
        if(StringUtils.isEmpty(code)){
            return "验证码不能为空";
        }
        String kapchaCode = session.getAttribute("verifyCode")+"";
        if(StringUtils.isEmpty(kapchaCode)||!code.toLowerCase().equals(kapchaCode)){
            return "验证码输入错误";
        }
        return "验证成功";
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码验证</title>
</head>
<body>
 
<img src="/kaptcha" onclick="this.src='/kaptcha?d=new Date()'">
 
<br>
<input type="text" maxlength="5" id="code" placeholder="请输入验证码"/>
<button id="verify">验证</button>
<br/>
<p id="verifyResult"></p>
 
</body>
 
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" >
  $(function(){
  //验证按钮点击事件
   $('#verify').click(function(){
    var code=$('#code').val();
    $.ajax({
      type:'GET',//方法类型
      url:'/verify?code='+code,
      success:function(result){
        $('#verifyResult').html(result);
      },
      error:function(){
        alert('请求失败');
      },
    });
   });
  });
</script>
</html>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.

效果

图片

图片

图片

结束语

生成验证码功能还是比较常用的,所以记录整理一下,方便以后回顾,如果有帮到你们的地方倍感荣幸,有路过的大佬还望不吝雅教!

责任编辑:武晓燕 来源: Java技术指北
相关推荐

2022-03-08 08:39:22

gRPC协议云原生

2023-12-30 13:41:39

JSON格式数据

2023-04-12 08:21:30

ChatGPTQQDiscord

2023-09-11 13:08:26

2024-07-29 12:21:12

2015-12-03 14:10:26

systemd容器Linux

2021-12-01 06:50:50

Docker底层原理

2022-12-09 09:21:10

分库分表算法

2017-12-19 09:05:39

2022-10-11 08:48:08

HTTP状态码浏览器

2023-04-04 08:14:45

2024-07-10 18:55:09

Python定时

2024-02-04 00:00:00

Effect数据组件

2024-01-19 08:25:38

死锁Java通信

2023-07-26 13:11:21

ChatGPT平台工具

2023-01-10 08:43:15

定义DDD架构

2022-04-26 08:10:33

MySQL存储InnoDB

2023-08-01 12:51:18

WebGPT机器学习模型

2024-01-02 12:05:26

Java并发编程

2020-11-09 09:59:50

Ajax技术
点赞
收藏

51CTO技术栈公众号