0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メモ7

Posted at

当然,可以使用不通过 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";
    }
}

解释

  1. JSF 页面:

    • <h:commandButton> 设置了 onclickoncomplete 属性。onclick 中设置一个隐藏字段 newWindowField 的值为 true,表示需要在新窗口中打开 URL。
    • oncomplete 中调用 openInNewWindow 函数。
    • openInNewWindow 函数检查隐藏字段 newWindowField 的值,如果为 true,并且有有效的 newUrl,则在新窗口中打开该 URL,并重置隐藏字段的值。
  2. 后端 Bean:

    • forwardToPage 方法调用外部 API 并设置 newUrl 属性。
    • newWindow 属性用于控制是否在新窗口中打开 URL,通过隐藏字段与前端交互。

这种方法不依赖 AJAX,而是通过标准的表单提交和隐藏字段来传递信息,确保在新窗口中打开动态 URL。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?