POST后将应用程序重定向到其他服务器

时间:2017-02-10 17:28:50

标签: java spring post login httpclient

我目前正在处理spring应用程序中的某段代码,该应用程序需要确定登录的用户是应该重定向到新站点(在另一台服务器上)还是继续使用旧站点。 / p>

我通过POST使用Apache HttpClient进行此操作,我可以从旧登录名登录新网站。

我的问题是,我无法在登录后将浏览器重定向到新网站,并且"仍然登录"而是将我重定向到新网站的登录页面因为我没有登录。

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重定向到控制器或jsp&#39。

2 个答案:

答案 0 :(得分:1)

登录会话通常基于某种cookie。 Cookie附加到域。在这个原因中,如果您登录到第一个站点(localhost:9080),那么您就有了一个cookie。如果您访问其他网站(例如google.com),那么您的Cookie无效,因此HttpClient不会发送Cookie。

如果您需要,可以手动操作/创建新的Cookie,使其对新网站有效。

答案 1 :(得分:0)

我终于让它工作了,这是一个非常古老的项目,在它的html中使用了框架。所以我通过JSP + javascript发布了这样的帖子:

请注意target="_top"属性,该属性允许在框架外加载其他网页。否则它将无效。

<form action="<%=newLoginUrl%>" method="post" id="redirectForm" target="_top">
    <input type="hidden" name="documentNumber" value="<%=docNum%>" />
    <input type="hidden" name="username" value="<%=userName%>" />
    <input type="hidden" name="password" value="<%=userPassword%>" />
</form>


<script type="text/javascript">
    document.getElementById("redirectForm").submit();
</script>