使用Spring Boot和Vue实现验证码的内容
时间: 2024-04-06 11:29:00 浏览: 55
spring boot实现验证码功能
可以使用第三方库 kaptcha 来生成验证码图片,Spring Boot 作为后端提供接口,Vue 作为前端展示验证码图片和发送验证码请求。
首先添加 kaptcha 依赖:
```xml
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
```
在 Spring Boot 中配置 kaptcha:
```java
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "no");
properties.setProperty("kaptcha.textproducer.font.color", "black");
properties.setProperty("kaptcha.image.width", "150");
properties.setProperty("kaptcha.image.height", "50");
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
properties.setProperty("kaptcha.textproducer.char.length", "4");
Config config = new Config(properties);
DefaultKaptcha producer = new DefaultKaptcha();
producer.setConfig(config);
return producer;
}
}
```
然后在 Controller 中提供生成验证码图片的接口:
```java
@RestController
public class CaptchaController {
private final Producer kaptchaProducer;
public CaptchaController(Producer kaptchaProducer) {
this.kaptchaProducer = kaptchaProducer;
}
@GetMapping("/captcha.jpg")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
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");
String text = kaptchaProducer.createText();
request.getSession().setAttribute("captcha", text);
BufferedImage image = kaptchaProducer.createImage(text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
out.close();
}
}
```
在 Vue 中,可以使用 axios 发送请求获取验证码图片并展示:
```vue
<template>
<div>
<img :src="captchaUrl" @click="refreshCaptcha" />
<input v-model="captcha" />
<button @click="submit">提交</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
captcha: '',
captchaUrl: '/captcha.jpg'
}
},
methods: {
refreshCaptcha() {
this.captchaUrl = '/captcha.jpg?' + Date.now()
},
submit() {
axios.post('/verifyCaptcha', {
captcha: this.captcha
})
}
}
}
</script>
```
在后端提供验证验证码的接口:
```java
@PostMapping("/verifyCaptcha")
public boolean verifyCaptcha(HttpServletRequest request, @RequestBody Map<String, String> captcha) {
String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
if (sessionCaptcha != null && sessionCaptcha.equals(captcha.get("captcha"))) {
return true;
}
return false;
}
```
以上代码只是一个简单的验证码示例,实际项目中还需要进行安全性和用户体验的优化。
阅读全文