2017-02-10 26 views
0

我目前正在研究Spring應用程序中的一段代碼,它需要確定登錄的用戶是應該重定向到新站點(在另一個服務器上)還是繼續舊的。在POST後將應用程序重定向到其他服務器

我一直在通過POST使用Apache HttpClient來做到這一點,我可以從舊登錄名登錄新網站。

我的問題是,我不能夠在登錄後瀏覽到新網站重定向和「處於登錄狀態」,而不是它重定向我到新網站的登錄頁面,因爲我沒有登錄in。

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。

回答

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> 
1

登錄的會話通常基於某種cookie。 Cookie被附加到域中。在這個原因中,如果你登錄到第一個站點(localhost:9080),那麼你有一個cookie。如果你去一個不同的網站(比如說google.com),那麼你的cookie在那裏是無效的,所以HttpClient不會發送cookie。

如果您需要,您可以手動操作/創建新的Cookie,以使其對新網站有效。

相關問題