当然,可以使用不通过 AJAX 的方式来实现这个需求。可以通过提交表单时设置一个隐藏字段,然后在提交后使用 JavaScript 打开新窗口。下面是一个示例:
JSF 页面
<h:form id="mainForm">
<h:commandButton id="forwardButton" value="Forward" action="#{bean.forwardToPage}"
onclick="document.getElementById('newWindowField').value='true';"
oncomplete="openInNewWindow();"/>
<h:inputHidden id="newWindowField" value="#{bean.newWindow}" />
<h:outputText id="newUrlOutput" value="#{bean.newUrl}" style="display:none;" />
<h:outputScript>
function openInNewWindow() {
var newWindow = document.getElementById('newWindowField').value;
var newUrl = document.getElementById('newUrlOutput').innerText;
if (newWindow === 'true' && newUrl) {
window.open(newUrl, '_blank');
document.getElementById('newWindowField').value = '';
}
}
</h:outputScript>
</h:form>
后端 Bean
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class Bean {
private String newUrl;
private String newWindow;
public void forwardToPage() {
// 调用外部 API 获取 URL
newUrl = callExternalApiAndGetUrl();
}
public String getNewUrl() {
return newUrl;
}
public void setNewUrl(String newUrl) {
this.newUrl = newUrl;
}
public String getNewWindow() {
return newWindow;
}
public void setNewWindow(String newWindow) {
this.newWindow = newWindow;
}
private String callExternalApiAndGetUrl() {
// 模拟调用外部 API 并返回 URL
return "https://example.com";
}
}
解释
-
JSF 页面:
-
<h:commandButton>
设置了onclick
和oncomplete
属性。onclick
中设置一个隐藏字段newWindowField
的值为true
,表示需要在新窗口中打开 URL。 -
oncomplete
中调用openInNewWindow
函数。 -
openInNewWindow
函数检查隐藏字段newWindowField
的值,如果为true
,并且有有效的newUrl
,则在新窗口中打开该 URL,并重置隐藏字段的值。
-
-
后端 Bean:
-
forwardToPage
方法调用外部 API 并设置newUrl
属性。 -
newWindow
属性用于控制是否在新窗口中打开 URL,通过隐藏字段与前端交互。
-
这种方法不依赖 AJAX,而是通过标准的表单提交和隐藏字段来传递信息,确保在新窗口中打开动态 URL。