How to invoke JSF backing bean method from link/non-faces-request

jsf-2

Solution

Use `<f:viewParam>` in the target view to set GET parameters as bean properties and use `<f:event type="preRenderView">` to invoke an action on them.

In `show.xhtml`:

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" required="true" />
    <f:event type="preRenderView" listener="#{bean.load}" />
</f:metadata>
<h:message for="id" />

In managed bean:

private Integer id;
private Data data;

public void load() {
    data = service.find(id);
}

Note that in the above example the URL `http://localhost/show.xhtml?id=30` is sufficient. You can always set more parameters as bean properties and have one "God" bean which delegates everything, but that's after all likely clumsy.

Also note that you can just attach a `Converter` to the `<f:viewParam>` (like as you could do in `<h:inputText>`). The `load()` method is then most likely entirely superfluous.

<f:metadata>
    <f:viewParam name="id" value="#{bean.data}" 
        converter="dataConverter" converterMessage="Bad request. Unknown data."
        required="true" requiredMessage="Bad request. Please use a link from within the system." />
</f:metadata>
<h:message for="id" />

See also:

- Communication in JSF 2 - Processing GET request parameters

- What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Problem

The use case is calling a method on a JSF 2.x Backing Bean directly from a hyperlink (Non-Faces-Request). What is the best way to do this? I imagine to do something like this: The Link: ``` http://localhost/show.xhtml?id=30&backingbeanname=loaddata&method=load ``` The Backing Bean: ``` @Named (value = "loaddata") public class DataLoader { public void load(int id){ ... } } ```

Original source

Related problems