Jquery JAVA 用JAVA和Jquery实现扫码登录的原理和代码

首先下载生成二维码的Jquery插件:https://pan.baidu.com/s/1eZESxNxgFDxsuc8ik8Ahjg

贴上前端代码,供参考

<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,在手机端登录之后,使用浏览器的扫码功能扫描显示的二维码即可,详情请看代码,如有不懂的地方请留言

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值