效果图
其实现在很少有再用这种验证方式了的,不过作为经典的图形验证码验证,留恋一下
导入依赖ValidateCode.jar就可以用了,当然也可以自己去写一个验证图形(实际上很简单)
这里介绍的是java的用法,其他语言大同小异
后端代码部分
写一个请求,专门请求验证码
做两件事,一是把验证码存入session供验证,二是把验证码渲染给前端
@Controller
public class CodeImgHandler {
@GetMapping("/loginCode")
public void getLoginCode(HttpServletRequest req, HttpServletResponse resp){
ValidateCode code = new ValidateCode(120,40,4,20); //validate封装的方法
req.getSession().setAttribute("loginCode", code.getCode()); //存入session
ByteArrayOutputStream out=new ByteArrayOutputStream();
try {
boolean flag = ImageIO.write(code.getBuffImg(), "JPEG",out);
byte[] b=out.toByteArray();
resp.getOutputStream().write(b); //返回这个流
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端部分
那么前端怎么获得呢?
<img src="/loginCode" id="limgpic" > //就这样一句话就可以实现图片读取了
那么我们如何刷新这个验证码呢?
<img src="/loginCode" id="limgpic" onclick="changeImgCode()">
<script>
function changeImgCode(){
$("#limgpic").prop("src","/loginCode?a="+Math.random()
//这样就可以实现点击刷新验证码了,如果不加个相区别的路径,请求发不出去
}
</script>