1.pom依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
2. CaptureController.java
@GetMapping("/captcha")
public void captcha(@RequestParam String key, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 指定验证码的长宽以及字符的个数
// SpecCaptcha captcha = new SpecCaptcha(135, 33, 5);
// captcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
// // 首先把验证码在后台保存一份,但是不能保存在session,可以存在redis,也可以存在后台的某个Map里面
// CaptureConfig.CAPTURE_MAP.put(key, captcha.text().toLowerCase());
// CaptchaUtil.out(captcha, request, response);
// 算术类型
ArithmeticCaptcha captcha = new ArithmeticCaptcha(135, 33);
captcha.setLen(2); // 几位数运算,默认是两位
captcha.getArithmeticString(); // 获取运算的公式:3+2=?
captcha.text(); // 获取运算的结果:5
CaptureConfig.CAPTURE_MAP.put(key, captcha.text().toLowerCase());
CaptchaUtil.out(captcha, request, response);
}
3. 登录接口做判断
// 判断验证码对不对
if (!admin.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(key))) {
// 如果不相等,说明验证不通过
CaptchaUtil.clear(request);
return Result.error("验证码不正确");
}
4. CaptureConfig.java
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CaptureConfig {
public static Map<String, String> CAPTURE_MAP = new HashMap<>();
}
5. LoginView.vue
<el-form-item>
<div style="display: flex; justify-content: center">
<el-input v-model="admin.verCode" prefix-icon="el-icon-user" style="width: 42%; margin-right: 10px" placeholder="请输入验证码"></el-input>
<img :src="captchaUrl" @click="clickImg()" width="140px" height="33px" />
</div>
</el-form-item>
mounted() {
this.key = Math.random();
this.captchaUrl = 'http://localhost:8888/login/captcha?key=' + this.key;
},
// 定义一些页面上控件出发的事件调用的方法
methods: {
login() {
request.post("/admin/login?key=" + this.key, this.admin).then(res => {
if (res.code === '0') {
this.$message.success("登录成功");
localStorage.setItem("user", JSON.stringify(res.data));
this.$router.push("/");
} else {
this.$message.error(res.msg);
this.key = Math.random();
this.captchaUrl = 'http://localhost:8888/login/captcha?key=' + this.key;
this.admin.verCode = ''
}
})
},
clickImg() {
this.key = Math.random();
this.captchaUrl = 'http://localhost:8888/login/captcha?key=' + this.key;
},
}