了解了,你可以在 forwardToPage
方法中调用外部 API,然后将获得的 URL 返回给前端,使用 JavaScript 在新窗口中打开该 URL。可以通过 AJAX 调用来实现这一点。
以下是一个示例:
JSF 页面
<h:commandButton value="Forward" action="#{bean.forwardToPage}" onclick="openInNewWindow(); return false;"/>
<script>
function openInNewWindow() {
// 通过 AJAX 调用后台方法
jsf.ajax.request(this, event, {
render: 'newUrlOutput',
onevent: function(data) {
if (data.status === 'success') {
var newUrl = document.getElementById('newUrlOutput').innerHTML;
window.open(newUrl, '_blank');
}
}
});
}
</script>
<h:outputText id="newUrlOutput" value="#{bean.newUrl}" style="display:none;" />
后端 Bean
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
@ManagedBean
@ViewScoped
public class Bean {
private String newUrl;
public void forwardToPage() {
// 调用外部 API 获取 URL
try {
URL url = new URL("https://api.example.com/getRedirectUrl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
Scanner scanner = new Scanner(url.openStream());
if (scanner.hasNext()) {
newUrl = scanner.nextLine();
}
scanner.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getNewUrl() {
return newUrl;
}
public void setNewUrl(String newUrl) {
this.newUrl = newUrl;
}
}
解释
-
JSF 页面:
-
<h:commandButton>
按钮会触发openInNewWindow
JavaScript 函数。 - 在
openInNewWindow
函数中,通过jsf.ajax.request
发起 AJAX 请求来调用forwardToPage
方法。 - 当 AJAX 请求成功时,会将后台返回的
newUrl
赋值给隐藏的<h:outputText>
组件,然后用window.open
在新窗口中打开该 URL。
-
-
后端 Bean:
-
forwardToPage
方法调用外部 API,并将返回的 URL 赋值给newUrl
属性。 -
newUrl
属性通过<h:outputText>
在页面中隐式呈现,用于 JavaScript 的处理。
-
这种方式可以确保外部 API 返回的 URL 能够在新窗口中正确打开。