h:commandbutton,如何重定向到外部站点?(JSF 2)

时间:2011-08-23 10:07:24

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

当我使用命令按钮重定向到页面时,在我的项目中,你只需要提供没有扩展名的页面名称,然后在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>

然后是支持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;
    }

2 个答案:

答案 0 :(得分:6)

使用ExternalContext.redirect()

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

如果您知道链接已经使用

<a href="#{someBean.someLink}">#{msg.someMessage}</a>

答案 1 :(得分:1)

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

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