java实现简单扫码登录功能
- 模仿微信pc网页版扫码登录
- 使用js代码生成qrcode二维码减轻服务器压力
- js循环请求服务端,判断是否qrcode被扫
- 二维码超时失效功能
- 二维码被扫成功登录,服务端产生sessionId,传到页面使用js保存cookie
- 多线程
生成qrcode相关js jquery.qrcode.js
-
代码
页面div
<div class="pc_qr_code">
<input type="hidden" id="uuid" value="${uuid }"/>
</div>
<div id="result">请使用手机扫码</div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
主要js
//生成二维码
!function(){
var uuid = $("#uuid").val();
var content;
content = "..........do?uuid="+uuid;
//console.dir(content);
$('.pc_qr_code').qrcode({
render:"canvas",
width:200,
height:200,
correctLevel:0,
text:content,
background:"#ffffff",
foreground:"black",
src:"/logo.png"
});
setCookie("sid", 123, -1*60*60*1000);
keepPool();//自动循环调用
}();
function keepPool(){
var uuid = $("#uuid").val();
$.get(ctx+"/web/login/pool.do",{uuid:uuid,},function(msg){
//如果放入一个不存在的网址怎么办?
//console.log(msg);
if(msg.successFlag == '1'){
$("#result").html("扫码成功");
setCookie(msg.data.cname, msg.data.cvalue, 3*60*60*1000);
//alert("将跳转...");
window.location.href = ctx +"/webstage/login/success.do";
}else if(msg.successFlag == '0'){
$("#result").html("该二维码已经失效,请重新获取");
}else{
keepPool();
}
});
}
//设置cookie
function setCookie(cname, cvalue, expireTime) {
var d = new Date();
d.setTime(d.getTime() + expireTime);//设置过期时间
var expires = "expires="+d.toUTCString();
var path = "path=/"
document.cookie = cname + "=" + cvalue + "; " + expires + "; " + path;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
“
java代码
//二维码首页
public String index() {
try {
uuid = UUID.randomUUID().toString();
super.getRequest().setAttribute("uuid", uuid);
ScanPool pool = new ScanPool();
pool.setCreateTime(System.currentTimeMillis());
Map<String, ScanPool> map =