我正在努力实现以下目标:
1) 最终用户将发布到 servlet(我们称之为 GW) - GW 将为接下来的请求存储他的 session 。
2)对于GW收到的每个请求,GW将发布到另一个servlet(将称为API)
3)只有GW可以发布到API(SSL安全),并且两者都有固定的IP(尽管与此问题无关)
4) 对于发布到 API 的每个请求,API 还必须为将来的请求维护一个 session 。
5) GW 使用以下实现发布到 API:
try {
HttpPost httppost = new HttpPost(uri);
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse response = httpclient.execute(httppost, httpContext);
} finally {
httpclient.getConnectionManager().shutdown();
}
6)API将接收如下请求:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(false);
// isSessionValidFromURL = req.isRequestedSessionIdFromURL();
// isSessionValidFromCookie = req.isRequestedSessionIdFromCookie();
isSessionValid = req.isRequestedSessionIdValid();
if (isSessionValid) {
...
...
}
...
}
7) 在 API 中,如果请求是新请求,它将创建一个新 session ,将参数存储在数据库中并构建全局变量等等。
问题是:发送登录(GW 向 API 发送登录)命令后,API 创建新 session 到目前为止一切顺利。在第二个命令中,它无法在以下代码行上验证 session :
isSessionValid = req.isRequestedSessionIdValid();
isSessionValidFromURL = req.isRequestedSessionIdFromURL();
isSessionValidFromCookie = req.isRequestedSessionIdFromCookie();
全部返回 false。我尝试使用如上所示的 cookie 机制发送 session id,并尝试发送收到的 session id from the url没有成功。
编辑:解决方案:This wonderful Post通过 url 传递(它是 SSL,因此不会造成安全漏洞)
最佳答案
此问题的一个解决方案是:
...
...
httpclient.setHttpRequestRetryHandler(myRetryHandler);
uri = AppInit.fieldProxyURI + ";jsessionid=" + sessionInfo.getAttribute(GatewayConstants.PROXYSESSIONID);
HttpPost httppost = new HttpPost(uri);
nvps =(List<NameValuePair>) sessionInfo.getAttribute(GatewayConstants.PROXY_QUERY_PARAMS);
httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
ProxyPoster thread = new ProxyPoster(httpclient,httppost,sessionInfo,localContext);
thread.start();
thread.join();
} finally {
// leave the connection resource open
}
static class ProxyPoster extends Thread {
//fields here..
// constructor here...
@Override
public void run() {
try {
HttpResponse response = httpClient.execute(httppost, context);
// proccess response
} catch (Exception e) {
httppost.abort();
}
}
这样就可以维持 session ,保持 httpclient 连接打开并通过 URL 发布收到的 session ID。 希望这会帮助其他人...
关于java - 从一个 servlet 发送到另一个 servlet 时无法维持 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14099825/