【发布时间】:2011-09-03 19:53:53
【问题描述】:
当我从 Android 访问 servlet 时,我无法保持会话。我只是将参数与 URL 一起传递给从数据库收集数据并将其存储在会话中的 servlet,但我无法在后续请求中检索它。
当我在 servlet 中关闭 PrintWriter 时会话是否过期?
【问题讨论】:
当我从 Android 访问 servlet 时,我无法保持会话。我只是将参数与 URL 一起传递给从数据库收集数据并将其存储在会话中的 servlet,但我无法在后续请求中检索它。
当我在 servlet 中关闭 PrintWriter 时会话是否过期?
【问题讨论】:
这是客户端的问题。 HTTP 会话由 cookie 维护。客户端需要确保按照 HTTP 规范正确地将 cookie 发送回后续请求。 HttpClient API 为此提供了CookieStore 类,您需要在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);
// ...
要了解有关会话如何工作的更多信息,请阅读此答案:How do servlets work? Instantiation, sessions, shared variables and multithreading
【讨论】: