spring boot整合kaptcha验证码
引入依赖
<dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version>
</dependency>
创建验证码生成配置类 KaptchaConfig.java
@Configuration
public class KaptchaConfig {@Beanpublic DefaultKaptcha kaptcha() {DefaultKaptcha kaptcha = new DefaultKaptcha();Properties properties = new Properties();// 配置验证码生成属性properties.setProperty("kaptcha.border", "no");properties.setProperty("kaptcha.textproducer.font.color", "black");// 更多配置属性...Config config = new Config(properties);kaptcha.setConfig(config);return kaptcha;}
}
创建验证码接口 CaptchaController.java
@Autowiredprivate DefaultKaptcha kaptcha;@GetMapping("/captcha")public ResponseEntity<byte[]> generateCaptcha(HttpServletRequest request) {// 生成验证码String text = kaptcha.createText();BufferedImage image = kaptcha.createImage(text);try {ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(image, "jpg", baos);baos.flush();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.IMAGE_JPEG);// 将验证码存储到会话中,以便后续校验HttpSession session = request.getSession();session.setAttribute("captcha", text);return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);} catch (IOException e) {return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);}}
前端
<template><div><img :src="captchaUrl" alt="captcha"><input v-model="inputCaptcha" placeholder="请输入验证码"><button @click="verifyCaptcha">提交</button></div>
</template><script>
import axios from 'axios';export default {data() {return {captchaUrl: '', // 验证码图片地址inputCaptcha: '', // 用户输入的验证码captchaId: '' // 验证码唯一标识符};},mounted() {this.generateCaptcha(); // 页面加载时生成验证码},methods: {generateCaptcha() {axios.get('/captcha').then(response => {this.captchaUrl = 'data:image/jpeg;base64,' + response.data.image;this.captchaId = response.data.captchaId;}).catch(error => {console.error(error);});},verifyCaptcha() {axios.post('/captcha/verify', {captchaId: this.captchaId,captcha: this.inputCaptcha}).then(response => {console.log('验证码校验成功');// TODO: 验证码校验成功后的处理}).catch(error => {console.error('验证码校验失败');// TODO: 验证码校验失败后的处理});}}
};
</script>
注:
校验验证码的方法写在登录请求token中会更好。