我目前正在 spring 应用程序中编写一些代码,该代码需要决定是否应将登录的用户重定向到新站点(在另一台服务器上)或继续在旧站点上。
我一直使用 Apache HttpClient 通过 POST 执行此操作,并且能够从旧登录名登录新站点。
我的问题是,登录并“保持登录”后我无法将浏览器重定向到新网站,而是将我重定向到新网站的登录页面,因为我尚未登录.
private void redirect2NewSite(HttpServletResponse response, String docNum, String username, String passwd) {
String url = "http://localhost:9080/website/doLogin";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("documentNumber", docNum));
urlParameters.add(new BasicNameValuePair("username", username));
urlParameters.add(new BasicNameValuePair("password", passwd));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse postResponse = client.execute(post);
String responseUrl = postResponse.getFirstHeader("Location").getValue();
response.setHeader("Location", responseUrl);
response.sendRedirect(responseUrl); // This sends me to the new page login
// But should send me to the home page, already logged in
}
旧项目使用 struts 重定向到 Controller 或 jsp。
最佳答案
登录的 session 通常基于某种 cookie。 cookie 附加到一个域。因此,如果您登录第一个站点 (localhost:9080),您就会在那里有一个 cookie。如果您访问其他网站(例如 google.com),您的 cookie 在那里无效,因此 HttpClient 不会发送 cookie。
如果您需要,您可以手动操作/创建新的 cookie,使其对新网站有效。
关于java - POST 后将应用程序重定向到其他服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42165296/