Search code examples
javajsfjakarta-eejsf-2java-ee-6

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


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

Solution

  • 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>