如何在Java servlets中跟踪android请求的会话



我的服务器代码是:

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

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
Integer accessCount=(Integer)session.getAttribute("sessionCount");

if(accessCount==null){
accessCount=new Integer(1);
System.out.println("Welcome for first time....");


}else{
System.out.println("Welcome for "+ accessCount+" time to our website....");
System.out.println("The request id"+session.getId());
accessCount=new Integer(accessCount.intValue()+1);
}
session.setAttribute("sessionCount", accessCount);

}

当我从浏览器访问服务器时,它会正确跟踪会话。输出为:

欢迎第一次...
欢迎2次访问我们的网站。
请求 ID:00A24FAF40E130E09F38D52311EF8F1D
欢迎3次访问我们的网站。
请求 ID:00A24FAF40E130E09F38D52311EF8F1D
欢迎4次访问我们的网站。
请求 ID:00A24FAF40E130E09F38D52311EF8F1D
欢迎5次访问我们的网站。
请求 ID:00A24FAF40E130E09F38D52311EF8F1D

但是当我使用Android模拟器从Android Studio点击它时,输出是:

欢迎第一次...

欢迎第一次...

欢迎第一次...

欢迎第一次...

我点击servlet的代码是

private String getServerResponse(String json){
HttpPost post= new HttpPost("http://10.0.2.2:23130/FirstServlet/welcome");
try {
StringEntity entity=new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client=new DefaultHttpClient();
BasicResponseHandler handler=new BasicResponseHandler();
try {
String response=client.execute(post,handler);
return response;
} catch (IOException e) {
Log.d("JWP", e.toString());
}
} catch (UnsupportedEncodingException e) {
Log.d("JWP", e.toString());
}

return "Unable to contact server......";
}

我提供注册数据,并在Android端连续按注册按钮,因此它会打印输出,如我在服务器端提到的。

所以我的问题是,如何在 Java servlet 中使用HttpSession跟踪 Android 请求的会话?

看起来问题是您没有在安卓端处理cookie,因此JSESSIONID没有被存储/发送回服务器。

我已经有好几年没有使用像HttpPost这样的低级HTTP代码了,但是如果我没记错的话,您可以使用CookieHandler.setDefault(new CookieManager());设置cookie处理

市面上有一些非常好的高级HTTP和REST库 - 你应该帮自己一个忙,至少学习其中一个。如果你正在做JSON REST(看起来你就是这样),我会推荐优秀的Retrofit库。

当然,你必须弄清楚如何让Retrofit使用cookie,这涉及OkHttp拦截器 - 这应该会有所帮助。

最新更新