使用springboot+vue实现验证码登录验证的前后端代码
时间: 2024-02-01 15:01:54 浏览: 111
前端代码:
```vue
<template>
<div>
<el-form :model="form" label-width="100px" ref="form">
<el-form-item label="手机号码" prop="phone">
<el-input v-model="form.phone" placeholder="请输入手机号码"></el-input>
</el-form-item>
<el-form-item label="验证码" prop="captcha">
<el-input v-model="form.captcha" placeholder="请输入验证码" style="width: 200px"></el-input>
<el-button type="primary" @click="sendCaptcha" :disabled="isSending">{{ captchaText }}</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { getCaptcha, login } from '@/api/user'
export default {
data() {
return {
form: {
phone: '',
captcha: ''
},
captchaText: '获取验证码',
isSending: false
}
},
methods: {
sendCaptcha() {
if (!this.form.phone) {
this.$message.error('请输入手机号码')
return
}
if (this.isSending) {
return
}
this.isSending = true
let count = 60
const interval = setInterval(() => {
count--
if (count <= 0) {
clearInterval(interval)
this.captchaText = '重新获取'
this.isSending = false
} else {
this.captchaText = `${count}s后重新获取`
}
}, 1000)
getCaptcha(this.form.phone).then(() => {
this.$message.success('验证码已发送')
}).catch(() => {
clearInterval(interval)
this.captchaText = '重新获取'
this.isSending = false
})
},
submitForm() {
this.$refs.form.validate(valid => {
if (valid) {
login(this.form.phone, this.form.captcha).then(() => {
this.$router.push('/')
}).catch(error => {
this.$message.error(error.message)
})
}
})
}
}
}
</script>
```
后端代码:
```java
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private RedisUtil redisUtil;
@PostMapping("/captcha")
public ResponseEntity<Object> getCaptcha(@RequestParam String phone) {
// 生成4位随机验证码
String captcha = String.valueOf(new Random().nextInt(8999) + 1000);
// 将验证码保存到redis中,有效期5分钟
redisUtil.set(phone, captcha, 5 * 60);
// TODO 发送短信验证码
return ResponseEntity.ok().build();
}
@PostMapping("/login")
public ResponseEntity<Object> login(@RequestParam String phone, @RequestParam String captcha) {
// 从redis中获取验证码
String redisCaptcha = (String) redisUtil.get(phone);
if (StringUtils.isBlank(redisCaptcha)) {
throw new BusinessException("验证码已失效,请重新获取");
}
if (!StringUtils.equals(redisCaptcha, captcha)) {
throw new BusinessException("验证码错误");
}
// TODO 验证手机号码是否已注册
// TODO 如果未注册,则自动注册
// TODO 生成token返回给前端
return ResponseEntity.ok().build();
}
}
```
阅读全文