Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect if a f:viewParam is empty

Сan I do a redirect (or error) if a f:viewParam is empty?

<f:metadata>
    <f:viewParam name="accountId" value="#{accountMB.id}"/>
</f:metadata>

When I add required="true", nothing happens. What are the options?

like image 942
zerg Avatar asked Jan 08 '23 12:01

zerg


1 Answers

When I add required="true", nothing happens

You need <h:message(s)> to show faces messages associated with a given (input) component. You probably already know how to do that for <h:inputText>. You can do exactly the same for <f:viewParam>.

<f:metadata>
    <f:viewParam id="foo" ... required="true" />
</f:metadata>
...
<h:message for="foo" />

Сan I do a redirect (or error) if a f:viewParam is empty?

Not directly with standard JSF validation facilities. You'd need to do the job manually in <f:viewAction> (you need to make sure that you don't have any validators/converters on it, otherwise it wouldn't be invoked due to a validation/conversion error; you could alternatively use <f:event type="preRenderView">).

<f:metadata>
    <f:viewParam value="#{bean.foo}" />
    <f:viewAction action="#{bean.checkFoo}" />
</f:metadata>

public String checkFoo() {
    if (foo == null || foo.isEmpty()) {
        return "some.xhtml"; // Redirect to that page.
    } else {
        return null; // Stay on current page.
    }
}

Sending a HTTP error can be done as below (this example sends a HTTP 400 error):

public void checkFoo() {
    if (foo == null || foo.isEmpty()) {
        FacesContext context = Facescontext.getCurrentInstance();
        context.getExternalContext().responseSendError(400, "Foo parameter is required");
        context.responseComplete();
    }
}

If you happen to use the JSF utility library OmniFaces, then you can use the <o:viewParamValidationFailed> tag for the very purpose without needing additional backing bean logic.

Sending a redirect on view param validation fail:

<f:metadata>
    <f:viewParam ... required="true">
        <o:viewParamValidationFailed sendRedirect="some.xhtml" />
    </f:viewParam>
</f:metadata>

Sending a HTTP 400 error on view param validation fail:

<f:metadata>
    <f:viewParam ... required="true">
        <o:viewParamValidationFailed sendError="400" />
    </f:viewParam>
</f:metadata>

See also:

  • What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
like image 66
BalusC Avatar answered Jan 20 '23 11:01

BalusC