【问题标题】:h:commandbutton, how to redirect to external site?(JSF 2) [duplicate]h:commandbutton,如何重定向到外部站点?(JSF 2)[重复]
【发布时间】:2011-11-01 19:52:14
【问题描述】:

当我使用命令按钮重定向到页面时,在我的项目中,你只需要给出不带扩展名的页面名称,然后在 action 属性中添加 ?faces-redirect=true我会被重定向。

但是如果我想被重定向到外部页面(例如:www.google.com)怎么办?

我尝试了很多方法:

www.google.com、google.com、http://google.com

但我失败了。

这就是我所做的:

<h:form>
            <h:commandButton 
                action="#{mainPageBB.goToLink}" value="#{msgs.clickhere}"/>
        </h:form>

然后是backing bean:

@Named("mainPageBB")
@RequestScoped
public class MainPageBB {

    @EJB
    private ILinkManagerEJB linkManagerEJB;


    public String goToLink() {      
        String link = linkManagerEJB.retrieveLink();
        if(link != null) {
                    System.out.println(link);       
            return link.trim() + "?faces-redirect=true";
        }
        return null;
    }

注意:retrieveLink(); 返回的值始终是 www.google.com(100% 确定)

我在控制台中完全没有错误,页面只是刷新。另外我确信第一个 if 子句验证为 true,所以我认为没有理由跳转到返回 null。

更新

我尝试使用外部上下文,但我得到一个 404,因为它将当前 url 附加到链接字符串:

public String goToRandomLink() {        
        String link = linkManagerEJB.retrieveRandomLink();
        if(link != null) {      
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            try {
                externalContext.redirect(link.trim());
            } catch (IOException e) {               
                e.printStackTrace();
            }           
        }
        return null;
    }

【问题讨论】:

    标签: java jsf jakarta-ee jsf-2 java-ee-6


    【解决方案1】:

    使用ExternalContext.redirect()

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    externalContext.redirect(link.trim());
    

    如果你知道链接已经使用

    &lt;a href="#{someBean.someLink}"&gt;#{msg.someMessage}&lt;/a&gt;

    【讨论】:

    • 我想我很接近了,当我这样做时会发生什么是链接字符串附加到我的项目 URL,所以我收到 404 错误,因为我尝试重定向到:localhost:8080/MyProject/www.google.com
    • 是的。我们没有返回 URL,而是返回视图名称。参见 BalusC 中的 this
    • 我知道该链接的唯一原因是我有意将值 www.google.com 放入数据库中,但将来我不知道目的地会是什么。所以我需要找到该命令按钮重定向到链接变量中保存的值的方法
    • 我刚刚看了你给我的链接,我明白,但我的问题是我的目标是从数据库中检索到的一些未知的外部 url(在我项目的某个文件夹中没有) .我不确定 ExternalContext 是否是我需要的,我有点困惑。
    • 是的,我知道该链接只是为了了解return 如何从行动中发挥作用。我的答案正文中提到的ExternalContext.redirect() 清楚地提到了您的问题的答案
    【解决方案2】:

    您可以在链接标签“a”之间创建一个带有 type="button" 的输入。 像这样的:

    <a href="http://www.google.com">
        <input type="button" value="Button text" />
    </a>
    

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2016-03-05
      • 2012-01-27
      相关资源
      最近更新 更多