2
votes

I want to implement a situation where the user enter a URL, and if a specified condition is true in my managed bean this URL will be opened in a new web page.

I found this possibility:

The “h:link” tag is useful to generate a link which requires to interact with the JSF “outcome” , but lack of “action” support make it hard to generate a dynamic outcome.

The “h:commandLink” tag is suck, the generated JavaScript is really scary! Not recommend to use this tag, unless you have a solid reason to support. But it supports the “action” attribute, which is what “h:link” lack of.

The “h:outputLink” is useful to generate a link which does not require to interact with the JSF program itself. At last, it will be perfect if the “action” attribute is added into the “h:link“.

But I didn't find a way to launch the open web page from my managed bean after the condition is verified.

I'm using JSF2.0, Facelets and PrimeFaces 3.4.

1

1 Answers

8
votes

To open the target in a new window using one of those link components, you need to specify target="_blank" attribute, but this will already open the target in a new window at the moment you click the link and does thus not depend on the response. You basically need to open the target in a new window at the moment the response has been arrived. The only way is returning a JavaScript window.open() call to the response so that it get executed in the webbrowser.

In standard JSF, you could just render JavaScript's window.open() conditionally.

<h:form>
    <h:inputText value="#{bean.url}" />
    <h:commandButton value="submit" action="#{bean.submit}">
        <f:ajax execute="@form" render="@form" />
    </h:commandButton>
    <h:outputScript rendered="#{bean.valid}">window.open('#{bean.url}')</h:outputScript>
</h:form>

with

private String url;
private boolean valid;

public void submit() {
    valid = validate(url);
}

// ...

In PrimeFaces, you could use RequestContext#execute() to specify JavaScript code which needs to be executed on complete of the response.

<h:form>
    <p:inputText value="#{bean.url}" />
    <p:commandButton value="submit" action="#{bean.submit}" />
</h:form>

with

private String url;

public void submit() {
    if (validate(url)) {
        RequestContext.getCurrentInstance().execute("window.open('" + url + "')");
    }
}

// ...

Unrelated to the concrete problem: the ranty statements which you cited there are seemingly written by someone who know nothing about HTTP/HTML basics (limitations of GET vs POST and so on). Please take them with a good grain of salt.