JavaWeb實現好友驗證的思路

需求分析:大家在一些網站註冊賬號的時候,有時會忘記密碼或者賬號被盜,正規的網站都是通過手機發驗證碼的,這可能要調用第三方來實現。因爲我是自己做的小項目,這是想有這麼個驗證的流程,所以我這裏就用好友驗證來代替。
思路分析:
1.從數據庫中查找出所有的好友,放入一個集合(friendTemList)
2.創建一個存放其他名字的集合(otherTemList),用來混淆用戶視聽
3.創建一個隨機數x(0-3),用來從friendTemList取出下標爲0-x的userName,從otherTemLis取下標爲0-(3-x)的userName,組成一個新的集合(finalList)
4.已經取出來的userName要從friendTemList及otherTemList中移除(Remove)
5.將friendTemList,otherTemList,finalList傳遞給前端。其friendTemList、otherTemList的作用是下次取userName是從它們裏邊取,finalList是顯示在前端供用戶選擇的。
6.當friendTemList,otherTemList的大小(size)小於0或小於對應的隨機數時,重置集合

實現中遇到的問題及解決方案:
1.我自己也是個前端小白,原來以爲js能處理後臺傳遞的java集合(List),後來瞭解到並不能,所以我重新定義了一個好友驗證的實體對象(FriendVerify),方便轉換成json對象傳遞到前端;`
public class FriendVerify {

private String userName;
private String friendTem;
private String otherTem;
private String finalFriend;`

friendTem表示臨時的好友字符串,otherTem表示臨時的非好友字符串,finalFriend表示顯示在前端供用戶選擇的字符串。它們的形式都是:
張三,李四,王五,....
在每個userName之間加個","是爲了方便傳遞給前端進行切割。不過這樣做也將後臺代碼變得複雜了一些,。。。,誰叫我是前端小白呢?就將就下吧!後臺首先將字符串轉換成數組,數組再轉換成List集合。下面來看代碼:
前端部分:主要將userName,friendTem,otherTem傳遞給後臺。
function friendVerify(){

   var userLoginName = currentUser.loginName;
   if(userLoginName == null || userLoginName == "" || userLoginName == 0){
         alert("請先輸入登錄名");
         return false;
     }else{
         $.ajax({
                 url:"${ctx}/toVerifyFriend?random="+ Math.random(),
                 type:"post",//發送請求的方式:(GET|POST)
                 dataType:"json",//服務器響應的數據類型
                 contentType:"application/json", //  編碼類型
                 data:JSON.stringify({userName : userLoginName,friendTem : friendTem,otherTem : otherTem}),
                async:true,
                success:function(data){
                     if(data != null && data != ""){
                        friendTem = data.friendVerify.friendTem;
                        otherTem = data.friendVerify.otherTem;
                        var finalFriend = data.friendVerify.finalFriend;
                        var finalFriendArray = new Array();
                        finalFriendArray = finalFriend.split(",");
                        var htmlstr="";
                        for(var i=0;i<finalFriendArray.length;i++){
                            htmlstr+="<label style='margin-left: 18px;line-height: 29px;'><input type='checkBox' value="+finalFriendArray[i]+" name='friendName'  style='margin-top: 8px'/><b style='margin-left:3px;'>"+finalFriendArray[i]+"</b></label>";
                        }
                        htmlstr+="<label style='margin-left: 40px'><input type='button' value='換一批' name='huanyipi' style='margin-top: 5px;' onclick='friendVerify()'/></label>";
                        $("#init").html(htmlstr);
                            }
                        }   
                        })
            return false;
            }
          };`

後臺代碼:這裏我直接將邏輯寫在了Controller層,一般來說,邏輯寫在Service層的實現類中,大家也不用糾結這個問題
    @RequestMapping("/toVerifyFriend")
    public void veriFyFriend(@RequestBody FriendVerify friendVerify,
            HttpServletResponse response) throws Exception{

        int flag = (int)(Math.random()*2 + 1);

        String userName = friendVerify.getUserName();

        String friendTem = friendVerify.getFriendTem();
        String[] friendTemArray = friendTem.split(",");
        List<String> friendTemList = CreateListUtils.arrayToList(friendTemArray);

        String otherTem = friendVerify.getOtherTem();
        String[] otherTemArray = otherTem.split(",");
        List<String> otherTemList = CreateListUtils.arrayToList(otherTemArray);

        if(friendTemArray==null||friendTemArray.length<flag||friendTemArray[0].equals("")){
            friendTemList.clear();
            System.out.println(friendTemList.size());
            friendTemList.addAll(InitFriendList(userName));
                //Object[] friendArray = friendTemList.toArray();
        }
        if(otherTemArray==null||otherTemArray.length<(3-flag)||otherTemArray[0].equals("")){
            otherTemList.clear();
            System.out.println(otherTemList.size());
            otherTemList.addAll(InitOtherList());

        }

        List<String> newfriendList = CreateListUtils.listFactory(friendTemList, flag);
        friendTemList.removeAll(newfriendList);

        List<String> newOtherList = CreateListUtils.listFactory(otherTemList, 3-flag);
        otherTemList.removeAll(newOtherList);


        List<String> finalList = new ArrayList<>();
        finalList.addAll(newfriendList);
        finalList.addAll(newOtherList);

        FriendVerify friendVer = new FriendVerify();
        friendVer.setFriendTem(CreateListUtils.listToString(friendTemList));
        friendVer.setOtherTem(CreateListUtils.listToString(otherTemList));
        friendVer.setFinalFriend(CreateListUtils.listToString(finalList));


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("friendVerify", friendVer);
        response.setContentType("text/html;charset=UTF-8");

        response.getWriter().println(jsonObject.toJSONString());
        response.getWriter().flush();

    }

//初始化friendList
public List<String> InitFriendList(String userName){

    List<Friend> friendsList = friendService.findFriendByName(userName);
    List<String> friendList = new ArrayList<>();
    for(Friend friend:friendsList){
        if(friend.getFriend_1().equals(userName)){
            friendList.add(friend.getFriend_2());
        }else{
            friendList.add(friend.getFriend_1());
            }
        }

        return friendList;

    }

    //初始化otherList
    public List<String> InitOtherList(){

        List<String> otherList = new ArrayList<>();
        otherList.add("趙峯");
        otherList.add("李洵");
        otherList.add("呂德財");
        otherList.add("高紅軍");
        otherList.add("劉雪芬");
        otherList.add("溫展楚");
        otherList.add("鐘琴思");
        otherList.add("張岐江");
        otherList.add("王鳳琪");
        return otherList;
    }



工具類:這裏有一個奇怪的問題:我如果用oldList.subList(0, flag)截取List值的時候,上面代碼中報錯,顯示在finalList.addAll(newfriendList);這個方法報錯。暫時沒有研究,待我有空慢慢研究,有知道的朋友可以告訴我

public class CreateListUtils {

        //根據隨機數生成List
        public static List<String> listFactory(List<String> oldList,int flag){

            List<String> newList = new ArrayList<>();

            for(int i = 0;i<flag;i++){

                newList.add(oldList.get(i)); 

            }
            //newList = oldList.subList(0, flag);
            return newList;

        }

        //數組轉換成List
        public static List<String> arrayToList(String[] array){

            List<String> toList = new ArrayList<>();

            for(int i=0;i<array.length;i++){
                toList.add(array[i]);
            }


            return toList;

        }
        //List轉換成字符串
        public static String listToString(List<String> list){

            StringBuffer toString = new StringBuffer();
            for(int i=0;i<list.size();i++){
                if(i<list.size()-1){
                    toString.append(list.get(i));
                    toString.append(",");
                }else{
                    toString.append(list.get(i));
                }
            }
            return toString.toString();

        }

}


好友驗證:這裏我要SpringMvc框架來接收checkBox標籤傳過來的數組。
@RequestMapping("/toLogFriendVerify")
public String logFriendVerify(@RequestParam(value = "friendName", required = false) String[] friendName,User currentUser,HttpServletRequest request){
    HttpSession session = request.getSession(false);

    List<String> finalFriendList = CreateListUtils.arrayToList(friendName);
    List<String> friendList = InitFriendList(currentUser.getLoginName());
    if(friendList.containsAll(finalFriendList)){
        User finalUser = userService.findUserByName(currentUser.getLoginName());
         //session處理,如果存在該用戶的session,先將存在的session註銷,再生成新的session
         sessionHandlerByCacheMap(session,finalUser);

        return "redirect:/toIndex"; 
        }
    return "redirect:/toLoginVerify"; 
    }

效果圖如下:
這裏寫圖片描述

好友驗證的思路大概就是這樣的,大家可以試試實現,原諒我前端寫得有點爛,確實不太會前端。可能有一些好友爲空的情況我沒有考慮,這些就大家自己去加判斷了。如果有更好的建議可以一起探討下。有很多朋友可能會說,這些都是早就有的東西,直接用別人寫的不就行了嗎?我的理解是:很多東西需要我們自己去想,去實現,特別是編程思想,而且特別是剛學編程的小白。
後面我會繼續更新博客,跟大家一起探討如何通過Spring的session監聽及數據庫中的登錄狀態來控制用戶實現唯一登錄的問題,以及用websocket實現羣聊及單聊,這些功能也基本實現了,不過有一點小bug,主要是前端有點問題。。。。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章