springboot vue 实现验证码
时间: 2023-10-20 15:09:46 浏览: 113
1. 在Spring Boot项目中引入验证码依赖
```xml
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
```
2. 添加Kaptcha配置类
```java
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha producer() {
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.length", "4");
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
```
3. 添加验证码生成接口
```java
@RestController
public class CaptchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
@GetMapping("/captcha.jpg")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
String text = defaultKaptcha.createText();
session.setAttribute("captcha", text);
BufferedImage image = defaultKaptcha.createImage(text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
out.close();
}
}
```
4. 在前端页面中添加验证码图片和输入框
```html
<template>
<div>
<div class="form-group">
<label for="captcha">验证码</label>
<div class="input-group">
<input type="text" class="form-control" id="captcha" name="captcha" v-model="captchaCode" placeholder="请输入验证码" required>
<span class="input-group-append">
<img src="/captcha.jpg" @click="refreshCaptcha" alt="验证码" style="cursor: pointer;">
</span>
</div>
</div>
</div>
</template>
```
5. 在Vue组件中添加刷新验证码方法和提交表单方法
```js
<script>
export default {
data() {
return {
captchaCode: '',
formData: {
// 表单数据
}
}
},
methods: {
refreshCaptcha() {
document.querySelector('img').src = '/captcha.jpg?' + Math.random()
},
submitForm() {
axios.post('/api/login', this.formData).then(res => {
// 处理登录结果
})
}
}
}
</script>
```
6. 在后端中验证验证码
```java
@PostMapping("/login")
public Result login(@RequestBody LoginForm form, HttpSession session) {
String captcha = (String) session.getAttribute("captcha");
if (StringUtils.isBlank(captcha) || !captcha.equalsIgnoreCase(form.getCaptcha())) {
return Result.error("验证码不正确");
}
// 验证通过,进行登录操作
// ...
}
```
阅读全文