通过Ajax从Servlet获取数据完成登录实例
2016-10-18 10:02
393 查看
Ajax的好处就是可以在页面不进行刷新的情况下,完成当前页面某些收据的更新,速度快且用户体验好。
刚开始学习,就着几行代码也要搞很长时间才能明白。
login.jsp--登录界面
Login.java--登录验证Servlet,返回验证结果
刚开始学习,就着几行代码也要搞很长时间才能明白。
login.jsp--登录界面
<span style="white-space:pre"> </span><form action="" method="post" onsubmit="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 } }到了这里我的登录就完成了
相关文章推荐
- JavaWeb将数据包装成JSON以及JSP通过ajax对JSON的获取与解析(代码实例)
- ajax获取的数据通过avalon绑定实例
- JavaWeb将数据包装成JSON以及JSP通过ajax对JSON的获取与解析(代码实例)
- YII框架中使用jQuery UI : 自动完成(Autocomplete)--本地数据和使用ajax获取远程数据实例
- 1.简单实例:ASP.NET下Echarts通过Ajax从数据库中获取数据
- JavaWeb将数据包装成JSON以及JSP通过ajax对JSON的获取与解析(代码实例)
- 【Extjs登陆】表单ajax提交,登录实例 后台为servlet
- 通过struts框架完成登录的实例
- JQUERY 实现AJAX跨域获取json数据实例
- ECharts图表组件中级入门篇:如何通过Ajax异步获取图表数据赋值于图表并渲染呈现
- AjaxPro.NET完成TextBox智能获取服务端数据功能(Asp.net 2.0)(示例代码下载)
- Ajax 通过XMLHttpRequest 对象完成首页的登录功能
- jquery通过ajax获取数据,控制显示的数据条数
- WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据
- spring mvc DispatcherServlet详解之三---request通过ModelAndView中获取View实例的过程
- jquery通过ajax获取数据(优化、封装)
- AJAX通过post提交数据,并获取XML格式返回结果
- PHP中使用CURL模拟登录并获取数据实例
- PHP中使用CURL模拟登录并获取数据实例
- echarts通过ajax向服务器发送post请求,servlet从数据库读取数据并返回前端