java前后端图片验证码功能整理
本帖最后由 徐行且慢 于 2020-6-28 10:14 编辑图片验证码
1、导入maven依赖
<dependencies>
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
2、前后端分离使用
(1)后台代码:发送验证码
//先启动redis,注入redis接口RedisTemplate
@GetMapping("image")
public Map<String,Object> captcha(HttpServletRequest request, HttpServletResponse response){
//图形验证码尺寸
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
String codekey = specCaptcha.text().toLowerCase();
String key = UUID.randomUUID().toString();
//存入redis,设置过期时间为30分钟
redisTemplate.opsForValue().set(key,codekey,30, TimeUnit.MINUTES);
//创建map
HashMap<String, Object> map = new HashMap<>();
map.put("key",key);
map.put("image",specCaptcha.toBase64());
//将map返回到前端
return map;
}
(2)前台代码:接收验证码
<img id="verImg" width="130px" height="48px"/>
<!--ajax代码-->
<script>
var verKey;
// 获取验证码
$.get('/captcha', function(res) {
verKey = res.key;
$('#verImg').attr('src', res.image);
},'json');
// 登录
$.post('/login', {
verKey: verKey,
verCode: '8u6h',
username: 'admin',
password: 'admin'
}, function(res) {
console.log(res);
}, 'json');
</script>
<!--vue代码-->
<script>
getCode(){
axios.get("http://localhost:9002/admin/image").then(res =>{
console.log(res);
this.imag = res.data.image;
this.verKey=res.data.key;
})
}
//登录
login(){
alert("11");
axios.post("http://localhost:9002/admin/login/"+this.key+"/"+this.verKey,this.pojo).then(res=>{
if(res.data.flag){
alert("登陆成功!");
}else{
alert("登陆失败");
}
})
},
</script>
(3)后台代码:解析验证码
@PostMapping("login/{key}/{verkey}")
public Result login(@RequestBody Admin admin,@PathVariable(value = "key") String key,@PathVariable(value = "verkey") String verKey){
//提取redis中的key
String keycode= (String) redisTemplate.opsForValue().get(verKey);
//判断验证码
if (keycode.equals(key)){
//登录查询
Admin a=adminService.login(admin);
//登陆成功
if (a!=null){
return new Result(true, StatusCode.OK,"登陆成功",a);
//否则,登陆失败
}else{
return new Result(false, StatusCode.ERROR,"登陆失败");
}
//验证码错误
}else {
return new Result(false, StatusCode.ERROR, "验证码错误");
}
} 前排支持大佬! 为啥不能发到技术版款
{:301_978:}谢谢大佬... 这验证的...好随便啊 parker.smith 发表于 2020-6-28 11:11
这验证的...好随便啊
又复杂的吗?
安利一下{:1_889:} 学习学习,,,
页:
[1]