Servlet结合jQuery实现异步登录
1.创建登录界面
https://www.cnblogs.com/YorkZhangYang/p/12538576.html
2.完成登录验证(原生js实现)
https://www.cnblogs.com/YorkZhangYang/p/12539033.html
3.创建LoginServlet(为演示登录过程,未连接数据库验证)
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.websocket.Session; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.设置获取表单字符集 request.setCharacterEncoding("utf-8"); //2.设置响应的类型,这里注释掉 //response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("username"); String pwd = request.getParameter("password"); String code = request.getParameter("validateCode"); String str=""; PrintWriter out = response.getWriter(); if(name.equals("")||name==null||pwd.equals("")||pwd==null||code.equals("")||code==null) { out.print("表单不能为空"); return; } String scode = (request.getSession().getAttribute("code").toString()).toLowerCase(); boolean IsName = name.equals("admin"); boolean IsPassword = pwd.equals("123"); boolean IsCode = code.toLowerCase().equals(scode); if(IsName&&IsPassword&&IsCode) { request.getSession().setAttribute("username", name); request.getSession().setAttribute("password", pwd); //向客户端响应一个字符串 str="ok"; response.getWriter().print(str); //response.sendRedirect("adminindex.jsp"); } else { if(!IsCode) { str="code"; response.getWriter().print(str); } else { str="namepwd"; response.getWriter().print(str); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
4.Login.jsp使用jQuery的$.ajax实现异步提交
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录界面</title> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="js/jquery-1.11.1.min.js"></script> <style> .bg{ height: 600px; background-image:url(images/bg.jpg); background-size:cover; } .form{ padding: 40px; margin-top: 175px; background: rgba(255,255,255,0.2); } .footer{ height: 60px; padding-top:20px; font-size: 14px; font-weight: bold; text-align: center; } </style> </head> <body> <div class="page-header"> <h1>XXXX信息系统登录界面</h1> </div> <div class="container-fluid"> <div class="row bg"> <div class="col-md-offset-6 col-md-4 col-sm-offset-3 col-sm-7 col-xs-offset-2 col-xs-8 col-lg-offset-6 col-lg-3 form"> <form class="form-horizontal" action="" method="post"> <div class="form-group"> <label for="username" class="col-sm-4 control-label">用户名</label> <div class="col-sm-8"> <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名"> </div> </div> <div class="form-group"> <label for="password" class="col-sm-4 control-label">密码</label> <div class="col-sm-8"> <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码"> </div> </div> <div class="form-group"> <label for="validateCode" class="col-sm-4 control-label">验证码</label> <div class="col-sm-4"> <input type="text" class="form-control" id="validateCode" name="validateCode" placeholder="验证码"> </div> <div class="col-sm-4"> <img id="verifyCode" src="${pageContext.request.contextPath}/VerifyCodeImg" alt="Loading" width="75px" height="35px" onclick="changeCode()"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox">记住我 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" id="submitBtn" class="btn btn-success" style="width: 50%;">登录</button> </div> </div> </form> <span style="color: red;" id="tip"></span> </div> </div> <div class="footer"> <p>©版权所有:XXXXX学院xx市xx大道XXX号</p> <p>邮编:530001联系邮箱:xxxxxxx@163.com</p> </div> </div> <script type="text/javascript"> //验证码更换 function changeCode() { var codeImg=document.getElementById("verifyCode"); //这里URL后追加随机数,使程序每次访问的都是不同的资源,防止浏览器缓存,即产生不同的验证码 codeImg.src="/LoginTest/VerifyCodeImg?d="+Math.random(); } //表单验证 //获取要验证的表单对象 let username = document.getElementById("username"); let password = document.getElementById("password"); let validatecode = document.getElementById("validateCode"); let span = document.getElementById("tip"); username.onblur=function() { vailidateUserName(); } password.onblur=function() { validatePassword(); } validatecode.onblur=function() { validateCode(); } //验证用户名 function vailidateUserName() { //2-12位,字母开头,不能有_$之外的特殊字符 let reg = /^[a-zA-Z][\w$]{1,11}$/; let value= username.value; if(!value) { span.innerHTML = "用户名不能为空"; return false; } else if(!reg.test(value)) { span.innerHTML = "用户名2-12位,字母开头,不能有_$之外的特殊字符"; return false; } else { span.innerHTML = ""; return true; } } //验证密码 function validatePassword() { let value = password.value; if(!value) { span.innerHTML = "密码不能为空"; return false; } else { span.innerHTML = ""; return true; } } //验证码不能为空 function validateCode() { let value = validatecode.value; if(!value) { span.innerHTML = "验证码不能为空"; return false; } else { span.innerHTML = ""; return true; } } //按钮提交 $("#submitBtn").click(function(){ if(vailidateUserName()&&validatePassword()&&validateCode()) { //document.getElementById("loginForm").submit(); var strName=$("#username").val(); var strPwd=$("#password").val(); var strCode=$("#validateCode").val(); console.log(strPwd); console.log(strCode); $.ajax({ url:"/LoginTest/LoginServlet", dataType:"text", type:"post", data:{username:strName,password:strPwd,validateCode:strCode}, beforeSend:function() { $("#tip").html("正在登录......"); }, success:function(data){ if(data=="ok") { //alert("登录成功!"); $("#tip").html("登录成功!"); window.location.href = "adminindex.jsp"; } if(data=="code") { $("#tip").html("验证码错误!"); } if(data=="namepwd") { $("#tip").html("用户名或密码错误!"); } }, error:function () { console.log("ajax请求数据失败!"); $("#tip").html("ajax请求数据失败!"); } }); } else { span.innerHTML = "表单未正确填写"; return false; } }); </script> <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) --> <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script> <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script> </body> </html>
5.运行结果
输入用户名admin,密码123,正确输入验证码后,点击登录,成功跳转到adminindex.jsp界面。
参考文章:
转载文章链接已标明,如有侵权请告知。文章仅作为知识记忆所用,如有错误,敬请指正。