需求
分析
点击验证码图片,改变验证码图片
点击获取验证码,发送验证码
代码
后端
@RestController
@RequestMapping(value = "/verify/")
@ApiModel("验证相关接口")
public class VerifyController {
@Autowired
private VerifyCodeBiz verifyCodeBiz;
@ApiOperation(value = "获取图片验证码")
@PostMapping(value = "getVerifyImage")
public ApiResult getVerifyImage(){
VerifyImageVO vo = verifyCodeBiz.getVerifyImage();
return ApiResult.success(vo);
}
}
@Service
@Slf4j
public class VerifyCodeBizImpl implements VerifyCodeBiz {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Override
public VerifyImageVO getVerifyImage() {
VerifyImageVO vo = new VerifyImageVO();
VerifyImagUtil verifyImagUtil = new VerifyImagUtil();
String base64 = null;
try {
base64 = VerifyImagUtil.toBase64(verifyImagUtil.getImage());
} catch (IOException e) {
e.printStackTrace();
}
String text = verifyImagUtil.getText();
String key = GenerateUtil.generateToken();
String verifyImageKey = RedisKeyUtil.getVerifyImageKey(key);
// redis缓存
redisTemplate.opsForValue().set(verifyImageKey,text,1, TimeUnit.MINUTES);
vo.setKey(key);
vo.setImageBase64("data:image/png;base64," + base64);
return vo;
}
}
返回结果:
前端
<div class="form">
<input type="hidden" id="verifyImageKey">
<div class="form-item">
<div class="form-input"><input type="tel" placeholder="请输入你的手机号"
id="mobile"
maxlength="11"></div>
</div>
<div class="form-item">
<div class="form-input"><input type="text" placeholder="图形验证码"
id="verifyImageText"
maxlength="4"></div>
<div class="from-input-right" ><img
src=""
alt="" id="verifyImage"></div>
</div>
<div class="form-item">
<div class="form-input"><input type="text" placeholder="验证码"
id="verifyCode"
maxlength="6"></div>
<div class="from-input-right from-button" id="getVerifyCode">
<div id="getVerifyCodeText" style="word-break:keep-all; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">获取验证码</div>
</div>
</div>
</div>
// 点击图形验证码刷新
$('#verifyImage').click(function () {
getVerifyImage();
})
function getVerifyImage() {
// 填充验证码图片
$.ajax({
type: 'POST',
url: URL_PRE + "/verify/getVerifyImage",
dataType: "json",
success: function (result) {
if (result.code != 0) {
alert(result.message);
} else {
$("#verifyImage").attr("src", result.data.imageBase64);
$('#verifyImageKey').val(result.data.key);
}
},
});
}