Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android二維碼掃描登陸網頁

Android二維碼掃描登陸網頁

編輯:關於Android編程

1二維碼掃描登陸

1,web端生成二維碼,傳遞uuid,並存入數據庫

2,web端輪訓查詢信息,是否有數據庫掃描二維碼信息

3,手機端掃描二維碼,獲取UUID,傳遞用戶名、密碼web端

4,web查詢數據庫中用戶信息(UserLogin),將登陸信息(用戶名,密碼)存入數據庫。

5,web輪訓查到用戶登陸信息,信息完整,則登陸成功。

1.1web端

1.1.1 導入依賴包(二維碼生成QRCode.jar)

jar包下載:QRCode.jar

\

 

1.1.2 用戶登陸信息實體類(UserLogin.java)

@Entity
@Table(name = "UserLogin")
public class UserLogin {
	@Id
	@GeneratedValue(generator = "UserLoginIdGenerator")
	@GenericGenerator(name = "UserLoginIdGenerator", strategy = "uuid")
	private String id;
	@Column
	private String name;
	@Column
	private String password;
	@Column
	private int uuid;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getUuid() {
		return uuid;
	}

	public void setUuid(int uuid) {
		this.uuid = uuid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 

1.1.3 生成二維碼(GetQrCodeServlet.java)

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.transaction.jta.platform.internal.JOnASJtaPlatform;

import sun.org.mozilla.javascript.internal.json.JsonParser;

import com.alibaba.fastjson.JSONObject;
import com.jie.qrcode.util.HibernateUtil;
import com.jie.qrcode.util.QRCodeUtil;
import com.jie.qrcode.vo.UserLogin;

/**
 * @ClassName: GetQrCodeServlet.java
 * @Description: TODO(生成二維碼)
 * @author yangjie
 * @version V1.0
 * @Date 2016-5-16 上午11:05:27
 */
public class GetQrCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		// 生成唯一ID
		int uuid = (int) (Math.random() * 100000);
		// 二維碼內容
		// String content =
		// "http://192.168.0.199:8080/QrCodeLogin/PhoneLoginServlet?uuid="
		// + uuid;
		JSONObject obj = new JSONObject();
		obj.put("url",
				"http://192.168.0.199:8080/QrCodeLogin/PhoneLoginServlet");
		obj.put("uuid", uuid);
		String content = obj.toString();
		System.out.println("obj:" + content);
		// 生成二維碼
		String imgName = uuid + "_" + (int) (new Date().getTime() / 1000)
				+ ".png";
		String contextRoot = request.getContextPath();
		String webpath = request.getSession().getServletContext()
				.getRealPath("/");
		System.out.println(webpath);
		String imgPath = webpath + "/img/qrCodeImg/" + imgName;
		String logoPath = webpath + "/img/logo.png";
		QRCodeUtil handler = new QRCodeUtil();
		// handler.encoderQRCode(content, imgPath, "png");
		handler.encoderQRCode(content, imgPath, logoPath, "png");

		// uuid保存
		SessionFactory sf = HibernateUtil.getSessionFacotry();
		Session session = sf.openSession();
		session.beginTransaction();// 事務開始
		UserLogin userlogin = new UserLogin();
		userlogin.setUuid(uuid);
		session.save(userlogin);// 將uuid保存到數據庫
		session.getTransaction().commit();// 事務提交
		session.close();
		sf = null;

		// 生成的圖片訪問地址
		String qrCodeImg = "http://192.168.0.199:8080/QrCodeLogin/img/qrCodeImg/"
				+ imgName;
		String jsonStr = "{\"uuid\":" + uuid + ",\"qrCodeImg\":\"" + qrCodeImg
				+ "\"}";
		out.print(jsonStr);
		out.flush();
		out.close();
	}
}
 

1.1.4 用長連接,檢查登錄狀態(LongConnectionCheckServlet.java)

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.jie.qrcode.util.HibernateUtil;
import com.jie.qrcode.vo.UserLogin;

/**
 * @ClassName:     LongConnectionCheckServlet.java
 * @Description:   TODO(用長連接,檢查登錄狀態) 
 * @author         yangjie
 * @version        V1.0  
 * @Date           2016-5-16 上午11:09:32
 */
public class LongConnectionCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int uuid = Integer.parseInt(request.getParameter("uuid"));
		String jsonStr = "";
		System.out.println("in");
		System.out.println("uuid:" + uuid);
		long inTime = new Date().getTime();
		Boolean bool = true;
		while (bool) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 根據uuid查詢數據庫登錄表信息
			String username = "";
			SessionFactory sf = HibernateUtil.getSessionFacotry();
			Session session = sf.openSession();
			Criteria criteria = session.createCriteria(UserLogin.class);
			criteria.add(Restrictions.eq("uuid", uuid));
			List result = criteria.list();
			if (result.size() > 0) {
				for (UserLogin s : result) {
					username = s.getName();
					if(!"".equals(username)&&username!=null){//如果用戶名信息不為空,則登陸成功
						bool = false;
						session.clear();
						session.beginTransaction();
						session.delete(s);//刪除二維碼登錄信息,表明已登錄
						session.getTransaction().commit();
					}
					jsonStr = "{\"uname\":\"" + username + "\"}";
					System.out.println(username);
				}
			} else {
				if (new Date().getTime() - inTime > 5000) {
					bool = false;
				}
			}
			session.close();
			sf = null;

		}
		System.out.println("login ok : " + jsonStr);
		PrintWriter out = response.getWriter();
		out.print(jsonStr);
		out.flush();
		out.close();
	}
}

 

1.1.5 接收手機二維碼回傳信息(PhoneLoginServlet.java)

 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.jie.qrcode.util.HibernateUtil;
import com.jie.qrcode.vo.UserLogin;


/**
 * @ClassName:     PhoneLoginServlet.java
 * @Description:   TODO(手機二維碼登陸) 
 * @author         yangjie
 * @version        V1.0  
 * @Date           2016-5-16 上午11:20:16
 */
public class PhoneLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public PhoneLoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int uuid = Integer.parseInt(request.getParameter("uuid"));
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		System.out.println(uuid);
		System.out.println(uname);
		System.out.println(upwd);
		// 驗證登陸
		boolean bool = true;
		//是否登陸
		boolean islogin = false;
		if (bool) {
			// 將登陸信息存入數據庫
			SessionFactory sf = HibernateUtil.getSessionFacotry();
			Session session = sf.openSession();
			Criteria criteria = session.createCriteria(UserLogin.class);
			criteria.add(Restrictions.eq("uuid", uuid));
			List result = criteria.list();
			if (result.size() > 0) {
				for (UserLogin s : result) {
					s.setName(uname);
					s.setPassword(upwd);
					session.clear();
					session.beginTransaction();//開始事務
					session.saveOrUpdate(s);
					session.getTransaction().commit();// 事務提交
					bool = false;
					islogin = true;
				}
			}else{//沒有該uuid信息,表明已登錄,二維碼過期
				islogin = false;
				System.out.println("二維碼已過期,請刷新頁面");
			}
			session.close();
			sf = null;
		}
		PrintWriter out = response.getWriter();
		out.print(islogin);//傳遞登陸是否成功
		out.flush();
		out.close();
	}
}

 


1.1.6 二維碼掃描界面(index.html)





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

 掃描二維碼登陸


1.1.7 運行效果

\
\

 

1.2手機端

1.2.1 導入依賴工程BarCodeLibrary

工程下載:Android二維碼掃描 \

 

1.2.2 創建工程並引入依賴包

\

 

1.2.3 手機二維碼界面(activity_main.xml)

 

1.2.4 MainActivity.java

package com.jie.qrcode;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zxing.activity.CaptureActivity;

public class MainActivity extends Activity implements OnClickListener{
	private Button btnScan;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnScan = (Button) findViewById(R.id.btn_scan);
		btnScan.setOnClickListener(this);
		
	}

	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, CaptureActivity.class);
		startActivityForResult(intent, 0);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==Activity.RESULT_OK){
			String result = data.getExtras().getString("result");//獲取掃描的結果
			//Log.i("result",result);
			JSONObject obj = JSONObject.parseObject(result);
			String uuid = obj.getString("uuid");
			String httpUrl = obj.getString("url");
			//Toast.makeText(getApplicationContext(), result, 1000).show();
			//將掃描內容提交到網頁
			HttpUtils http = new HttpUtils();
			RequestParams params = new RequestParams();
			params.addBodyParameter("uuid", uuid);
			//Log.i("uuid",uuid);
			params.addBodyParameter("uname", "yangjie");
			params.addBodyParameter("upwd", "123456");
			http.send(HttpMethod.POST, httpUrl, params , new RequestCallBack() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					// TODO Auto-generated method stub
					Log.i("http.send","failuer");
					Toast.makeText(getApplicationContext(), "登陸失敗,二維碼過期,請刷新頁面!", 1000).show();
				}

				@Override
				public void onSuccess(ResponseInfo arg0) {
					// TODO Auto-generated method stub
					Log.i("http.send","success");
					Toast.makeText(getApplicationContext(), "登陸成功!", 1000).show();
				}
			});
		}
	}
}

 

1.2.5 運行效果

\\ \\

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved