Itrip项目(3)实现用户登陆验证功能

141 阅读6分钟

(1)更新register.htmlregister.js
register.html

<div class="i-reg-bottom cur">
			    <form class="fromOne" action="http://localhost:9001/save_Users.do" method="post">
					<div class="i_mobile">
						手机号  <input name="usercode" id="telusercode" type="text" placeholder="请输入手机号码" /><span></span>
						<!-- 用于手机注册判断的操作码 -->
						<input name="code" id="code" type="hidden" value="1">
					</div>
				    <div class="i_mobile">
					    昵&nbsp;&nbsp;&nbsp;&nbsp;称   <input name="username" id="uname" type="text" placeholder="请输入昵称" /><span></span>
					    <!-- 用于手机注册判断的操作码 -->
					    <input name="code" id="telcode" type="hidden" value="1">
				    </div>
					<div class="i_pwd">
						登陆密码  <input name="userpassword"  id="passwd" type="password" placeholder="请输入密码" /><span></span>
					</div>
					<div class="i_check">
						验证码  <input type="text" placeholder="请输入验证码" /><span></span>
						<div class="i_check_in"></div><i class="idCode">换一张</i>
					</div>
					<div class="i_lives">
						激活码  <input name="activecode" id="activetelcode" type="text" placeholder="请输入激活码" /><a href="#" id="btactivecode">获取激活码</a>
					</div>

					<div class="i-reg-check">
						<input id="i-reg-info" checked="checked" type="checkbox">
						<label for="i-reg-info">
						我已经阅读并同意遵守
						<a class="agreement" href="javascript:;">《i旅行用户服务协议》</a>
						</label>
					</div>
					<div class="i-reg-sub">

						<input type="hidden" name="screationdate" id="screationdate"/>
						<input class="submitOne" type="button" id="bttelok" value="同意协议并注册">
					</div>
    			</form>
    		</div>

register.js

/提交按钮,所有验证通过方可提交
 // 手机注册
$('.submitOne').click(function(){

  if(ok1 && ok2){
    var date=new Date();
    var usercode=$("#telusercode").val();
	var code=$("#code").val();
	var username=$("#uname").val();
	var userpassword=$("#passwd").val();
	var activecode=$("#activetelcode").val();
	var usercode=$("#telusercode").val();
    var screationdate=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();

    var jsondata={
    	"usercode":usercode,
	    "code":code,
	    "username":username,
	    "userpassword":userpassword,
	    "activecode":activecode,
	    "screationdate":screationdate

};

 $.post('http://localhost:9001/save_Users.do',jsondata,function(msg){
    	alert(msg);
		if(msg=='注册成功'){
			window.location="login.html"; //注册成功后自动跳转到登陆界面
		}
});

(2)实现用户登陆验证,更新实现类ItripUserImpAction中的check方法

@Override
	@CrossOrigin(allowCredentials = "true", maxAge = 3600)
	@RequestMapping(value = "check_Users.do")
	public String check(HttpServletRequest request, HttpServletResponse response, ItripUser user) {
		ItripUser nus = itripUsersBiz.check(user);
		if (nus != null) {//判断数据库是否存在该数据
			//将us对象转为json字符串保存到redis中
			String usjson = JSONObject.toJSONString(nus);
			System.out.println(usjson);
			//写入到redis中存储
			RedisUtil.addRedis(nus.getId() + "", usjson);
			Cookie ck = new Cookie("id", nus.getId().toString());
			response.addCookie(ck);//向客户端的cookie中存放数据
			request.getSession().setAttribute("id", nus.getId());
			return "" + 1;
		}

		return "" + 0;
	}

(3)更新login.htmllogin.js文件
login.html

<!-- 手机动态登录 -->
                        <div id="actionPass" class="form-group  margin-left-100 " style="display: none;">
                            <div class="controls col-sm-9">
                                <input type="button" id="btcheckcode" class="btn btn-warning form-control" value="获取验证码"></input>
                            </div>
                        </div>

login.js

//手机登录
$("#tellogin").click(function(){
    //获取手机号码
    var tel=$("#username").val();
    //获取验证码
    var passwd=$("#password").val();
    var jsdata={
            "usercode":tel,
            "activecode":passwd
    };
    $.post('http://localhost:9001/checktel_Users.do',jsdata,function(msg){
        if(msg=='1'){
            window.location="index.html";
        }else{
            alert('登陆失败!');
        }
    });
});

(4)在主页呈现登陆者信息:
index.html

<!-- 未登录显示 -->
			<div class="i-nav-login" id="unlogin">
				<a href="login.html">登陆</a>
				<span>|</span>
				<a href="register.html">注册</a>
			</div>
			
<!-- 用于登录者呈现登陆者的用户姓名 -->
			<div class="i-nav-login" id="username">
				<font color="#f0ffff">登陆:</font><span id="uname">xxx</span>|<font color="#f0ffff"><a id="btlogout" href="#">注销</a></font>
			</div>

在工具类RedisUtil中添加获取redis中存放的用户对象的方法getId( )
RedisUtil.java

    /**
	 * 获取redis中存放的用户对象
	 * */
	public static String getId(String id){
		Jedis jedis=new Jedis("localhost",6379); //替换为实际连接地址与端口
		String usstr=jedis.get(id);
		return usstr;
	}

在实现类ItripUserImpAction中添加用于在首页显示登陆者信息的方法

//用于在首页显示登陆者信息的方法
	@CrossOrigin()
	@RequestMapping(value = "showIndexUser_Users.do")
	public String showIndexUser(HttpServletRequest request, HttpServletResponse response, Long id) {
		//从redis中获取登陆者的信息
		if (id != null) {
			String userstr = RedisUtil.getId(id.toString());
			if(userstr!=null){
				return userstr;
			}
		}
		return null;
	}

index.js

/*****登陆者信息**************/
$("#unlogin").show();
$("#username").hide();

$.getJSON('http://localhost:9001/showIndexUser_Users.do?id=42',function (us) {
	//alert(us);
	if(us!=''){
		$("#uname").html('<font color="#f0ffff">'+us.username+'</font>');
		$("#unlogin").hide();
		$("#username").show();
	}
});

(5)在主页显示注销功能:
在工具类RedisUtil中添加删除redis中存放的用户对象delId( )
RedisUtil.java

    /**
	 * 删除redis中存放的用户对象
	 * */
	public static String delId(String id){
		Jedis jedis=new Jedis("localhost",6379); //替换为实际连接地址与端口
		Long delid=jedis.del(id);
		if(delid!=null){
			return "ok";
		}
		return "fail";
	}

在实现类ItripUserImpAction中添加用于在首页显示注销登陆的方法

    /***
	 * 注销登录
	 * */
	@RequestMapping(value = "logout_Users.do")
	public String logout(HttpServletRequest request, HttpServletResponse response, Long id){
		String rst=RedisUtil.delId(id.toString()); //删除redis中寄存的用户信息,而不是数据库中用户信息!否则又要重新注册
		if(rst!=null&&rst.equals("ok")){
			return "注销成功";
		}
		return "注销失败";
	}

在index.html页面给出注销事件的id信息等等
index.html

<!-- 用于登录者呈现登陆者的用户姓名 -->
			<div class="i-nav-login" id="username">
				<font color="#f0ffff">登陆:</font><span id="uname">xxx</span>|<font color="#f0ffff"><a id="btlogout" href="#">注销</a></font>
			</div>

然后在index.js文件里编写注销登陆的JavaScript事件
index.js

//注销用户登录
$("#btlogout").click(function(){
	$.get('http://localhost:9001/logout_Users.do?id=42',function(rst){
		alert(rst);
		if(rst=='注销成功'){
			$("#unlogin").show();
			$("#username").hide();
		}
	});
});

(6)完善手机动态登陆模块的功能:
login.html

<!-- 手机动态登录 -->
                        <div id="actionPass" class="form-group  margin-left-100 " style="display: none;">
                            <div class="controls col-sm-9">
                                <input type="button" id="btcheckcode" class="btn btn-warning form-control" value="获取验证码"></input>
                            </div>
                        </div>
                        
        <button class="btn btn-danger " id="login">登陆</button>
        <button class="btn btn-danger " id="tellogin">手机登陆</button> //手机动态登录的按钮

在实现类ItripUserImpAction中添加用于手机动态登陆验证的方法

@CrossOrigin(allowCredentials = "true", maxAge = 3600)
	@RequestMapping(value = "checktel_Users.do")
	public String checktel(HttpServletRequest request, HttpServletResponse response, ItripUser user) {
		System.out.println("checktel_Users.do--->");
		//判断从客户端传递的手机验证码和系统生成的手机验证码是否相同
		if(smsck!=null&&smsck.equals(user.getActivecode())){
			ItripUser nus = itripUsersBiz.checkTel(user.getUsercode());
			if (nus != null) {//判断数据库是否存在该数据
				//将us对象转为json字符串保存到redis中
				String usjson = JSONObject.toJSONString(nus);
				System.out.println(usjson);
				//写入到redis中存储
				RedisUtil.addRedis(nus.getId() + "", usjson);
				Cookie ck = new Cookie("id", nus.getId().toString());
				response.addCookie(ck);//向客户端的cookie中存放数据
				request.getSession().setAttribute("id", nus.getId());
				return "" + 1;
			}
		}
		return "" + 0;
	}

在ItripUserMapper中添加

//根据手机号码查询
    public ItripUser checkTel(String tel);

在ItripUserMapper.xml中添加

 <select id="checkTel" parameterType="java.lang.String" resultMap="BaseResultMap">
        select * from itrip_user  where userCode=#{tel}
  </select>

在业务类ItripUsersBiz中添加

//根据手机号码查询
	public ItripUser checkTel(String tel);

在实现类ItripUsersBizImp中添加

@Override
	public ItripUser checkTel(String tel) {
		if(tel!=null&&!tel.trim().equals("")){
			return itripUserMapper.checkTel(tel);
		}
		return null;
	}

在login.js文件里编写手机动态登录JavaScript事件

$("#tellogin").hide();
$("#login").show();

$("#selectShowType input[type=radio]").on("change",function (e) {
    if(this.value==1){
        $("#password").attr("placeholder","请输入密码");
        $("#actionPass").hide();
        $("#staticPass").show();

        $("#tellogin").hide();
        $("#login").show();
    }else{
        $("#password").attr("placeholder","请输入手机验证码");
        $("#actionPass").show();
        $("#staticPass").hide();

        $("#tellogin").show();
        $("#login").hide();
    }
});

//手机验证码动态登录checktel_Users.do
$("#btcheckcode").click(function(){
    //获取手机号码
    var tel=$("#username").val();
    alert(tel);
    //获取手机验证码
    $.get('http://localhost:9001/sendSms_Users.do?tel='+tel,function(msg){
        alert(msg);
    });
});

//手机登录
$("#tellogin").click(function(){
    //获取手机号码
    var tel=$("#username").val();
    //获取验证码
    var passwd=$("#password").val();
    var jsdata={
            "usercode":tel,
            "activecode":passwd
    };

    $.post('http://localhost:9001/checktel_Users.do',jsdata,function(msg){
        if(msg=='1'){
            window.location="index.html";
        }else{
            alert('登陆失败!');
        }

    });

});

实现功能的步骤:
• 在实现类ItripUserImpAction中编写方法以及给出请求路径@RequestMapping(value = "@#¥"),同时给出Mapper文件以及biz业务类的更新
• 在相关html文件里给出事件id等信息
• 在相关js文件里编写JavaScript事件

(7)跨域的cookie设置和访问
login.js

if(flage){
        showMessage.hide();

        //window.location="./index.html"
        var jsondata={"usercode":name,"userpassword":pd};
        /******************************
        * $.post('http://localhost:9001/check_Users.do',jsondata,function(rst){
        *    if(rst=='1'){
        *        window.location="index.html";
        *    }else{
        *        alert('登陆失败!');
        *    }
        * });
        *********************************/
        $.ajax({
            url:'http://localhost:9001/check_Users.do',
            type:"post",
            dataType:"json",
            data:jsondata,
            xhrFields:{withCredentials: true},//允许服务器携带cookie到客户端
            success:function(rst){
                if(rst=='1'){
                    window.location="index.html";
                }else{
                    alert('登陆失败!');
                }
            }
        });

index.js

//读取本地cookie
//读取
function readCookie(name){

	var searchName=name+"=";
	var cookies=document.cookie.split(';');
	for(var i=0;i<cookies.length;i++){
		var c=cookies[i];
		while(c.charAt(0)==' '){
			c=c.substring(1,c.length);
		}
		if(c.indexOf(searchName)==0){
			return c.substring(searchName.length,c.length)
		}
	}
	return null;
}
$(function(){
	var id=readCookie("id");
	//alert(id);
	$.getJSON('http://localhost:9001/showIndexUser_Users.do?id='+id,function (us) {
		//alert(us);
		if(us!=''){
			$("#uname").html('<font color="#f0ffff">'+us.username+'</font>');
			$("#unlogin").hide();
			$("#username").show();
		}
	});