SpringBoot实现验证码生成与验证功能

效果:

  1. 验证码生成

本效果是利用easy-captcha工具包实现,开源地址为如下:

easy-captcha

首先需要添加相关依赖到pom.xml中,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hb</groupId>
    <artifactId>newSystem</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>newSystem</name>
    <description>用作练习</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/repositories/central</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

代码段:

<dependency>

<groupId>com.github.whvcse</groupId>

<artifactId>easy-captcha</artifactId>

<version>1.6.2</version>

</dependency>

是对该包的依赖引入。

1.1验证码格式

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

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

表 1: easy-captcha验证码字符类型

类型

描述

TYPE_DEFAULT

数字与字母混合

TYPEONLYNUMBER

纯数字

TYPEONLYCHAR

纯字母

TYPEONLYUPPER

纯大写字母

TYPEONLYLOWER

纯小写字母

TYPENUMAND_UPPER

数字和大写字母

1.2后端逻辑的实现

在controll包中新建KaptchaController类,在里面新建一个方法,使用GifCaptcha生成一个PNG类型的验证码对象,并以图片流的·方式输出到前端,后端代码如下:

package com.hb.newSystem.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());
    }

}

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

1.3前端逻辑实现

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码显示</title>
</head>
<body>
 <img src="/kaptcha" onclick="this.src='/kaptcha?d=new Date()*1'">
</body>
</html>

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

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

localhost:8080/yanzhnegma.html

效果如下:

  1. 验证码验证

后端代码:

package com.hb.newSystem.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 "验证成功";
    }
}

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码测试</title>
</head>
<body>

<img src="/kaptcha" onclick="this.src='/kaptcha?d=new Date()*1'">

<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>

目录结构:

最后效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>