1. 程式人生 > 其它 >Spring Boot + Web Socket 實現掃碼登入,這種方式太香了!!

Spring Boot + Web Socket 實現掃碼登入,這種方式太香了!!

最近單位又有一個新Java專案。

涉及到掃碼登入。之前專案使用的是 ajax輪詢的方式。感覺太low了。

所以這次用webSocket的方式進行實現

好。廢話不多說!咱們開始!!

一、首先咱們需要一張表

這表是幹啥的呢?就是記錄一下誰掃碼了。誰登入了。

User_Token表

欄位如下:

  • uuid : 用於確保唯一性
  • userId :誰登入的
  • loginTime :登入時間
  • createTime :建立時間 用於判斷是否過期
  • state:是否二維碼失效 0有效 1失效

二、角色都有哪些

咱們還需要分析一下子。掃碼登入這個業務邏輯都有哪些角色

  • android端 or 微信Web端 :掃碼
  • PC端 :被掃。登入
  • 服務端:掌控全域性,提供介面。

三、介面都需要哪些?

有了角色。你用大腿也能想出來介面了對不對!!

所以咱們的介面有2個!

  • 生成二維碼介面:生成一個二維碼。二維碼中有UUID。
  • 確認身份介面:確定身份以及判斷是否二維碼過期等

四、步驟

那句話怎麼說的來著。要把大象裝冰箱一共分幾步?

  • PC端開啟。呼叫生成二維碼介面 並與 服務端建立連結。連結使用uuid進行繫結
  • 微信Web端進行掃碼。獲取二維碼中的uuid。
  • 微信Web端拿到uuid以後。顯示是否登入頁面。點選確定後 呼叫 確認身份介面。
  • 確認身份介面通過以後。服務端給PC端傳送資訊。完成登入。此時連結斷開。

好了!分析完了這些。你們一定在想。。還有完沒完啊。。不要在BB了。。趕緊貼程式碼吧。。

作者:觀眾老爺們。我這是在教給你們如何思考的方法呀?

那麼開始貼程式碼吧!希望大家在看到的同時也可以自己進行思考。

五、瘋狂貼程式碼

首先需要獲取二維碼的程式碼對不對! 貼!

//獲取登入二維碼、放入Token
@RequestMapping(value = "/getLoginQr" ,method = RequestMethod.GET)
public void createCodeImg(HttpServletRequest request, HttpServletResponse response){
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");

    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    try {
        //這裡沒啥操作 就是生成一個UUID插入 資料庫的表裡
        String uuid = userService.createQrImg();
        response.setHeader("uuid", uuid);
        // 這裡是開源工具類 hutool裡的QrCodeUtil 
        // 網址:http://hutool.mydoc.io/
        QrCodeUtil.generate(uuid, 300, 300, "jpg",response.getOutputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

有了獲取二維碼的介面。相對的前端需要呼叫。

知識點:動態載入圖片流並取出header中的引數

這裡使用了xmlhttp進行處理。

為什麼?

因為後端返回的是一個流。

那麼流中。就是放置了二維碼中的uuid。這個uuid作為一次會話的識別符號使用。

那麼前端也需要拿到。跟後端進行webSocket連結。

這樣有人掃碼後。服務端才可以使用webSocket的方式通知前端。有人掃碼成功了。你做你的業務吧。醬紫。

所以為了拿到請求中 header中放置的uuid 所以這樣通過xmlhttp進行處理

<div class="qrCodeImg-box" id="qrImgDiv"></div>

js

$(document).ready(function(){
    initQrImg();
});
 
 
 function initQrImg(){
    $("#qrImgDiv").empty();

    var xmlhttp;
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",getQrPath,true);
    xmlhttp.responseType = "blob";
    xmlhttp.onload = function(){
        console.log(this);
        uuid = this.getResponseHeader("uuid");

        if (this.status == 200) {
            var blob = this.response;
            var img = document.createElement("img");
            img.className = 'qrCodeBox-img';
            img.onload = function(e) {
                window.URL.revokeObjectURL(img.src);
            };
            img.src = window.URL.createObjectURL(blob);
            document.getElementById("qrImgDiv").appendChild(img);

            initWebSocket();
        }
    }
    xmlhttp.send();
}



var path = "://localhost:8085";
var getQrPath =  "http" + path + "/user/getLoginQr";
var wsPath =     "ws" + path + "/websocket/";



function initWebSocket(){

   if(typeof(WebSocket) == "undefined") {
       console.log("您的瀏覽器不支援WebSocket");
   }else{
       console.log("您的瀏覽器支援WebSocket");
       //實現化WebSocket物件,指定要連線的伺服器地址與埠  建立連線
       //等同於socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
       var wsPathStr = wsPath+uuid;
       socket = new WebSocket(wsPathStr);
       //開啟事件
       socket.onopen = function() {
           console.log("Socket 已開啟");
           //socket.send("這是來自客戶端的訊息" + location.href + new Date());
       };
       //獲得訊息事件
       socket.onmessage = function(msg) {
           console.log(msg.data);
           var data = JSON.parse(msg.data);
           if(data.code == 200){
               alert("登入成功!");
               //這裡存放自己業務需要的資料。怎麼放自己看
               window.sessionStorage.uuid = uuid;
               window.sessionStorage.userId = data.userId;
               window.sessionStorage.projId = data.projId;

               window.location.href = "pages/upload.html"
           }else{
               //如果過期了,關閉連線、重置連線、重新整理二維碼
               socket.close();
               initQrImg();
           }
           //發現訊息進入    開始處理前端觸發邏輯
       };
       //關閉事件
       socket.onclose = function() {
           console.log("Socket已關閉");
       };
       //發生了錯誤事件
       socket.onerror = function() {
           alert("Socket發生了錯誤");
           //此時可以嘗試重新整理頁面
       }
   }

}

好了。上面已經提到了前端如何配置webSocket。

下面說一下

springBoot中如何操作webSocket

Spring Boot 就不介紹了,基礎教程和示例原始碼看這裡:https://github.com/javastacks/spring-boot-best-practice

1、增加pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、增加一個Bean

/**
 * WebSocket的支援
 * @return
 */
@Bean
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
}

3、定義WebSocketServer

package com.stylefeng.guns.rest.modular.inve.websocket;
 
/**
 * Created by jiangjiacheng on 2019/6/4.
 */
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
 
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
 
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
 
    static Log log=LogFactory.get(WebSocketServer.class);
 
    //靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。
    private static int onlineCount = 0;
 
    //concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
 
    //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
    private Session session;
 
    //接收sid
    private String sid="";
 
    /**
     * 連線建立成功呼叫的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //線上數加1
        log.info("有新視窗開始監聽:"+sid+",當前線上人數為" + getOnlineCount());
        this.sid=sid;
        /*try {
            sendMessage("連線成功");
        } catch (IOException e) {
            log.error("websocket IO異常");
        }*/
    }
 
    /**
     * 連線關閉呼叫的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //線上數減1
        log.info("有一連線關閉!當前線上人數為" + getOnlineCount());
    }
 
    /**
     * 收到客戶端訊息後呼叫的方法
     *
     * @param message 客戶端傳送過來的訊息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到來自視窗"+sid+"的資訊:"+message);
        //群發訊息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }
    /**
     * 實現伺服器主動推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
 
 
    /**
     * 群發自定義訊息
     * */
    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
        log.info("推送訊息到視窗"+sid+",推送內容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //這裡可以設定只推送給這個sid的,為null則全部推送
                if(sid == null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
 
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

這樣就增加了webSocket的支援啦。

那麼回到剛才的步驟。

1、首先PC端呼叫介面展示出來了二維碼。

2、請求二維碼中的http請求。就有uuid在 header中。直接取到uuid 作為webSocket的標識sid進行連線。

3、然後手機端使用相機拿到二維碼中的uuid。使用uuid + userid 請求 掃碼成功介面。

貼掃碼成功介面

Controller程式碼:

/**
 * 確認身份介面:確定身份以及判斷是否二維碼過期等
 * @param token
 * @param userId
 * @return
 */
@RequestMapping(value = "/bindUserIdAndToken" ,method = RequestMethod.GET)
@ResponseBody
public Object bindUserIdAndToken(@RequestParam("token") String token ,
                                 @RequestParam("userId") Integer userId,
                                 @RequestParam(required = false,value = "projId") Integer projId){

    try {
        return new SuccessTip(userService.bindUserIdAndToken(userId,token,projId));
    } catch (Exception e) {
        e.printStackTrace();
        return new ErrorTip(500,e.getMessage());
    }

}

Service程式碼

@Override
public String bindUserIdAndToken(Integer userId, String token,Integer projId) throws Exception {

    QrLoginToken qrLoginToken = new QrLoginToken();
    qrLoginToken.setToken(token);
    qrLoginToken = qrLoginTokenMapper.selectOne(qrLoginToken);

    if(null == qrLoginToken){
        throw  new Exception("錯誤的請求!");
    }

    Date createDate = new Date(qrLoginToken.getCreateTime().getTime() + (1000 * 60 * Constant.LOGIN_VALIDATION_TIME));
    Date nowDate = new Date();
    if(nowDate.getTime() > createDate.getTime()){//當前時間大於校驗時間

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",500);
        jsonObject.put("msg","二維碼失效!");
        WebSocketServer.sendInfo(jsonObject.toJSONString(),token);

        throw  new Exception("二維碼失效!");
    }

    qrLoginToken.setLoginTime(new Date());
    qrLoginToken.setUserId(userId);

    int i = qrLoginTokenMapper.updateById(qrLoginToken);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code",200);
    jsonObject.put("msg","ok");
    jsonObject.put("userId",userId);
    if(ToolUtil.isNotEmpty(projId)){
        jsonObject.put("projId",projId);
    }
    WebSocketServer.sendInfo(jsonObject.toJSONString(),token);

    if(i > 0 ){
        return null;
    }else{
        throw  new Exception("伺服器異常!");
    }
}

邏輯大概就是判斷一下 token對不對

如果對的話。時間是否過期。如果沒有過期進行業務邏輯操作

//這句話比較關鍵
WebSocketServer.sendInfo(jsonObject.toJSONString(),token);

就是通知前端 已經登入成功了。並且給他業務所需要的內容。

然後前端程式碼接收到了。就進行業務邏輯操作就可以啦。

原文連結:https://blog.csdn.net/q826qq1878/article/details/91041679

版權宣告:本文為CSDN博主「93年頸椎病人」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。

近期熱文推薦:

1.1,000+ 道 Java面試題及答案整理(2021最新版)

2.終於靠開源專案弄到 IntelliJ IDEA 啟用碼了,真香!

3.阿里 Mock 工具正式開源,幹掉市面上所有 Mock 工具!

4.Spring Cloud 2020.0.0 正式釋出,全新顛覆性版本!

5.《Java開發手冊(嵩山版)》最新發布,速速下載!

覺得不錯,別忘了隨手點贊+轉發哦!