JavaWeb实现好友验证的思路

来源:互联网 发布:nvidia cuda windows 编辑:程序博客网 时间:2024/05/17 09:47
需求分析:大家在一些网站注册账号的时候,有时会忘记密码或者账号被盗,正规的网站都是通过手机发验证码的,这可能要调用第三方来实现。因为我是自己做的小项目,这是想有这么个验证的流程,所以我这里就用好友验证来代替。思路分析: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();    }//初始化friendListpublic 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,主要是前端有点问题。。。。
原创粉丝点击