码迷,mamicode.com
首页 > 微信 > 详细

微信扫码登录

时间:2017-06-19 12:40:11      阅读:2702      评论:0      收藏:0      [点我收藏+]

标签:anim   分享   用户   数字   verify   logs   spi   release   print   

一、微信官方参考文档地址:

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN

首先你需要在微信开放平台申请一个微信网站应用,获取

AppID:aaaaaaaaabbcc

AppSecret: sfasfsafsafsafsads

二、jsp页面代码

<%@ page pageEncoding="UTF-8"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page session="true"%>
<!DOCTYPE html>
<html >
    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
        <link href="<%=request.getContextPath()%>/css/cas.css" rel="stylesheet" type="text/css"></link>
        <link href="/css/newsTextStyle.css" type="text/css" rel="stylesheet" />
        <link href="/css/login.css" type="text/css" rel="stylesheet" />
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="js/wxLogin.js"></script>
        <script type="text/javascript" src="js/popup_layer.js"></script>
        <style type="text/css">
        iframe{
            height:350px;
        }
            .ccidlogin {
                background: url(images/loginccid.jpg) no-repeat center top;
                width: 1200px;
                height: 620px;
                position: relative;
                margin: 0 auto;
            }

            .red-line {
                position: absolute;
                top: 273px;
                left: 0px;
                display: block;
                background: url(images/renline_04.gif) repeat-x left top;
                height: 81px;
                width: 100%;
                z-index: 0;
            }

            .ccidlogintext1 {
                position: absolute; top:280px;
                right: 130px;
            }

            .ccidlogintext2 {
                top: 244px;
                top: 241px\9;
                *top: 238px;
            }

            .ccidlogintext1 input,.ccidlogintext2 input {
                margin-left: 200px;
                width: 200px;
                height: 22px;
            }

            .ccid-jinr {
                position: relative;
                top: 265px;
                *top: 261px;
                left: 740px;
                width: 220px;
                height: 31px;
            }

            .ccid-btn {
                background: url(images/buttonn.gif) no-repeat 0 0;
                width: 91px;
                height: 31px;
                color: #fff;
                font-weight: bold;
                float: left;
                border: none;
                display: block;
                margin-right: 15px;
                cursor: pointer;
            }

            body,td {
                font-size: 12px;
            }

            .tab {
                position: absolute;
                top: 160px;
                right: 124px;
            }

            .tab4 {
                position: absolute;
                top: 410px;
                right: 560px;
                height: 100px;
                width: 543px;
                line-height: 20px;
            }

            .TabCon3 {
                position: absolute;
                top: 370px;
                right: 124px;
                width: 420px;
                height: 180px;
                line-height: 20px;
            }

            #TabCon1 {
                width: 420px;
                height: 180px;
                border-left: 0px solid;
                border-bottom: 0px solid;
                border-right: 0px solid;
            }

            #TabCon2 {
                width: 420px;
                height: 180px;
                border-left: 0px solid;
                border-bottom: 0px solid;
                border-right: 0px solid;
            }
            
            #TabCon3 {
                width: 420px;
                height: 180px;
                border-left: 0px solid;
                border-bottom: 0px solid;
                border-right: 0px solid;
            }
            #TabCon4 {
                width: 420px;
                height: 180px;
                line-height: 180px;
                text-align: center;
                border-left: 0px solid;
                border-bottom: 0px solid;
                border-right: 0px solid;
            }

            .xixi1 {
                width: 100%;
                height: 29px;
                line-height: 29px;
                background-image: url(images/news_bghover1.png);
                cursor: pointer;
                background-repeat: no-repeat;
            }
            
           

            .xixi2 {
                width: 100%;
                height: 29px;
                line-height: 29px;
                background-image: url(images/news_bghover2.png);
                background-repeat: no-repeat;
                cursor: pointer;
            }
            
             .xixi3 {
                width: 100%;
                height: 29px;
                line-height: 29px;
                background-image: url(images/news_bghover3.png);
                background-repeat: no-repeat;
                float:left;
                cursor: pointer;
            }
            .xixi4 {
                width: 100%;
                height: 29px;
                line-height: 29px;
                background-image: url(images/news_bghover3.png);/*background-image: url(images/news_bghover4.png)*/
                background-repeat: no-repeat;
                float:left;
                cursor: pointer;
            }

            .tab1 {
                width: 96px;
                height: 29px;
                line-height: 29px;
                float: left;
                text-align: center;
                cursor: pointer;
                color: #FFF;
            }

            .tab2 {
                width: 96px;
                height: 29px;
                line-height: 29px;
                float: left;
                text-align: center;
                cursor: pointer;
                color: #000;
            }
            .tab3 {
                width: 96px;
                height: 29px;
                line-height: 29px;
                float: left;
                text-align: center;
                cursor: pointer;
                color: #000;
            }
            .tab_4 {
                width: 96px;
                height: 29px;
                line-height: 29px;
                float: left;
                text-align: center;
                cursor: pointer;
                color: #000;
            }
            
            

            .tabInput {
                line-height: normal;
                width: 100%;
                display: inline-block;
                margin-bottom: 10px;
            }

            .tab_label {
                float: left;
                width: 30%;
                text-align: right;
                height: 24px;
                line-height: 24px;
            }
               /*底部链接*/
            #footer-link{
                width: 50px;
                height: 10px;
                float:right;
                font-color:red;
                
            }
          
        /* 仿淘宝登陆页面style.css */  
        *{margin: 0;padding: 0;}
        input{padding: 0;margin: 0;}
        body{font-family: "Microsoft YaHei";}
        .clear{clear: both;}
        /* .login-box-warp{background-color: #ffffff;border: 1px solid #dddddd;width: 350px;height: 390px;position: relative;margin-left: 61%;top: 188px;} */
        .login-box-warp{background-color: #ffffff;border: 1px solid #dddddd;width: 430px;height: 430px;position: relative;margin-left: 54%;top: 110px;}
        .login-tip{width: 300px;height: auto;position: absolute;top: 0;right: 0;}
        .login-switch{width: 52px;height: 52px;line-height: 52px;text-align: center;float: right;}
        .login-switch img{vertical-align: middle;}
        .pop-tip{border: 1px solid #f3d995;background-color: #fefcee;width: 143px;height: 28px;float: right;margin-right: 10px;margin-top: 8px;position: relative;}
        .pop-arrow{position: absolute;z-index: 10;top: 8px;right: 0;}
        .pop-arrow em{position: absolute;top: 0;left: 1px;overflow: hidden;width: 0;height: 0;border-style: solid;border-color: rgba(255,255,255,0);border-left-color: #f3d995;border-width: 6px 0 6px 6px;}
        .pop-arrow span{position: absolute;top: 0;left: 0;overflow: hidden;width: 0;height: 0;border-style: solid;border-color: rgba(255,255,255,0);border-left-color: #fefcee;border-width: 6px 0 6px 6px;}
        .pop-content{width: 100%;height: 28px;text-align: center;line-height: 22px;font-size: 12px;font-weight: 400;color: #df9c1f;}
        .pop-content img,.pop-content span{vertical-align: middle;padding: 0 2px}
        
        /* .login-content{width: 300px;height: auto;margin: 40px 25px 10px 25px;position: absolute;z-index: 20;} */
        .login-content{width: 300px;height: auto;margin: 60px 65px 10px 65px;position: absolute;z-index: 20;}
        .login-content-weixin{width: 300px;height: auto;margin: 20px 65px 10px 65px;position: absolute;z-index: 20;}
        .login-title{padding-bottom: 8px;font-size: 16px;font-weight: 700;color: #3c3c3c;}
        .login-msg{border: 1px solid #ffb4a8;width: 294px;height: 20px;line-height: 15px;padding: 3px;background-color: #fef2f2;}
        .login-msg img{padding-left: 3px;vertical-align: middle;}
        .login-msg span{font-size: 12px;color: #6c6c6c;vertical-align: middle;}
        .login-msg span a{font-size: 12px;color: #f40;text-decoration: none;}
        .login-msg span a:hover{cursor: pointer;}
        .qrcode-img{width: 125px;height: 125px;margin: 30px auto 20px auto;}
        .qrcode-desc{width: 100%;height: 50px;line-height: 50px;text-align: center;font-size: 12px;color: #9c9c9c;}
        .qrcode-desc img,.qrcode-desc span{vertical-align: middle;padding: 0 2px;}
        .qrcode-desc .mobile_weixin{color: #f40;}
        .field{border: 1px solid #dddddd;width: 300px;height: 40px;}
        .yzm{width: 300px;}
        .yzm .yzm_button{float: right;border-width: 0;width: 70px;height: 30px;margin-top: 25px;font-size: 16px;color: #fff;display: block;background-color: #ff4400;}
        .send_button{float: right;;width: 80px;height: 30px;border-width: 0;background-color: #ff4400;color: #ffffff;font-size: 14px;border-radius: 5px;margin-top: 25px;display: block;}
        .username_field{margin-top: 15px;}
        .password_field{margin-top: 20px;}
        .yzm_field{width: 200px;margin-top: 20px;float: left;}
        .field label{width: 40px;height: 40px;display: block;float: left;}
        .field input{border-width: 0;width: 240px;height: 40px;padding-left: 15px;font-size: 14px;display: block;float: left;outline: medium;}
        .login_submit{width: 300px;height: 40px;margin-top: 20px;}
        .login_submit button[type="submit"]{border-width: 0;background-color: #f40;color: #fff;width: 300px;height: 40px;line-height: 40px;text-align: center;font-size: 16px;font-weight: 700;border-radius: 3px;}
        .login_submit button[type="submit"]:hover{cursor: pointer;}
        .login_submit button[type="button"]{border-width: 0;background-color: #f40;color: #fff;width: 300px;height: 40px;line-height: 40px;text-align: center;font-size: 16px;font-weight: 700;border-radius: 3px;}
        .login_submit button[type="button"]:hover{cursor: pointer;}
        #bindWechat{border-width: 0;background-color: #f40;color: #fff;width: 300px;height: 40px;line-height: 40px;text-align: center;font-size: 16px;font-weight: 700;border-radius: 3px;}
        #bindWechat:hover{cursor: pointer;}
        .login-links{width: 300px;height: 20px;margin: auto;text-align: right;position: absolute;bottom: 20px;right: 20px;}
        .login-links a{text-decoration: none;padding-right: 15px;color: #6c6c6c;font-size: 12px;}
        .login-links a:hover{color: #f40;}
        
        </style>
        <%
            String yan1 = (String) ((HttpServletRequest) request).getSession().getAttribute("flag1");
            String yan2 = (String) ((HttpServletRequest) request).getSession().getAttribute("flag0");
            String yan3 = (String) ((HttpServletRequest) request).getSession().getAttribute("flag3");
            String yan4 = (String) ((HttpServletRequest) request).getSession().getAttribute("flag4");
            if (yan1 == null) {
                yan1 = "";
            }
            if (yan2 == null) {
                yan2 = "";
            }
            if (yan4 == null) {
                yan4 = "";
            }
            ((HttpServletRequest) request).getSession().removeAttribute("timeTemp");

            //int wait = Integer.parseInt(waitime);
            //错误次数
            String count =  (String)((HttpServletRequest) request).getSession().getAttribute("count");
            //int count = Integer.parseInt(((HttpServletRequest) request).getSession().getAttribute("count").toString());
            if (count == null || count == "") {
                count = "0";
            }
            int errorcount = Integer.parseInt(count);
            //int errorcount = count;
        %>
        <script language="javascript">
        //--------------微信参数----------------------
        //var appid="wxfc13b6653a46d2e7";//测试版
        //var weiChatUrl = "eip.ccidit.com";
        
        var appid="wxf952746adb0bbb46";//正式版
        var weiChatUrl = "oa.ccidgroup.com";
      //--------------微信参数----------------------
            $(function(){
                $("#login_pwd,#login_pwd1").click(function(){
                    $("#mima").css("display","block");
                    $("#saoma").css("display","none");
                    $("#weixin").css("display","none");
                });
                $("#login_mm").click(function(){
                    $("#saoma").css("display","block");
                    $("#mima").css("display","none");
                    $("#weixin").css("display","none");
                });
            });
            //生成二维码
            setTimeout(function(){
                var obj = new WxLogin({
                      id:"login_container", 
                      appid: appid, 
                      scope: "snsapi_login",
                      redirect_uri: encodeURI("http://"+weiChatUrl+"/weChatLogin_get_Code.action?param=true_noname_2_noyanzhengma_true"),
                      state: "3d6be0a4035d839573b04816624a415e#wechat_redirect",
                      style: "",
                      href: "http://oa.ccidgroup.com/css/weChat.css"
                });
            },50);
            
            var isbindWechat = "false";
            var username = "noname";
            var password = "nopassword";
            //微信绑定生成二维码前需要填写用户名密码
            function mybindWechat(){
                isbindWechat = "true";
                   username = $.trim($("#weixinusername").val());
                   password = $.trim($("#weixinpassword").val());
                if(username != "" && password != ""){
                    geterweimatobing(username,password);
                    $("#saoma").css("display","block");
                    $("#mima").css("display","none");
                    $("#weixin").css("display","none");
                }else{ 
                    alert("请输入用户名密码");
                }
            }
            //验证用户名和密码的正确性
            function checkNameAndPass(){
                var name = $.trim($("#weixinusername").val());
                   var pass = $.trim($("#weixinpassword").val());
                   if(username != "" && password != ""){
                       var URL = "http://"+weiChatUrl+"/weChatLogin_mycheckNameAndPass.action?param=true_loginByPhone&name="+name+"&pass="+pass;
                       $.ajax({
                        url: URL,
                        type: post,
                        //dataType: ‘json‘,
                        timeout: 10000,
                        success: function (data) {
                            if($.trim(data)=="true"){
                              mybindWechat();        
                            }else{
                                alert("用户名密码不匹配");
                            }
                        },
                        fail: function (err) {
                          console.log(err)
                        }
                      })
                }else{
                    alert("请输入用户名密码");
                }
            }
            
            
            //跳转输入绑定微信页面
            function bingdWeChatBefore(){
                $("#saoma").css("display","none");
                $("#mima").css("display","none");
                $("#weixin").css("display","block");
            }
            
             //返回密码登录
            function returnMima(){
                $("#saoma").css("display","none");
                $("#mima").css("display","block");
                $("#weixin").css("display","none");
            }
            //动态生成二维码(扫码绑定)
            function geterweimatobing(username,password){
                var param = "true_"+username+"_"+password+"_noyanzhengma_"+isbindWechat;
                setTimeout(function(){
                    var obj = new WxLogin({
                          id:"login_container", 
                          appid: appid, 
                          scope: "snsapi_login",
                          redirect_uri: encodeURI("http://"+weiChatUrl+"/weChatLogin_get_Code.action?param="+param),
                          state: "3d6be0a4035d839573b04816624a415e#wechat_redirect",
                          style: "",
                          href: "http://"+weiChatUrl+"/css/weChat.css"
                    });
                },10);
                isbindWechat = "false";
            }
            
            //动态生成二维码(扫码登录)
            function geterweimatologin(){
                var username = "noname";
                var password = "nopassword";
                var param = "true_"+username+"_"+password+"_noyanzhengma_"+isbindWechat;
                setTimeout(function(){
                    var obj = new WxLogin({
                          id:"login_container", 
                          appid: appid, 
                          scope: "snsapi_login",
                          redirect_uri: encodeURI("http://"+weiChatUrl+"/weChatLogin_get_Code.action?param="+param),
                          state: "3d6be0a4035d839573b04816624a415e#wechat_redirect",
                          style: "",
                          href: "http://"+weiChatUrl+"/css/weChat.css"
                    });
                },10);
                isbindWechat = "false";
            }
            
            //var cTime = 100;
            var count = <%=count%>;
            function test() {
                ale();
                if (cTime >= 1) {
                    //TimeClose();
                }
            }
            //倒计时
            function TimeClose() {
                window.setTimeout(TimeClose(), 1000);
                if (cTime <= 0) {
                    this.ShowTime.innerHTML = "<input type=‘submit‘ class=‘ccid-btn‘ value=‘登录‘ style=‘float: none;display: inline;‘ ></input>" + "<input type=‘reset‘  class=‘ccid-btn‘ value=‘重置‘ style=‘float: none;display: inline;‘ ></input>";
                } else {

                    if (Div(cTime, 60) > 0) {
                        if (cTime % 60 === 0) {
                            this.ShowTime.innerHTML = "您累计输入密码错误" + count + "次,倒计时" + Div(cTime, 60) + "分钟可以重新登录";

                        } else {
                            this.ShowTime.innerHTML = "您累计输入密码错误" + count + "次,倒计时" + Div(cTime, 60) + "分钟" + (cTime % 60) + "秒可以重新登录";
                        }

                    } else {
                        this.ShowTime.innerHTML = "您累计输入密码错误" + count + "次,倒计时" + (cTime % 60) + "秒可以重新登录";
                    }
                    cTime--;
                }
            }
            //两个数整除运算
            function Div(n1, n2) {
                var rslt = n1 / n2; //
                if (rslt >= 0) {
                    rslt = Math.floor(rslt); //返回值为小于等于其数值参数的最大整数值。
                } else {
                    rslt = Math.ceil(rslt); //返回值为大于等于其数字参数的最小整数。
                }
                return rslt;
            }
   
            function ale() {
                var ua = navigator.userAgent.toLowerCase();
                var IeValue = ua.indexOf("msie");
                if (ua.substring(IeValue + 4, IeValue + 6) < 9 && ua.substring(IeValue + 4, IeValue + 6) > 1)
                    alert(" 目前业务系统V1.02只支持IE9及以上版本和火狐浏览器V36及以上版本 。\n 您当前浏览器版本:IE" + ua.substring(IeValue + 4, IeValue + 8) + ",请更换浏览器。");
            }
            
            
            function fromCCIDIT(){
                var url = "/baseServer?servicename=extLogin&sysId=CCIDIT";
                window.location.href=url;
            }
            
            function fromRKXOA(){
                var url = "/baseServer?servicename=extLogin&sysId=RKXOA";
                window.location.href=url;
                
            }
            //获取验证码
            function mysend_yzm(){
                var mobilePhone = $.trim($("#mobilephone").val());
                    if(!(/^1[34578][0-9]{9}/.test(mobilePhone))) 
                    {
                        alert("请输入有效的手机号码!"); 
                        return false; 
                    }else{
                        showWaitTime();
                        $.ajax({
                              url: "http://"+weiChatUrl+"/weChatLogin_getPhoneCode.action?param=true_loginByPhone&mobilePhone="+mobilePhone,
                              type: get,
                              //dataType: ‘json‘,
                              timeout: 10000,
                              success: function (data) {
                                  console.log(data);
                                //if($.trim(data)=="success"){
                                    //showWaitTime();
                                //}
                              },
                              fail: function (err) {
                                console.log(err)
                              }
                            })
                    }
            }
            var WaitTime =60;
            var cce;
            //显示等待时间
            function showWaitTime(){
                cce = setTimeout(function() {
                    showWaitTime();
                }, 1000);
                
                if(WaitTime>0){
                    WaitTime = WaitTime-1;
                    $("#send_yzm").html(WaitTime+"s");
                    document.getElementById("send_yzm").disabled=true; 
                }else{
                    window.clearTimeout(cce);
                    WaitTime = 60;
                    $("#send_yzm").html("发送验证码");
                    document.getElementById("send_yzm").disabled=false; 
                }
            }
            
            //手机验证码登录
            function loginByPhone(){
                var mobilePhone = $("#mobilephone").val();
                var phoneCode = $("#mobileyzm").val();
                var send_yzm = $("#send_yzm").html();
                
                if(mobilePhone!="" && phoneCode !=""){
                    if(send_yzm == "发送验证码"){
                        alert("验证码无效,请重新验证");
                    }else{
                        $.ajax({
                            url: "http://"+weiChatUrl+"/weChatLogin_loginByPhone.action?param=true_loginByPhone&mobilePhone="+mobilePhone+"&phoneCode="+phoneCode,
                            type: get,
                            //dataType: ‘json‘,
                            timeout: 10000,
                            success: function (data) {
                                var Data = $.trim(data);
                                if(Data == "noThisPhone"){
                                    alert("请输入注册手机号!");
                                }else if(Data == "error"){
                                    alert("登录失败!");
                                }else if(Data == "noThisCode"){
                                    alert("手机验证码错误!");
                                }else{
                                    window.location.href="frameworkMgt_sysIndex.action";
                                }
                            },
                            fail: function (err) {
                              console.log(err)
                            }
                          })
                    }
                }else{
                    alert("请先验证您的手机号");
                }
                
            }
           
        </script>

    </head>
    <body style="background-color:#fff; position:relative; z-index:99; overflow:hidden;" onload="test()">
        <form id="fm1" class="fm-v clearfix" method="post" action="/login">
            <input type="hidden"  id="waitime"> <input type="hidden" value="<%=count%>" id="count">
            <div class="red-line"></div>
            <div class="ccidlogin">
                   <div class="tab4" style="padding-top: 20px; font-size: 14px; color:  #ff4500;"  >
                   <div style="font-size: 14px; color:  #000000;">
                       其他登录: <!--<a href="Demo-B/index.jsp"><img src="images/login-icon.gif" style="width:50px;height:20px;"> 
                        <img src="images/logobj_02.gif" style="width:50px;height:20px;"> 
                       DEMO-B
                       </a>
                       <span style="width:10px;">|</span>-->
                       <a href="/account?action=sparkLogin">统一身份认证登录    </a>    
                   </div>
                  <br/>
                  <font style="font-weight: bolder;">温馨提示:</font> 
                   <br/>目前系统只支持火狐和IE9及以上版本的浏览器,推荐使用火狐浏览器。 
                     <br/>
                     (<a href="http://download.firefox.com.cn/releases-sha2/full/45.0/zh-CN/Firefox-full-latest.exe">下载火狐桌面浏览器</a>)
                     (<a href="http://219.141.211.80:8963/OurIMServer/00/apk/EIP.apk">下载安卓手机客户端</a>)
                     (<a href="http://hxtime.com/e/ios.html">下载苹果手机客户端</a>)
                     <br/>技术支持:项浩鹏   &nbsp 电话:8855-9120
                  </div> 
                    
                <!-- 仿淘宝登陆页面html -->        
                <div class="login-box-warp">
                    <!--微信扫码登录-->
                    <div id="saoma" style="display: none">
                        <div class="login-tip">
                            <div class="login-switch">
                                <img id="login_pwd" src="images/login-1/diannao.png">
                            </div>
                            <!-- <div class="pop-tip">
                                <div class="pop-arrow">
                                    <em></em>
                                    <span></span>
                                </div>
                                <div class="pop-content">
                                    <img src="images/login-1/anquan.png">
                                    <span>密码登录在这里</span>
                                </div>
                            </div> -->
                            <div class="clear"></div>
                        </div>
                        <div class="login-content-weixin">
                           <!--  <div class="login-title">手机扫码,安全登录</div> -->
                            <div id="login_container">
                                <!-- <img src="images/login-1/erweima1.png" width="125" height="125"> -->
                            </div>
                           <!--  <div class="qrcode-desc">
                                <img src="images/login-1/saoyisao.png">
                                <span>打开<a class="mobile_weixin"> 手机微信 </a>扫一扫登录</span>
                            </div> -->
                        </div>
                        <div class="login-links">
                            <a id="login_pwd1" href="#">密码登录</a>
                        </div>
                    </div>
            
                    <!--用户名密码登录-->
                    <div id="mima">
                        <div class="login-tip">
                            <div class="login-switch" onclick="geterweimatologin()">
                                <img id="login_mm" src="images/login-1/erweima.png">
                            </div>
                            <div class="pop-tip">
                                <div class="pop-arrow">
                                    <em></em>
                                    <span></span>
                                </div>
                                <div class="pop-content">
                                    <img src="images/login-1/anquan.png">
                                    <span>微信登录更快捷</span>
                                </div>
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div class="login-content">
                            <div id="login_title_div" class="login-title">密码登录</div>
                            <% 
                            if(yan1!="" || yan2 !="" || yan4 !=""){
                            %>
                            <div class="login-msg" style="">
                                <img src="images/login/warning.png">
                                <span id="warning_msg"><%=yan1%><%=yan2%><%=yan4%></span>
                            </div>
                             <% 
                                }
                            %>
                            <div class="login_form">
                                 <%
                                       if (errorcount <5) {
                                   %>
                                <div id="username_div" class="field username_field">
                                    <label for="username"><img src="images/login-1/user.png" width="40" height="40"></label>
                                    <input id="username" type="text" name="username" placeholder="会员名/邮箱/手机号" required="required">
                                </div>
                               
                                <div id="password_div" class="field password_field">
                                    <label for="password"><img src="images/login-1/pwd.png" width="40" height="40"></label>
                                    <input id="password" type="password" name="password" required="required">
                                </div>
                                <%
                                       }
                                   %>
                                 <%
                                ((HttpServletRequest) request).getSession().setAttribute("flag0",
                                        "");
                                    %>
                                    
                                   <%
                                       if (3<= errorcount && errorcount <5) {
                                   %>
                                <div id="yzm_div" class="yzm">
                                    <div class="field yzm_field">
                                        <label for="yzm"><img src="images/login-1/pwd.png" width="40" height="40"></label>
                                        <input id="yanzhengma" type="text" name="yanzhengma" style="width: 130px"  required="required"> 
                                    </div>
                                    <img class="yzm_button" src="<%=request.getContextPath()%>yanzhengma.jsp"></img>
                                    <div class="clear"></div>
                                </div>
                                <%
                                    }
                                %>
                                
                                
                                <%
                                    ((HttpServletRequest) request).getSession().setAttribute("flag1","");
                                
                                %>
                                <%
                                       if (5<=errorcount) {
                                     ((HttpServletRequest) request).getSession().setAttribute("logunRandomNum","");
                                   %>
                                <div id="mobilephone_div" class="field username_field" >
                                    <label for="mobilephone"><img src="images/login-1/pwd.png" width="40" height="40"></label>
                                    <input id="mobilephone" type="text" name="mobilephone" placeholder="手机号">
                                </div>
                                <div id="mobileyzm_div" class="yzm"  >
                                    <div class="field yzm_field">
                                        <label for="mobileyzm"><img src="images/login-1/pwd.png" width="40" height="40"></label>
                                        <input id="mobileyzm" type="text" name="mobileyzm" style="width: 130px" >
                                    </div>
                                    <button id="send_yzm" class="send_button" type="button" onclick="mysend_yzm()">发送验证码</button>
                                    <div class="clear"></div>
                                </div>
                                <%
                                       }
                                   %>
                                   <%
                                       if (errorcount<5) {
                                   %>
                                <div class="login_submit">
                                    <button id="login-button" type="submit">登 录</button>
                                </div>
                                 <%
                                       }
                                   %>
                                   <%
                                       if (errorcount>=5) {
                                   %>
                                <div class="login_submit">
                                    <button id="login-button" type="button" onclick="loginByPhone()">手机登录</button>
                                </div>
                                 <%
                                       }
                                   %>
                            </div>
                        </div>
                        <!-- <div class="login-links">
                            <a href="">忘记密码</a>
                        </div> -->
                        <div class="login-links" >
                            <a id="weixinbd" onclick="bingdWeChatBefore()">绑定微信</a>
                        </div>
                    </div>
                
                    <!--微信绑定登录-->
                    <div id="weixin" style="display: none">
                        <div class="login-tip">
                            <div class="login-switch" onclick="returnMima()">
                                <img id="login_mm" src="images/login-1/diannao.png">
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div class="login-content">
                            <div id="login_title_div" class="login-title">微信绑定</div>
                            <% 
                            if(yan1!="" || yan2 !="" || yan4 !=""){
                            %>
                            <div class="login-msg" style="">
                                <img src="images/login/warning.png">
                                <span id="warning_msg"><%=yan1%><%=yan2%><%=yan4%></span>
                            </div>
                             <% 
                                }
                            %>
                            <div class="login_form">
                                <div id="username_div" class="field username_field">
                                    <label for="username"><img src="images/login-1/user.png" width="40" height="40"></label>
                                    <input id="weixinusername" type="text" name="weixinusername" placeholder="会员名/邮箱/手机号" >
                                </div>
                               
                                <div id="password_div" class="field password_field">
                                    <label for="password"><img src="images/login-1/pwd.png" width="40" height="40"></label>
                                    <input id="weixinpassword" type="password" name="password" >
                                </div>
                                
                                <div class="login_submit">
                                     <button  type="button" onclick="checkNameAndPass()">下 一 步</button>
                                </div>
                                   
                            </div>
                        </div>
                        <!-- <div class="login-links">
                            <a href="">忘记密码</a>
                        </div> -->
                        <div class="login-links" >
                            <a onclick="returnMima()">返回</a>
                        </div>
                    </div>
                </div>

                <%
                    if ("true".equals(yan3)) {
                %>
                <div class="TabCon3">
                    <span style="color: red">对不起,您当前不具有外网登录权限.</span>
                    <!-- <br/>请您访问内网地址: <a href="http://172.16.80.23">http://192.168.80.30</a> -->
                </div>

                <%
                    }
                %>
            </div>
            <input type="hidden" name="loginTemp" value="login"></input> <input type="hidden" name="_eventId" value="submit"></input>
            <div id="sidebar">
                <div id="list-languages"></div>
            </div>
        </form>
        
        <script type="text/javascript">
            function login() {
                var username = document.getElementById(username).value;
                var upwd = document.getElementById(password).value;
                if (username === ‘‘ || upwd === ‘‘) {
                    alert(请输入正确的用户名、密码);
                } else {
                    document.forms[0].action = "/login";
                    document.forms[0].submit();
                }
            }
        </script>
        <script type="text/javascript">
            var loginstr = document.forms[0].action;
            function setTab03Syn(i) {
                selectTab03Syn(i);
            }

            function selectTab03Syn(i) {
                switch (i) {
                    case 1:
                        document.forms[0].action = loginstr;
                        document.getElementById("TabCon1").style.display = "block";
                        document.getElementById("TabCon2").style.display = "none";
                        document.getElementById("TabCon3").style.display = "none";
                        document.getElementById("TabCon4").style.display = "none";
                        document.getElementById("font1").style.color = "#ffffff";
                        document.getElementById("font2").style.color = "#000000";
                        document.getElementById("font3").style.color = "#000000";
                        document.getElementById("font4").style.color = "#000000";
                        break;
                    case 2:
                        document.forms[0].action = "sLoginServlet";
                        document.getElementById("TabCon1").style.display = "none";
                        document.getElementById("TabCon3").style.display = "none";
                        document.getElementById("TabCon4").style.display = "none";
                        document.getElementById("TabCon2").style.display = "block";
                        document.getElementById("font1").style.color = "#000000";
                        document.getElementById("font3").style.color = "#000000";
                        document.getElementById("font4").style.color = "#000000";
                        document.getElementById("font2").style.color = "#ffffff";
                        break;
                        
                    case 3:
                        document.forms[0].action = "sLoginServlet";
                        document.getElementById("TabCon1").style.display = "none";
                        document.getElementById("TabCon2").style.display = "none";
                        document.getElementById("TabCon4").style.display = "none";
                        document.getElementById("TabCon3").style.display = "block";
                        document.getElementById("font1").style.color = "#000000";
                        document.getElementById("font2").style.color = "#000000";
                        document.getElementById("font4").style.color = "#000000";
                        document.getElementById("font3").style.color = "#ffffff";
                        break;
                        
                    case 4:
                        document.forms[0].action = "sLoginServlet";
                        document.getElementById("TabCon1").style.display = "none";
                        document.getElementById("TabCon2").style.display = "none";
                        document.getElementById("TabCon3").style.display = "none";
                        document.getElementById("TabCon4").style.display = "block";
                        document.getElementById("font1").style.color = "#000000";
                        document.getElementById("font2").style.color = "#000000";
                        document.getElementById("font3").style.color = "#000000";
                        document.getElementById("font4").style.color = "red";
                        break;
                }
            }

            $(document).ready(function () {

            var t9 = new PopupLayer({
            trigger: "#ele9",
                    popupBlk: "#blk9",
                    closeBtn: "#close9",
                    useOverlay: true,
                    useFx: true,
                    offsets: {
                    x: 0,
                            y: - 41
                    }
            });
                    t9.doEffects = function (way) {
                    if (way == "open") {
                    this.popupLayer.css({opacity: 0.3}).show(300, function () {
                    this.popupLayer.animate({
                    left: ($(document).width() - this.popupLayer.width()) / 2,
                            top: (document.documentElement.clientHeight - this.popupLayer.height()) / 2 + $(document).scrollTop(),
                            opacity: 0.8
                    }, 300, function () {
                    this.popupLayer.css("opacity", 1)
                    }.binding(this));
                    }.binding(this));
                    } else {
                    this.popupLayer.animate({
                    left: this.trigger.offset().left,
                            top: this.trigger.offset().top,
                            opacity: 0.1
                    }, {duration: 200, complete: function () {
                    this.popupLayer.css("opacity", 1);
                            this.popupLayer.hide();
                    }.binding(this)});
                    }


                    $(#ele9).click();
                    }});

        </script>    
    </body>
</html>

 

上面的代码比较乱,其实有关微信的代码只有以下这些:

1、导入微信二维码支持js(本例中,把此js下载放到本地了)

<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

2、在body中写一个div用来显示二维码:

<div id="login_container"></div>

3、在js中调用以下方法来生成二维码

var appid="aaaaaaaaaaaaaaabbbbcc";//微信应用提供的appid
var weiChatUrl = "oa.ccidgroup.com";

//动态生成二维码(扫码登录)
function geterweimatologin(){
     var username = "noname";
     var password = "nopassword";
     var param = "true_"+username+"_"+password+"_noyanzhengma_"+isbindWechat;
     setTimeout(function(){
         var obj = new WxLogin({
         id:"login_container", 
         appid: appid, 
         scope: "snsapi_login",
         redirect_uri: encodeURI("http://"+weiChatUrl+"/weChatLogin_get_Code.action?param="+param),
         state: "3d6be0a4035d839573b04816624a415e#wechat_redirect",
         style: "",
         href: "http://"+weiChatUrl+"/css/weChat.css"
          });
         },10);
     isbindWechat = "false";
 }

三、java后台代码

package com.ccidit.features.weChatLogin.action;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.struts2.ServletActionContext;

import com.ccidit.core.cas.CCIDCAS;
import com.ccidit.core.common.jdbc.dao.util.JDBCTools;
import com.ccidit.core.util.sendSms.SingletonClient;
import com.ccidit.features.po.UserLogMessage;
import com.ccidit.platform.sdk.Client;
import com.common.core.base.BaseAction;
import com.common.core.util.Md5Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 微信登录
 * @author gaoyipeng
 *
 */
public class WeChatLoginAction   extends BaseAction {
    String appid = "aaaaaaaaaabbbbccc";
    String secret = "asdfasdfasddfsadfasdf";
    
    String [] stringArr;
    private static Map<String, UserLogMessage> userList = new HashMap<String, UserLogMessage>(); // 登录错误的用户Map集合
    private static String userName;
    private Map<String,Object> resultMap;
       public Map<String, Object> getResultMap() {
           return resultMap;
       }

       public void setResultMap(Map<String, Object> resultMap) {
           this.resultMap = resultMap;
       }
       
       
    /**
     * 请求CODE
     * @throws IOException 
     */
    public String get_Code() throws IOException {
        HttpServletRequest req = ServletActionContext.getRequest();
        HttpServletResponse resp = ServletActionContext.getResponse();
        String param = req.getParameter("param");
        stringArr= param.split("_");
        String weChatLogin = stringArr[0];
        String username = stringArr[1];
        String password = stringArr[2];
        String yanzhengma = stringArr[3];
        String code = req.getParameter("code");
        String state = req.getParameter("state");
        String get_Userinfo =get_Access_Token(req,resp,code, state);
        if(get_Userinfo.equals("true")){
            return "openFirstPage";
        }else if(get_Userinfo.equals("noNameAndPass")){
            ((HttpServletRequest) req).getSession().setAttribute("flag0", "该账号未绑定微信");
            req.setAttribute("yz", "该账号未绑定微信");
            return "noNameAndPass";
        }else{
            return "openFirstPage";
        }
        
        //return "get_Code";
    }

    /**
     * 通过code获取access_token
     * @throws IOException 
     */
    public String get_Access_Token(HttpServletRequest req,HttpServletResponse resp,String code, String state) throws IOException {
        String send_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
            appid + "&secret=" + secret + "&code=" + code +
            "&grant_type=authorization_code";
        URL myURL = null;
        try {
            myURL = new URL(send_url);
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        HttpsURLConnection httpsConn = null;
        try {
            httpsConn = (HttpsURLConnection) myURL.openConnection();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // 取得该连接的输入流,以读取响应内容
        InputStreamReader insr = null;

        try {
            insr = new InputStreamReader(httpsConn.getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

     // 读取服务器的响应内容并显示
        int respInt = 0;

        try {
            respInt = insr.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String result = "";
        while (respInt != -1) {
            //System.out.print((char) respInt);
            result += (char) respInt;
            try {
                respInt = insr.read();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        JSONObject jsStr = JSONObject.fromObject(result);
        int a= result.indexOf("errcode");
        if(a>0){
            //redirectTo(req, resp, 0);
            return "error";
        }
        String access_token = jsStr.getString("access_token");
        String openid = jsStr.getString("openid");
        
        String get_Userinfo = get_Userinfo(req,resp,access_token,openid);
        return get_Userinfo;
    }
    
    /**
     * 获取用户基本信息
     * @throws IOException 
     */
    public String get_Userinfo(HttpServletRequest req,HttpServletResponse resp,String access_token,String openid) throws IOException{
        String openFirstPage="false";
        String send_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                access_token + "&openid=" + openid;
        
        StringBuilder sb = new StringBuilder(send_url);
        HttpMethod method = new PostMethod(sb.toString());
        HttpClient httpclient = new HttpClient();
         
        try {
            httpclient.executeMethod(method);
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
         
        String result = null;
        try {
            result = new String(method.getResponseBody(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        JSONObject jsStr = JSONObject.fromObject(result);
        String unionid = jsStr.getString("unionid");
        String headimgurl = jsStr.getString("headimgurl");
        String nickname = jsStr.getString("nickname");
        String checkisbingwechat = checkIsBingWeChat(unionid);//判断用户是否已经绑定微信

        if(!checkisbingwechat.equals("false")){
            if(moniLogin(req,resp,checkisbingwechat,stringArr[2],"noyanzheng")){
                //saveLoginLog(checkisbingwechat);//添加微信登陆日志
                bindWeChat(unionid,headimgurl,nickname,checkisbingwechat);//此处执行此绑定方法,只是为了更新头像
                openFirstPage = "true";
            };
            
        }else{//绑定微信
            String checklogin="";
            if(!stringArr[1].equals("noname")){//是否有用户名
                try {
                     checklogin = checkLogin(req,resp,stringArr[1],stringArr[2],stringArr[3]);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(checklogin.equals("true")){
                    if(moniLogin(req,resp,stringArr[1],stringArr[2],stringArr[3])){
                        //saveLoginLog(stringArr[1]);//添加微信登陆日志
                        if(stringArr[4].equals("true")){//是否绑定,是
                            if(bindWeChat(unionid,headimgurl,nickname,stringArr[1])){
                                openFirstPage = "true";
                            }
                        }else{
                            openFirstPage = "true";
                        }
                    };
                }else{
                    openFirstPage = "noNameAndPass";
                }
            }else{
                ((HttpServletRequest) req).getSession().setAttribute("unionid",unionid);
                ((HttpServletRequest) req).getSession().setAttribute("headimgurl",headimgurl);
                ((HttpServletRequest) req).getSession().setAttribute("nickname",nickname);
                openFirstPage = "noNameAndPass";
            }
        }
        return openFirstPage;
        
    }
    /**
     * 如果已经绑定微信则登录
     */
    public Boolean moniLogin(HttpServletRequest request,HttpServletResponse response,String username,String password,String yanzhengma){
        //HttpServletRequest request = ServletActionContext.getRequest();
        //HttpServletResponse response = ServletActionContext.getResponse();
        try {
            CCIDCAS.checkLogin(request, response, username, password, yanzhengma,4);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return true;
    }
    
    /**
     * 判断用户是否已经 绑定微信,已经绑定返回绑定CName
     */
    public String checkIsBingWeChat(String unionid){
        //此处通过用户名,密码查询数据库对应人员unionid是否存在,存在即已经绑定微信,否则,未绑定
        //String sql = "select CName from Base_User where ID = (select baseuser_id from base_user_system where system_loginname=‘"+unionid+"‘)";
        String sql = "select CName from Base_User where Unionid=‘"+unionid+"‘";
        String passwd;
        Connection conn = JDBCTools.getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        String DBunionName="false";
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            //System.out.println("没有绑定");
            while (rs.next()) {
                DBunionName = rs.getString("CName");
                //System.out.println("绑定了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(conn, stmt, rs);
        }
        return DBunionName;
    }
    
    /**
     * 绑定微信
     */
    public static boolean bindWeChat(String unionid,String headimgurl,String nickname,String username){
        /*String sql= "INSERT INTO base_user_system (id, baseuser_id,_baseuser_name,system_name,system_loginname, binding_time, nickname, headimgurl)"+
                 "(select ‘"+id+"‘,id,‘"+"weChat‘,‘"+username+"‘,‘"+unionid+"‘,‘"+binding_time+"‘,‘"+nickname+"‘,‘"+headimgurl+"‘ from Base_User where CName=‘"+username+"‘)";*/
         
         String sql= "update Base_User set Unionid=‘"+unionid+"‘,HeadImgUrl=‘"+headimgurl+"‘,HeadImgOrder=‘2‘ where CName=‘"+username+"‘";
         String passwd;
         Connection conn = JDBCTools.getConnection();
         Statement stmt = null;
         int rs = 0;
         boolean hasuser = false;
         try {
             stmt = conn.createStatement();
             rs = stmt.executeUpdate(sql);
             hasuser = true;
         } catch (Exception e) {
             e.printStackTrace();
             hasuser = false;
         } 
         return hasuser;
    }
    
    
    /**
     * 登录前的一些验证
     */
    public String checkLogin(ServletRequest request, ServletResponse response, String uname, String upass, String yanzhengma) throws IOException {
        boolean isloginTem; // 是否已登录标识
        upass = Md5Utils.md5(upass);
        isloginTem = isLoginVal(uname, upass);// 判断用户录入的用户名和密码是否匹配

        if (isloginTem) { // 如果用户名和密码匹配,则判断验证码是否正确,和执行登录间隔机制
                String yan = (String) ((HttpServletRequest) request).getSession().getAttribute("rand");
                if (true) { // 如果验证码正确
                    return "true";
                } else {// 如果验证码错误,怎返回登录页面
                    ((HttpServletRequest) request).getSession().setAttribute("flag1", "验证码输入错误");
                    request.setAttribute("yz", "验证码输入错误");
                    redirectTo(request, response, 0);
                    return "false";
                }
        } else {// 如果用户名与密码不匹配
            ((HttpServletRequest) request).getSession().setAttribute("flag0", "账号或密码错误");
            request.setAttribute("yz", "账号或密码错误");
            redirectTo(request, response, 0); // 返回登录页面
            return "false";
        }
    }
        
        
    /**
     * 根据参数跳转页面
     *
     * @param request
     * @param response
     * @param jumpType 0为登陆页面 ;1为用户请求的页面;3用IP方式请求登录页面;4用户信息页面
     * @throws IOException
     */
    public static void redirectTo(ServletRequest request, ServletResponse response, int jumpType) throws IOException {
        HttpServletRequest rq = (HttpServletRequest) request;
        HttpServletResponse rp = (HttpServletResponse) response;
        String redirectURL = getFullUrl(request, jumpType);
        String h5 = request.getParameter("h5");
        String yz = (String) rq.getAttribute("yz");
        //request.setAttribute("userName", "123");
        //String userName = (String) request.getAttribute("userName");
        if("/h5".equals(h5)){
            jumpType=6;
        }
        switch (jumpType) {
            case 0:
                redirectURL += "&userName="+userName+"&yz="+yz;
                rp.sendRedirect(redirectURL);
                break;
            case 1:
                rp.sendRedirect(redirectURL);
                break;
            case 3:
                redirectURL = Client.getProperties("ythIP") + "/casLoginView.jsp?loginTemp=tologin";
                rp.sendRedirect(redirectURL);
                break;
            case 4:
                redirectURL = "http://127.0.0.1/sUserInfo.jsp";
                rp.sendRedirect(redirectURL);
                break;
            case 5:
                redirectURL = Client.getProperties("h5login") ;
                rp.sendRedirect(redirectURL);
                break;
            case 6:
                redirectURL = Client.getProperties("h5login") ;
                rp.sendRedirect(redirectURL);
                break;
            case 7:
                redirectURL = Client.getProperties("mobileURL") ;
                rp.sendRedirect(redirectURL);
                break;
                
            case 8:
                redirectURL = Client.getProperties("mobileURLCSIP") ;
                rp.sendRedirect(redirectURL);
                break;     
        }
    }
    
    /**
     * 得到请求的完全路径,包括参数
     *
     * @param i 0为登陆页面 ;1为用户请求路径; 2为只获取ServerName;
     * @param request
     * @return 返回用请求的URL路径
     */
    public static String getFullUrl(ServletRequest request, int i) {
        StringBuilder url = new StringBuilder();
        String scheme = request.getScheme();
        String sname = request.getServerName();
        String name = Client.getProperties(sname); //根据server Name 查找登录地址
        String serverName =name;
        if(name.contains(",")){
        serverName = name.substring(0, name.indexOf(","));
        }
//        String serverName =  Client.getProperties("ythurl");
        int port = request.getServerPort();
        if (port < 0) {
            port = 80; // Work around java.net.URL bug
        }
        //url.append(scheme);
        //url.append("://");
        //url.append(request.getServerName());
        url.append(serverName);
        if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
            url.append(‘:‘);
            url.append(port);
        }
        // url.append(((HttpServletRequest) request).getRequestURI());
        String queryString = ((HttpServletRequest) request).getQueryString();
        if (i == 0) {

            url.append(name.substring(name.indexOf(",") + 1));
        } else {
            String requestURI = ((HttpServletRequest) request).getRequestURI();

            if ("/login".equals(requestURI) || i == 2) {

                return url.toString();

            } else {
                url.append(requestURI);
                if (queryString != null) {
                    url.append(‘?‘).append(queryString);
                }
            }

        }
        return url.toString();
    }

    /**
     * 根据用户名密码验证登陆
     *
     * @param uname
     * @param upass
     * @return "true"用户名密码正确 ; "false"密码错误
     */
    public static boolean isLoginVal(String uname, String upass) {
        boolean isloginTemp = false;
        if (uname != null && upass != null) {
            Matcher matcher = Pattern.compile("^[0-9a-zA-Z_-]+$").matcher(uname);
            if (matcher.find()) { // 用户名中,是否有特殊字符
                isloginTemp = queryUser(uname, upass);
                userName = uname;
            } else {
                isloginTemp = false;// 如果用户名中包含特殊字符,则返回false
            }
        }
        return isloginTemp;
    }
    
    /**
     * 验证用户名密码的匹配性
     */
    public void mycheckNameAndPass() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String uname = request.getParameter("name");
        String upass = Md5Utils.md5(request.getParameter("pass"));
        boolean isloginTemp = false;
        if (uname != null && upass != null) {
            Matcher matcher = Pattern.compile("^[0-9a-zA-Z_-]+$").matcher(uname);
            if (matcher.find()) { // 用户名中,是否有特殊字符
                isloginTemp = queryUser(uname, upass);
                userName = uname;
            } else {
                isloginTemp = false;// 如果用户名中包含特殊字符,则返回false
            }
        }
        try {
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.println(isloginTemp);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    /**
     * 执行验证登陆查询
     *
     * @param CName
     * @param Password
     * @return
     */
    public static boolean queryUser(String CName, String Password) {
        String sql = "select password from YTH.Base_User where CName = ‘" + CName + "‘ and IsValid = ‘1‘";
        String passwd;
        Connection conn = JDBCTools.getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        boolean hasuser = false;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            if (rs.next()) {// 如果查到用户的密码,则与输入密码比对,如果相符则返回true,否则返回false
                passwd = rs.getString("password");
                if (Password.equals(passwd)) {
                    hasuser = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            hasuser = false;
        } finally {
            JDBCTools.release(conn, stmt, rs);
        }
        return hasuser;
    }
    /**
     * 通过手机号登录
     */
    public void loginByPhone(){
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        String mobilePhone = request.getParameter("mobilePhone");
        String sql = "select CName from YTH.Base_User where MobilePhone = ‘" + mobilePhone + "‘ and IsValid = ‘1‘";
        //String sql = "select CName from YTH.Base_User where MobilePhone = ‘13501379277‘ and IsValid = ‘1‘";
        String phoneCode = request.getParameter("phoneCode");
        Boolean VerificationCode = VerificationCode(request,phoneCode);
        
        String CName;
        Connection conn = JDBCTools.getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        String openFirstPage = "";
        
        
     // 获取登录时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String logtime = format.format(date);
        Timestamp create = Timestamp.valueOf(logtime); // 将字符的时间转换成时间对象
        
        
        PrintWriter out = null;
        try {
            out = ServletActionContext.getResponse().getWriter();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        HttpSession session = request.getSession();
        int count1 = Integer.parseInt(session.getAttribute("count").toString());
        
        JSONObject cell = new JSONObject();
            if(!VerificationCode){//!VerificationCode
                count1++;
                    request.getSession().setAttribute("count", String.valueOf(count1));
                   cell.put("result", "noThisCode");
                   cell.put("count", String.valueOf(count1));
                out.println(cell);
            }else{
                try {
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery(sql);
                    
                    if (rs.next()) {
                        CName = rs.getString("CName");
                        if(CName == null){
                             count1++;
                             request.getSession().setAttribute("count", String.valueOf(count1));
                             
                             cell.put("result", "noThisPhone");
                             cell.put("count", String.valueOf(count1));
                              out.println(cell);
                        }else{
                                //System.out.println("手机号对应人员为:"+CName);
                                count1++;
                                    request.getSession().removeAttribute("count");//.setAttribute("count", "");
                                    phoneMoniLogin(request,response,CName, create, "noyanzheng");
                                cell.put("result", "success");
                                cell.put("count", String.valueOf(count1));
                                out.println(cell);
                        }
                    }else{
                        count1++;
                            request.getSession().setAttribute("count", String.valueOf(count1));
                        
                           cell.put("result", "noThisPhone");
                         cell.put("count", String.valueOf(count1));
                         out.println(cell);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    out.flush();
                    out.close();
                    JDBCTools.release(conn, stmt, rs);
                }
            }
    }
    
    /**
     * 手机号模拟登录
     */
    public Boolean phoneMoniLogin(HttpServletRequest request,HttpServletResponse response,String username,Timestamp create,String yanzhengma){
        //HttpServletRequest request = ServletActionContext.getRequest();
        //HttpServletResponse response = ServletActionContext.getResponse();
        //HttpSession session = ((HttpServletRequest) request).getSession(true);
        try {
            CCIDCAS.checkLogin(request, response, username, "noupass", "noyanzheng",4);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return true;
    }
    
    /**
     * 判断手机验证码是否正确
     */
    public Boolean VerificationCode(HttpServletRequest request,String phoneCode){
        //System.out.println((((HttpServletRequest) request).getSession().getAttribute("loginRandomNum")));
        HttpSession session = request.getSession();
        //System.out.println(session.getAttribute("loginRandomNum").toString());
        if(session.getAttribute("loginRandomNum")!=null){
            if(session.getAttribute("loginRandomNum").toString().equals(phoneCode)){
                return true;
            }else{
                request.getSession().setAttribute("flag4", "手机验证码输入错误");
                return false;
            }
        }else{
            return false;
        }
        
    }
    
    /**
     * 获取手机验证码
     */
    
    public void getPhoneCode(){
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        String mobilePhone = request.getParameter("mobilePhone");
        int i=SingletonClient.getClient().registEx("565560");
        int randomNum = (int)((Math.random()*9+1)*100000);
        HttpSession session = request.getSession();
        session.setAttribute("loginRandomNum", randomNum);
        //((HttpServletRequest) request).getSession().setAttribute("loginRandomNum", randomNum);
        int a = SingletonClient.getClient().sendSMS(new String[] { mobilePhone },"您的登录验证码为:"+randomNum+",请在一分钟内登录【EIP综合业务管理平台】",3);
        double b=0;
        try {
            b = SingletonClient.getClient().getBalance();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        /*System.out.println("短信发送结果:"+a);
        System.out.println("查询余额返回结果:"+b);*/
        try {
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.println("success");
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 绑定微信
     */
    public void bangDingWeChat(){
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        String name = request.getParameter("name");
        String unionid = (String) ((HttpServletRequest) request).getSession().getAttribute("unionid");
        String headimgurl = (String) ((HttpServletRequest) request).getSession().getAttribute("headimgurl");
        String nickname = (String) ((HttpServletRequest) request).getSession().getAttribute("nickname");
        String sql= "update Base_User set Unionid=‘"+unionid+"‘,HeadImgUrl=‘"+headimgurl+"‘,HeadImgOrder=‘2‘ where CName=‘"+name+"‘";
        Connection conn = JDBCTools.getConnection();
        Statement stmt = null;
        int rs = 0;
        boolean hasuser = false;
        
        // 获取登录时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String logtime = format.format(date);
        Timestamp create = Timestamp.valueOf(logtime); // 将字符的时间转换成时间对象
        try {
            stmt = conn.createStatement();
            rs = stmt.executeUpdate(sql);
            if(moniLogin(request,response,name,"nopass","noyanzheng")){
                //saveLoginLog(name);//添加微信登陆日志
                
                PrintWriter out = ServletActionContext.getResponse().getWriter();
                out.println("success");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            hasuser = false;
        } 
         ((HttpServletRequest) request).getSession().removeAttribute("unionid");
          ((HttpServletRequest) request).getSession().removeAttribute("headimgurl");
          ((HttpServletRequest) request).getSession().removeAttribute("nickname");
    }
  
    
    
    /**
     * 同步头像
     */
    public void SynchronousWeChat(){
        String requestUrl = "http://wechat.ccidgroup.com/_vti_bin/EmployeesService.svc/GetEmployeesByDeptId/1";
        HttpURLConnection con = null;
        String result = null;
        try {
            URL url = new URL(requestUrl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(10000);
            con.setReadTimeout(2000);
            con.setDoOutput(false); // post改为true
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "text/plain");
            con.connect();
            int code = con.getResponseCode();
            if (code == 200) {
                // 读取返回内容
                StringBuffer buffer = new StringBuffer();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        con.getInputStream(), "UTF-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    buffer.append(temp);
                    buffer.append("\n");
                }
                result = buffer.toString().trim();
                JSONArray AllArray = JSONArray.fromObject(result);
                
               
                for(int i=0;i<AllArray.length();i++){
                    JSONObject obj = AllArray.getJSONObject(i);
                    // "update Base_User set HeadImgUrl=‘HeadImgUrl‘,HeadImgOrder=‘2‘ where MobilePhone=‘18618449922‘ and (HeadImgOrder>1 or HeadImgOrder is null or HeadImgOrder=‘‘)
                     String sql= "update Base_User set HeadImgUrl=‘"+obj.get("photoUrl")+"‘,HeadImgOrder=‘3‘ where (HeadImgOrder>2 or HeadImgOrder is null or HeadImgOrder=‘‘)  and MobilePhone=‘"+obj.get("mobile")+"‘";
                     Connection conn = JDBCTools.getConnection();
                     Statement stmt = null;
                     int rs = 0;
                     try {
                         stmt = conn.createStatement();
                         rs = stmt.executeUpdate(sql);
                     } catch (Exception e) {
                         e.printStackTrace();
                     } 
                }
                
                PrintWriter out = ServletActionContext.getResponse().getWriter();
                out.println("success");
                out.flush();
                out.close();
                
            } else {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        con.getErrorStream(), "UTF-8"));
                StringBuffer buffer = new StringBuffer();
                String temp;
                while ((temp = br.readLine()) != null) {
                    buffer.append(temp);
                    buffer.append("\n");
                }
                PrintWriter out = ServletActionContext.getResponse().getWriter();
                out.println("failure");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            
        } finally {
            con.disconnect();
        }
    }
}

 四、效果展示

技术分享

 

 

技术分享

 

微信扫码登录

标签:anim   分享   用户   数字   verify   logs   spi   release   print   

原文地址:http://www.cnblogs.com/Garnett-Boy/p/7047873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!