h:commandbutton, how to redirect to external site?(JSF 2) [duplicate]

家住魔仙堡 提交于 2020-02-08 08:49:40

问题


When i use command button to redirect to pages, inside my project, u just need to give the name of the page with no extention, followed by ?faces-redirect=true in the action attribute and i will get redirected.

But what if i want to get redirected to an external page(example:www.google.com)?

I tried in many ways:

www.google.com, google.com, http://google.com

but i failed.

This is what i did:

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

and then the 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;
    }

Note: the value returned by retrieveLink(); is always www.google.com(100% sure)

I get no errors at all in the console, the page just refreshes. Also i am sure the first if clause validates to true, so i see no reason for it to jump to return null.

Update

I tried with external context, but i get a 404 because it appends the current url to the link string:

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;
    }

回答1:


Use ExternalContext.redirect()

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

and if you know the link already just use

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




回答2:


You can do this creating an input with type="button" between a link tag "a". Something like this:

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


来源:https://stackoverflow.com/questions/31809414/open-new-page-with-hcommandbutton-in-jsf-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!