1. 程式人生 > >用JAVA和Jquery實現掃碼登入的原理和程式碼

用JAVA和Jquery實現掃碼登入的原理和程式碼

貼上前端程式碼,供參考

<script type="text/javascript" src="js/jquery-3.3.1.js"></script>

<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">


	var flag = false;
	//登入
	function login() {
		if ($('#user_name').val().length < 1) {
			alert('請輸入使用者名稱');
			return;
		} else if ($('#user_pwd').val().length < 1) {
			alert('請輸入密碼');
			return;
		}
var ss=GetQueryString('s');
		$.ajax({
			type : "post",
			url : "useraction.action?methodName=loginup",
			dataType : "json",
			data : {
				user_name : $('#user_name').val(),
				user_pwd : $('#user_pwd').val(),
				s:ss,
				d : new Date()
			},
			success : function(data) {
				//返回處理的方法
				if (data!=0) {
					if (GetQueryString('m') == 'go') {
						location.href = "findBook.jsp?go=to";
						return;
					}
					if(data==2){
						location.href = "index.jsp";
					}else if(data==1){
						location.href = "addBook.jsp";
					}
					
				} else {
					alert('登入失敗');
					location.href="login.jsp"
				}
			}
		});
	}
	setInterval("iflogin();", "1500");//定時器
	//判斷是否登入
	function iflogin() {
		$.ajax({
			type : "post",
			url : "useraction.action?methodName=loginfalg",
			dataType : "json",
			data : {
				 <%String x = UUID.randomUUID().toString();%>
				   random:'<%=x%>',
				d : new Date()
			},
			success : function(data) {
				//返回處理的方法
				if (data!=0) {
					if (GetQueryString('m') == 'go') {
						location.href = "findBook.jsp?go=to";
						return;
					}
					if(data==2){
						location.href = "index.jsp";
					}else if(data==1){
						location.href = "addBook.jsp";
					}
				}
			}
		});
	}

	//獲取位址列的值
	function GetQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null)
			return unescape(r[2]);
		return null;
	}
	var ll = true;
	//顯示
	function er() {
		if (ll) {
			$('#tables').show();
			$('#tab1').hide();
			ll = false;
		} else {
			$('#tables').hide();
			$('#tab1').show();
			ll = true;
		}
	}
	//生成二維碼的方法
	

</script>
</head>

<body>
	<!--top-->

	<jsp:include page="commonality.jsp"></jsp:include>
	<div class="logoin_wrap mt30">
		<h2>使用者登陸</h2>
		<div id="table">
			<form id='tab1'>
				<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tr>
						<td height="30px"></td>
					</tr>
				</table>
				<table width="100%" height="35" border="0" cellpadding="0"
					cellspacing="0">
					<tr>
						<td width="44%" align="right" valign="middle" class="f14">使用者名稱:</td>
						<td width="56%" align="left" valign="middle"><input
							type="text" name="user_name" value="" id="user_name"
							class="input w180"></td>
					</tr>
				</table>
				<table width="100%" height="35" border="0" cellpadding="0"
					cellspacing="0">
					<tr>
						<td width="44%" align="right" valign="middle" class="f14">密&nbsp;&nbsp;碼:</td>
						<td width="56%" align="left" valign="middle"><input
							type="password" name="user_pwd" value="" id="user_pwd"
							class="input w180"></td>
					</tr>
				</table>

				<table width="100%" height="35" border="0" cellpadding="0"
					cellspacing="0">
					<tr>
						<td width="44%" align="right" valign="middle" class="f14"></td>
						<td width="56%" align="left" valign="middle">
							<!-- 圖片按鈕,與type=submit按鈕的效果是一樣,也可以用來提交表單 --> <img
							src="images/admin_dl.png" onclick="login();" /> <!-- 							onclick="login();" -->
							<a id='er' onclick="er()">二維碼登入</a>
						</td>
					</tr>
				</table>
				<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tr>
						<td>&nbsp;</td>
					</tr>
				</table>
			</form>
			<div id='tables' align="center">
				<br>
				<div>
					<a href="#" onclick="er()">帳號密碼登入</a>
				</div>
			</div>
		</div>
	</div>
	<!--end content-->

	<!--footer-->

	<div id="footer_wrap">
		<p>Copyright ©2014 飛凡教育,版權所有</p>
	</div>

	<!--end footer-->
	<script type="text/javascript" src="js/jquery.qrcode.min.js"></script>

	<script type="text/javascript">
	$(function() {
		$('#tables').hide();
		$("#tables").qrcode({
		    render: "canvas", //也可以替換為table
		    width: 250,
		    height: 250,
		    //掃碼動作
	 	    text:"http://192.168.43.147:8080/BookProject/useraction.action?methodName=sm&user_name=admins&random=<%=x%>"
	<%-- 	    text: "http://192.168.43.217:8080<%=request.getRequestURI()%>" --%>
		});
	});
	</script>

然後貼上後端程式碼

public class UserAction extends ActionSupport implements ModelDriven<User> {
	private User u = new User();
	private UserDao ud = new UserDaoImpl();

	/**
	 * 
	 * @Title: add
	 * @Description: 註冊
	 * @param request
	 * @param response
	 * @return
	 * @return String
	 */
	public ActionForward add(HttpServletRequest request, HttpServletResponse response) {

		try {
			int index = ud.AddUser(u);
			String str = JSON.toJSONString(index);
			super.print(str, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: loginup
	 * @Description: (判斷是手機還是電腦登入)
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public void loginup(HttpServletRequest request, HttpServletResponse response) {
		if (request.getParameter("s") == null || request.getParameter("s").equals("")) {
			login(request, response);
		} else {
			Phonelogin(request, response);
		}
	}

	/**
	 * @Title: Phonelogin
	 * @Description: (手機登入)
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public ActionForward Phonelogin(HttpServletRequest request, HttpServletResponse response) {
		try {
			User login = null;
			// String user_pwd = request.getParameter("user_pwd");
			login = ud.Login(u);
			if (login != null) {// 登入成功
				System.out.println("手機登陸");
				request.getSession().setAttribute("user", login);// 也存在手機會話中
				if (login.getUser_type() == 2) {
					// 是使用者
					String str = JSON.toJSONString(2);
					super.print(str, response);
					return null;
				} else {// 管理員
					String str = JSON.toJSONString(1);
					super.print(str, response);
					return null;
				}
			} else {// 登入失敗
				String str = JSON.toJSONString(0);
				super.print(str, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: sm
	 * @Description: (判斷有沒有掃碼動作)
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public ActionForward sm(HttpServletRequest request, HttpServletResponse response) {
		String random = request.getParameter("random");// 隨機字元用來區分使用者
		Object attribute = request.getSession().getAttribute("user");// 使用者手機的物件
		if (u.getUser_name() != null) {
			System.out.println("掃碼");
			if (attribute != null) {// 如果在手機上登入
				String str = "登入成功";
				User u = (User) attribute;// 將手機的登入的使用者放入ServletContext
				request.getServletContext().setAttribute(random, u);
				try {
					response.getWriter().print("<script>alert('登入成功')</script>");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {// 如果在手機上沒有登入
				try {
					response.getWriter().print("<script>alert('您還未登入'); location.href='login.jsp?s=m'</script>");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 
	 * @Title: login
	 * @Description: 電腦登陸
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public ActionForward login(HttpServletRequest request, HttpServletResponse response) {
		try {
			System.out.println("電腦登入");
			int flag = 0;
			User user = ud.Login(u);
			if (user != null) {
				request.getSession().setAttribute("user", user);
				if (user.getUser_type() == 2) {// 如果是使用者
					flag = 2;
					String str = JSON.toJSONString(flag);
					super.print(str, response);
					return null;
				} else {
					flag = 1;// 管理員
					String str = JSON.toJSONString(flag);
					super.print(str, response);
					return null;
				}
			} else {
				flag = 0;
			}
			// request.getSession().getServletContext().setAttribute("user", user);
			String str = JSON.toJSONString(flag);
			super.print(str, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: Judge
	 * @Description: 判斷是否重複
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public ActionForward judge(HttpServletRequest request, HttpServletResponse response) {
		int index = 0;
		try {
			index = ud.Judge(u);
			String str = JSON.toJSONString(index);
			super.print(str, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: loginfalg
	 * @Description: (login不停的請求)
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public ActionForward loginfalg(HttpServletRequest request, HttpServletResponse response) {
		// 手機端物件
		String random = request.getParameter("random");
		User attribute = null;
		if (random != null) {
			attribute = (User) request.getServletContext().getAttribute(random);// 掃碼動作物件
		}
		int index = 0;// 用index作為條件讓使用者判斷
		if (attribute != null) {// 有掃碼動作 和手機端登入時
			System.out.println("成功");
			/**
			 * 將手機端物件儲存到session
			 */
			request.getSession().setAttribute("user", attribute);
			index = attribute.getUser_type();// 是不是管理員
			/**
			 * 將掃碼動作儲存下來的物件清空
			 */
			request.getServletContext().setAttribute(random, null);
		}
		String str = JSON.toJSONString(index);
		try {
			super.print(str, response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: exit
	 * @Description: (使用者退出系統)
	 * @param request
	 * @param response
	 * @return
	 * @return ActionForward
	 */
	public ActionForward exit(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().setAttribute("user", null);// 退出使用的
		// request.getServletContext().setAttribute("userfalg", null);//
		return new ActionForward(false, "login.jsp");
	}

實現登入的原理是首先在手機和電腦在同一區域網下,如果然後用手機瀏覽器訪問登入頁面,在手機端訪問登入頁面的時候後面帶個?s=xxx,或者&s=xxx,在手機端登入之後,使用瀏覽器的掃碼功能掃描顯示的二維碼即可,詳情請看程式碼,如有不懂的地方請留言