首页 > 代码库 > android 实现简单登录
android 实现简单登录
一直知道WEB登录之后是通过session保持回话的,现在安卓却不知道怎么弄了。
研究了一下,记录一下。直接上代码:
服务器端:
index.jsp
<%@page import="java.io.PrintWriter"%> <%@page import="com.sun.org.apache.xml.internal.serialize.Printer"%> <%@page import="com.google.gson.JsonObject"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% //测试,只用一个用户名登录,不设密码 String userName = request.getParameter("userName"); PrintWriter pw = response.getWriter(); //只要用户名符合集可登录 if(userName.equals("miquan")) { //返回安卓端的json JsonObject json = new JsonObject(); json.addProperty("success", true); json.addProperty("sessionId", request.getSession().getId()); //保存在服务器端的session request.getSession().setAttribute("userName", "I am a test name."); pw.write(json.toString()); pw.flush(); } else { JsonObject obj = new JsonObject(); obj.addProperty("success", false); pw.write(obj.toString()); pw.flush(); } %>
session.jsp
<%@page import="javax.websocket.Session"%> <%@page import="java.io.PrintWriter"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% PrintWriter pw = response.getWriter(); //获取到同一个session,而不是从新生成一个session,这样就达到我要的效果了 pw.write((String)session.getAttribute("userName")); pw.flush(); %>
安卓端:
//登录 btnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FinalHttp fh = new FinalHttp(); fh.get("http://172.27.35.1:8080/login/index.jsp?userName=miquan", new AjaxCallBack<Object>() { @Override public void onSuccess(Object t) { //获取返回来的json String str = t.toString(); str = str.trim(); try { JSONObject obj = new JSONObject(str); boolean success = obj.getBoolean("success"); //登录成功 if(success) { //app = (MyApplication) this.getApplication(); //MyApplication添加了属性sessionId和isLogin app.setLogin(true); app.setSessionId(obj.getString("sessionId")); Toast.makeText(app, "登录成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(app, "登录失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } super.onSuccess(t); } @Override public void onFailure(Throwable t, int errorNo, String strMsg) { Log.e("miquan", "failure " + strMsg); super.onFailure(t, errorNo, strMsg); } }); } });
//测试 btnSession.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FinalHttp fh = new FinalHttp(); //添加session,连请求一起发送,这里服务器用的是java开发的 fh.addHeader("Cookie", "JSESSIONID=" + app.getSessionId()); fh.get("http://172.27.35.1:8080/login/session.jsp", new AjaxCallBack<Object>() { @Override public void onSuccess(Object t) { Log.e("miquan", t.toString()); super.onSuccess(t); } @Override public void onFailure(Throwable t, int errorNo, String strMsg) { Log.e("miquan", "failure " + strMsg); super.onFailure(t, errorNo, strMsg); } }); } });
马上下班了,不多写。。。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。