通过Ajax从Servlet获取数据完成登录实例

Ajax的好处就是可以在页面不进行刷新的情况下,完成当前页面某些收据的更新,速度快且用户体验好。

刚开始学习,就着几行代码也要搞很长时间才能明白。

login.jsp--登录界面

<span style="white-space:pre">	</span><form action="" method="post" οnsubmit="return logincheck();">
	<span style="white-space:pre">	</span><div class="login_row login_row_text">
	<span style="white-space:pre">		</span><label id="login_lab_user" class="login_lab"></label>
	<span style="white-space:pre">		</span><input id="loginname" class="itext" type="text" name="username" tabindex="1" autocomplete="off"
		<span style="white-space:pre">		</span>placeholder="邮箱/用户名/已验证手机">
		<span style="white-space:pre">	</span></div>
	<span style="white-space:pre">	</span><div class="login_row login_row_text">
		<span style="white-space:pre">	</span><label id="login_lab_pwd" class="login_lab"></label>
		<span style="white-space:pre">	</span><input id="signpwd" class="itext" type="password" name="password" tabindex="2" autocomplete="off"
			<span style="white-space:pre">	</span>placeholder="密码">
		</div>
	<span style="white-space:pre">	</span><div class="login_row">
		<span style="white-space:pre">	</span><input id="loginbut" type="submit" name="login_sub" value="登       录" tabindex="4">
	<span style="white-space:pre">	</span></div><div id="meserror"><ul id="meserrorul"></ul></div>
<span style="white-space:pre">	</span></form>
js-bbs.js--js文件登录验证,其中包括正则判断和数据库的验证判断

/*login.jsp 登录验证*/
function logincheck() {
	var uname = document.getElementById("loginname");
	var upwd = document.getElementById("signpwd");
	
	console.log(uname.value," ",upwd.value);
	if(uname.value == "" || uname.value == null)  {
		var cul = document.getElementById("meserrorul");
		cul.innerHTML = "<li>账号不能为空</li>";
		document.getElementById("meserror").style.display = "";
		return false;
	}else if(upwd.value == "" || upwd.value == null) {
		var cul = document.getElementById("meserrorul");
		cul.innerHTML = "<li>密码不能为空</li>";
		document.getElementById("meserror").style.display = "";
		return false;
	}else if(upwd.value == "" || upwd.value == null) {
		var cul = document.getElementById("meserrorul");
		cul.innerHTML = "<li>密码不能为空</li>";
		document.getElementById("meserror").style.display = "";
		return false;
	}else {		//通过AJAX从数据库中验证
		var xhr;
		if (window.ActiveXObject) {
			//测试ActiveX是否存在
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");//低版本IE
			} catch (e) {
				xhr = new ActiveXObiect("Msxml2.XMLHTTP");//高版本IE
			}
			
		} 
		else if (window.XMLHttpRequest) {
			//测试XHR是否已经被定义
			xhr = new XMLHttpRequest();
		}
		else {
			//如果不支持AJAX则抛出错误
			throw new Error("Ajax is not supported by this browser");
		}
		
		//就绪状态处理器
		xhr.onreadystatechange = function() {
			if(this.readyState == 4) {			//忽略除DONE状态之外的所有状态
				if (this.status >= 200 && this.status <300) {
					//成功
					var data = xhr.responseText;
					console.log(data);
					if(data=="fail"){
						console.log("Active data");
						var cul = document.getElementById("meserrorul");
						cul.innerHTML = "<li>账号/密码错误</li>";
						document.getElementById("meserror").style.display = "";
					}else {
						var url = "LoginSuccess";<span style="white-space:pre">	</span>//servlet路径
//						location.href=url;//get发送
						post(url, {userId:data}); 
					}
				}
				else {
					//出错
					location.href="error.jsp";
				}
			}
		};	
		xhr.open("GET", "Login?username=" + uname.value + "&password=" + upwd.value,true);
		xhr.send(null);
		return false;
	}
};
//post虚拟表单
function post(URL, PARAMS) {        
    var temp = document.createElement("form");        
    temp.action = URL;        
    temp.method = "post";        
    temp.style.display = "none";        
    for (var x in PARAMS) {        
        var opt = document.createElement("textarea");        
        opt.name = x;        
        opt.value = PARAMS[x];        
        // alert(opt.name)        
        temp.appendChild(opt);        
    }        
    document.body.appendChild(temp);        
    temp.submit();        
    return temp;        
} 
因为不想get发送所以就从网上学习了一种创建虚拟表单的方式来post想要发送到servlet的内容,当post传到servlet之后,通过“out.print();”回传想要接受的值,这时遇到了一个问题,我想要从在servlet中通过数据库中验证当没有查询到的时候就返回代表错误信息的字符串,查询到了,就直接通过servlet直接跳转到主页,跳转主页使用
request.getRequestDispatcher("home.jsp").forward(request, response);
可是这样的话Ajax就把整个jsp文件的内容都传回js文件中了,无法跳转到主页,不知道什么好的办法,所以自己就想了一种让验证信息返回到js文件中,js文件再把参数传到另一个servlet的方法来进行页面跳转

Login.java--登录验证Servlet,返回验证结果

<span style="white-space:pre">		</span>String username = request.getParameter("username").trim();
		String userpwd = request.getParameter("password").trim();
		PrintWriter out = response.getWriter();
		
		try {
			Connection conn = MySQLDbHelper.getConnection();
			Statement stmt = MySQLDbHelper.creStatement(conn);
			String sql = "SELECT safeuserid FROM SafeUser WHERE safeusername='"+username+"' AND safepassword= '"+userpwd+"'";
			ResultSet rs = MySQLDbHelper.executeQuery(stmt, sql);
			if(rs.next()) {
				String userid = rs.getString("safeuserid");
				
				MySQLDbHelper.close(rs);
				MySQLDbHelper.close(stmt);
				MySQLDbHelper.close(conn);
				out.print(userid);
			} else {
				out.print("fail");
			}
		} catch (Exception e) {
			// TODO: handle exception
			response.sendRedirect("error.jsp");
		}
LoginSuccess.java--跳转servlet,通过验证后的传值和跳转

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		String userId = request.getParameter("userId");
		HttpSession session = request.getSession(true);		
		String sql = "SELECT safeusername FROM SafeUser WHERE safeuserid='"+userId+"'";	
		
		try {
			Connection conn = MySQLDbHelper.getConnection();
			Statement stmt = MySQLDbHelper.creStatement(conn);
			ResultSet rs = MySQLDbHelper.executeQuery(stmt, sql);
			if (rs.next()) {
				String sUserName = rs.getString("safeusername");
				
				session.setAttribute("userName", sUserName);
				session.setAttribute("userId", userId);
				
				rs.close();
				stmt.close();
				conn.close();
				
				request.getRequestDispatcher("home.jsp").forward(request, response);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
到了这里我的登录就完成了







  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值