您好,登錄后才能下訂單哦!
這篇文章主要介紹如何使用java實現簡單掃碼登錄功能,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
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>
主要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; }
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 = new HashMap<String, ScanPool>(1); map.put(uuid, pool); PoolCache.cacheMap.put(uuid, pool); pool = null; } catch (Exception e) { Log4jUtil.CommonLog.error("pc生成二維碼登錄", e); } return "index"; } //判斷二維碼是否被掃描 public void pool() { DataResultInfo result = null; System.out.println("檢測[ " + uuid + " ]是否登錄"); ScanPool pool = null; if(MapUtils.isNotEmpty(PoolCache.cacheMap)) pool = PoolCache.cacheMap.get(uuid); try { if (pool == null) { // 掃碼超時,進線程休眠 result = DataResultInfo.getInstance().failure(); result.setSuccessFlag(CommonConstant.Zero); result.setExtension(CommonConstant.Zero, "該二維碼已經失效,請重新獲取"); Thread.sleep(10 * 1000L); } else { // 使用計時器,固定時間后不再等待掃描結果--防止頁面訪問超時 new Thread(new ScanCounter(uuid, pool)).start(); boolean scanFlag = pool.getScanStatus(); //這里得到的ScanPool(時間靠前)和用戶使用手機掃碼后得到的不是一個,用戶掃碼后又重新更新了ScanPool對象,并重新放入了redis中,,所以這里要等待上面的計時器走完,才能獲得最新的ScanPool if (scanFlag) { result = DataResultInfo.getSuccess(); // 根據uuid從redis中獲取pool對象,得到對應的sessionId,返給頁面,通過js存cookie中 JSONObject jsonObj = new JSONObject(); jsonObj.put("cname", CookieConstant.SESSION_KEY); jsonObj.put("cvalue", pool.getSession()); result.setData(jsonObj); } else { result = DataResultInfo.getInstance().failure(); result.setMessage("等待掃描"); } } } catch (Exception e) { e.printStackTrace(); } sendJsonMessage(result); } //手機掃碼接口(以id和token作為用戶身份登錄) public String phoneScanLogin() { DataResultInfo result = null; ScanPool pool = null; if(MapUtils.isNotEmpty(PoolCache.cacheMap)) pool = PoolCache.cacheMap.get(uuid); try { if (pool == null) { result = DataResultInfo.getInstance().failure(); result.setMessage("該二維碼已經失效,請重新獲取"); } else { if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(token)) { //根據id和token查詢后臺,獲取用戶信息userBean String redisToken = redisUtil.getRedis(RedisKeyConstant.APP_TOKEN+userId); if(redisToken != null && redisToken.equals(token)){ UserBean userBean = userService.findByUserId(Long.valueOf(userId)); if (userBean != null) { String sessionId = SessionConstant.SESSION_ID_PRE + FormatUtils.password(userBean.getId() .toString()); Map<String, String> cookieSession = new HashMap<String, String>(); cookieSession .put(CookieConstant.SESSION_KEY, sessionId); // WrCookie.writeCookie(getResponse(),cookieSession); // 添加用戶信息到redis boolean re = redisUtil.addUserInfo( RedisKeyConstant.SESSION + sessionId, BeanUtils.toBean(userBean, UserInfo.class)); getSession().setAttribute( SessionConstant.USER_INFO_WEB, BeanUtils.toBean(userBean, UserInfo.class)); getSession().setAttribute( DomainConstant.USER_CENTER_KEY, DomainConstant.USER_CENTER); pool.setSession(sessionId); pool.scanSuccess(); }else{ result = DataResultInfo.getInstance().failure(); result.setMessage("用戶信息獲取異常!請稍后再試"); } } else { result = DataResultInfo.getInstance().failure(); result.setExtension("11", "用戶身份信息失效,請重新登錄!"); } } else { result = DataResultInfo.getInstance().failure(); result.setMessage("請求參數有誤!"); return "error"; } // 不能清除,否則conn方法得不到pool對象,不會進入線程休眠 // System.out.println("清除掃描過的uuid"); //PoolCache.cacheMap.remove(uuid); } } catch (Exception e) { Log4jUtil.CommonLog.error("手機掃碼 后訪問 異常", e); } sendJsonMessage(result); return null; } //掃碼成功跳轉頁 public String success() { String sessionId = WrCookie.getCookie(super.getRequest(), CookieConstant.SESSION_KEY); UserInfo userInfo = redisUtil.getUserInfo(RedisKeyConstant.SESSION + sessionId); super.getRequest().setAttribute(SessionConstant.USER_INFO_WEB, userInfo); return SUCCESS; } //線程判斷二維碼是否超時 class ScanCounter implements Runnable { public Long timeout = 30 * 1000L; //超時時長 // 傳入的對象 private String uuid; private ScanPool scanPool; public ScanCounter(String p, ScanPool scanPool) { uuid = p; this.scanPool = scanPool; } @Override public void run() { try { Thread.sleep(timeout); } catch (InterruptedException e) { e.printStackTrace(); } notifyPool(uuid, scanPool); } public synchronized void notifyPool(String uuid, ScanPool scanPool) { if (scanPool != null) scanPool.notifyPool(); } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public ScanPool getScanPool() { return scanPool; } public void setScanPool(ScanPool scanPool) { this.scanPool = scanPool; } }
ScanPool.java(存放uuid的bean)
public class ScanPool implements Serializable{ /** * @Fields serialVersionUID : TODO(用一句話描述這個變量表示什么) */ private static final long serialVersionUID = -9117921544228636689L; private Object session ; //創建時間 private Long createTime = System.currentTimeMillis(); //登錄狀態 private boolean scanFlag = false; public boolean isScan(){ return scanFlag; } public void setScan(boolean scanFlag){ this.scanFlag = scanFlag; } /** * 獲取掃描狀態,如果還沒有掃描,則等待固定秒數 * @param wiatSecond 需要等待的秒數 * @return */ public synchronized boolean getScanStatus(){ try { if(!isScan()){ //如果還未掃描,則等待 this.wait(); } if (isScan()) { System.err.println("手機掃描完成設置getScanStatus..true..........."); return true; } } catch (InterruptedException e) { e.printStackTrace(); } return false; } /** * 掃碼之后設置掃碼狀態 * @param token * @param id */ public synchronized void scanSuccess(){ try { System.err.println("手機掃描完成setScan(true)....同時釋放notifyAll(手機掃碼時,根據uuid獲得的scanpool對象)"); setScan(true); this.notifyAll(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void notifyPool(){ try { this.notifyAll(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /***********************************************/ public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public Object getSession() { return session; } public void setSession(Object session) { this.session = session; } }
PoolCache.java(定時清理二維碼uuid的類)
public class PoolCache { // 緩存超時時間 10分鐘 private static Long timeOutSecond = 10 * 60 * 1000L; // 每半小時清理一次緩存 private static Long cleanIntervalSecond = 30 * 60 * 1000L; //此map在多線程中會出現 ConcurrentModificationException //public static Map<String, ScanPool> cacheMap = new HashMap<String, ScanPool>(); //List //public static CopyOnWriteArrayList<Map<String, ScanPool>> copyOnWriteArrayList = new CopyOnWriteArrayList<Map<String,ScanPool>>(); //專用于高并發的map類-----Map的并發處理(ConcurrentHashMap) public static ConcurrentHashMap<String, ScanPool> cacheMap = new ConcurrentHashMap<String, ScanPool>(); static { new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(cleanIntervalSecond); } catch (InterruptedException e) { e.printStackTrace(); } clean(); } } public void clean() { try { /*if (copyOnWriteArrayList.size() > 0) { Iterator<Map<String, ScanPool>> iterator = copyOnWriteArrayList.iterator(); while (iterator.hasNext()) { Map<String, ScanPool> map = iterator.next(); Iterator<String> it2 = map.keySet().iterator(); while (it2.hasNext()){ String uuid = it2.next(); ScanPool pool = map.get(uuid); if (System.currentTimeMillis() - pool.getCreateTime() > timeOutSecond ) { copyOnWriteArrayList.remove(map); System.err.println("失效了: .. "+ uuid); System.err.println("失效了: .. "+ map); break; } } } }*/ if (cacheMap.keySet().size() > 0) { Iterator<String> iterator = cacheMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); ScanPool pool = cacheMap.get(key); if (System.currentTimeMillis() - pool.getCreateTime() > timeOutSecond ) { cacheMap.remove(key); } } } } catch (Exception e) { Log4jUtil.CommonLog.error("定時清理uuid異常", e); } } }).start(); } }
掃碼流程圖:
流程圖:
使用線程實時監聽掃碼狀態;
用戶掃描二維碼相當于使用 用戶名密碼 在網頁端登錄,需要存瀏覽器cookie
,而用戶通過使用手機掃碼,直接請求服務器,登陸成功,js中得到用戶數據及cookie,把cookie返給頁面,再通過js存入cookie中
以上是“如何使用java實現簡單掃碼登錄功能”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。