从Android访问servlet时维护HTTP会话

当我从Android访问servlet时,我无法维护会话。 我只是将参数和URL一起传递给servlet,servlet从数据库中收集数据并将其存储在会话中,但我无法在后续请求中检索它。

当我在servlet中关闭PrintWriter时,会话是否会过期?

这是客户端的问题。 HTTP会话由cookie维护。 客户端需要确保根据HTTP规范正确地将cookie发送回后续请求。 HttpClient API为此提供了CookieStore类,您需要在HttpContext中设置它,而HttpContext又需要在每次HttpClient#execute()调用时传递。

 HttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // ... HttpResponse response1 = httpClient.execute(yourMethod1, httpContext); // ... HttpResponse response2 = httpClient.execute(yourMethod2, httpContext); // ... 

要了解有关会话如何工作的更多信息,请阅读以下答案: servlet如何工作? 实例化,会话,共享变量和multithreading