Spring Boot 3登录开发进阶:图形验证码接口的实现

内容简介

上文我们已经整合好了jwt,本文我们开始实现图形验证码接口的实现。

前置条件

本文衔接上文,请从上文开始

spring boot3登录开发(整合jwt)_springboot3 jwt-CSDN博客

图形验证码接口实现

1、导入工具依赖

pom.xml:

<dependency>  
    <groupId>com.github.penggle</groupId>  
    <artifactId>kaptcha</artifactId>  
    <version>最新版本</version>  
</dependency>

注意:请替换最新版本为实际可用的最新版本号。

2、配置Kaptcha

创建一个配置类来配置Kaptcha。这通常包括设置验证码的文本长度、字体、颜色、图片大小等属性,在Spring Boot的配置类中添加Kaptcha的配置。

import com.google.code.kaptcha.impl.DefaultKaptcha;  
import com.google.code.kaptcha.util.Config;  
import java.util.Properties;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
  
@Configuration  
public class KaptchaConfig {  
  
    @Bean  
    public DefaultKaptcha getDefaultKaptcha() {  
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();  
        Properties properties = new Properties();  
        // 设置验证码的长度  
        properties.setProperty("kaptcha.textproducer.char.length", "4");  
        // 设置字体  
        properties.setProperty("kaptcha.textproducer.font.names", "宋体");  
        // 字体大小  
        properties.setProperty("kaptcha.textproducer.font.size", "30");  
        // 字体颜色  
        properties.setProperty("kaptcha.textproducer.font.color", "black");  
        // 设置图片宽度  
        properties.setProperty("kaptcha.image.width", "125");  
        // 设置图片高度  
        properties.setProperty("kaptcha.image.height", "45");  
        // 设置背景色  
        properties.setProperty("kaptcha.background.clear.to.white", "true");  
        // 设置是否有边框  
        properties.setProperty("kaptcha.border", "yes");  
        // 边框颜色  
        properties.setProperty("kaptcha.border.color", "105,179,90");  
        // 验证码图片样式  
        Config config = new Config(properties);  
        defaultKaptcha.setConfig(config);  
        return defaultKaptcha;  
    }  
}

3、 创建验证码生成服务

这里用到了redis,需要整合好:Spring Boot与Redis深度整合:实战指南

import com.google.code.kaptcha.impl.DefaultKaptcha;  
import com.google.code.kaptcha.util.Config;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.data.redis.core.StringRedisTemplate;  
import org.springframework.stereotype.Service;  
  
import javax.imageio.ImageIO;  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.awt.image.BufferedImage;  
import java.io.ByteArrayOutputStream;  
import java.util.Properties;  
  
@Service  
public class CaptchaService {  
  
    private DefaultKaptcha defaultKaptcha;  
  
    @Autowired  
    private StringRedisTemplate redisTemplate;  
  
    public CaptchaService() {  
        defaultKaptcha = new DefaultKaptcha();  
        Properties properties = new Properties();  
        // 设置验证码相关属性,如字体、大小、颜色等  
        properties.setProperty("kaptcha.border", "yes");  
        properties.setProperty("kaptcha.border.color", "105,179,90");  
        // ... 其他属性设置  
        Config config = new Config(properties);  
        defaultKaptcha.setConfig(config);  
    }  
  
    public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {  
        String captchaText = defaultKaptcha.createText();  
        String key = UUID.randomUUID().toString(); // 生成唯一的key  
        redisTemplate.opsForValue().set(key, captchaText, 60, TimeUnit.SECONDS); // 将验证码保存到Redis,并设置过期时间  
        request.getSession().setAttribute("captchaKey", key); // 将key保存到session中,用于前端验证  
  
        BufferedImage image = defaultKaptcha.createImage(captchaText);  
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
        ImageIO.write(image, "jpg", byteArrayOutputStream);  
        byte[] captchaImage = byteArrayOutputStream.toByteArray();  
          
        response.setDateHeader("Expires", 0);  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
        response.setHeader("Pragma", "no-cache");  
        response.setContentType("image/jpeg");  
          
        ServletOutputStream out = response.getOutputStream();  
        out.write(captchaImage);  
        out.flush();  
        out.close();  
    }  
}

4.、创建验证码控制器

在控制器中创建一个接口,创建一个控制器来处理验证码的生成请求。该接口通常是一个HTTP GET请求,返回验证码图片。

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
@RestController  
public class CaptchaController {  
  
    @Autowired  
    private CaptchaService captchaService;  
  
    @GetMapping("/captcha")  
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {  
        captchaService.createCaptcha(request, response);  
    }  
}

5.、前端(Vue)

1. 安装Axios(如果尚未安装)

使用npm或yarn安装Axios,以便进行HTTP请求。

npm install axios --save

或者

yarn add axios
 2. 在Vue组件中请求验证
<template>  
  <div>  
    <img :src="captchaSrc" @click="refreshCaptcha" alt="验证码" />  
    <input type="text" v-model="captchaInput" placeholder="请输入验证码" />  
    <button @click="submitForm">提交</button>  
  </div>  
</template>  
  
<script>  
import axios from 'axios';  
  
export default {  
  data() {  
    return {  
      captchaSrc: '',  
      captchaInput: '',  
    };  
  },  
  methods: {  
    refreshCaptcha() {  
      this.getCaptcha();  
    },  
    getCaptcha() {  
      axios.get('/captcha')  
        .then(response => {  
          this.captchaSrc = window.URL.createObjectURL(new Blob([response.data]));  
        })  
        .catch(error => {  
          console.error(error);  
        });  
    },  
    submitForm() {  
      // 提交表单逻辑,包括验证captchaInput是否正确  
      // ...  
    },  
  },  
  mounted() {  
    this.getCaptcha();  
  },  
};  
</script>
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot实现登录图形验证码,可以按照以下步骤进行: 1. 添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` 2. 配置Kaptcha 在application.properties文件中添加以下配置: ``` #Kaptcha验证码配置 kaptcha.border=no kaptcha.textproducer.font.color=black kaptcha.textproducer.char.space=5 kaptcha.image.width=160 kaptcha.image.height=60 kaptcha.textproducer.char.length=4 kaptcha.textproducer.font.size=30 ``` 3. 创建验证码接口 创建一个验证码接口,用于生成和返回验证码图片。例如: ``` @RestController @RequestMapping("/captcha") public class CaptchaController { @Autowired private Producer kaptchaProducer; @GetMapping("/image") public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); // return a jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = kaptchaProducer.createText(); // store the text in the session request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // create the image with the text BufferedImage bi = kaptchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } } } ``` 4. 校验验证码登录接口中校验验证码。例如: ``` @RestController @RequestMapping("/login") public class LoginController { @PostMapping("/auth") public ResultBean<String> doLogin(@RequestParam String username, @RequestParam String password, @RequestParam String captcha, HttpServletRequest request) { String kaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); if (StringUtils.isBlank(kaptcha) || !kaptcha.equalsIgnoreCase(captcha)) { return ResultBean.failed("验证码错误!"); } // TODO: 登录验证逻辑 return ResultBean.success("登录成功!"); } } ``` 这样就可以在Spring Boot实现登录图形验证码了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值