3

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){ ... }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user1866929
  • 33
  • 1
  • 5

1 Answers1

5

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Although the solution from BalusC invokes the method on the bean but it does not trigger jsf navigation. After a while I found this solution which covers exactly my use case:[link]http://docs.jboss.org/seam/3/latest/reference/en-US/html_single/#viewaction – user1866929 Dec 13 '12 at 20:04
  • @user1866929: you didn't state that you need navigation. For that, head to this answer: http://stackoverflow.com/questions/13530651/jsf-call-backing-bean-method-without-rendering-the-page-using-url-parameters/13530836#13530836 Note that JSF 2.2 will come with a similar ``. – BalusC Dec 13 '12 at 20:13