大家好,又见面了,我是全栈君。
一直都知道WEB通过登录后session拿着回答,如今,安卓不知道怎么弄的。
研究了一下,它记录。直接在代码:
server结束:
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"%>
<%
//測试,仅仅用一个username登录。不设password
String userName = request.getParameter("userName");
PrintWriter pw = response.getWriter();
//仅仅要username符合集可登录
if(userName.equals("miquan")) {
//返回安卓端的json
JsonObject json = new JsonObject();
json.addProperty("success", true);
json.addProperty("sessionId", request.getSession().getId());
//保存在server端的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。连请求一起发送。这里server用的是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);
}
});
}
});
现在下班,多写。。。
版权声明:本文博客原创文章,转载请注明原文地址。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117271.html原文链接:https://javaforall.cn