LuckyLuke
LuckyLuke

Reputation: 49097

How to obtain data from database when using h:link and h:button in JSF GET method

I am having a simple application with one entity. The entity is Car so I have made CRUD methods and a "get all cars" method. I am using JSF to make a website where I have the list of cars with a edit/show/delete link next to it. Instead of using POST I want to use GET on the show/edit links. So far I have used the h:link with the id as a parameter and I set them in the show page as viewParams.

The whole application works but I have a question. Currently I am doing the EJB invocation that finds the appropiate car from the ID in the set-method for a car ID in the backing bean. I have not found another way of doing this so I wonder if this is correct? Because I don't have an action method that is invoked the same way as h:commandButton and return the string for the page that it shall navigate to.

Upvotes: 1

Views: 427

Answers (1)

BalusC
BalusC

Reputation: 1109635

You can use <f:event type="preRenderView"> to trigger a view action before the view is rendered.

E.g.

<f:metadata>
    <f:viewParam name="id" value="#{cars.id}" />
    <f:event type="preRenderView" listener="#{cars.init}" />
</f:metadata>

with

@ManagedBean
@ViewScoped
public class Cars {

    private Long id;
    private Car car;

    @EJB
    private CarService service;

    public void init() {
        car = service.find(id);
    }

    // ...
}

Note that in upcoming JSF 2.2, the <f:event type="preRenderView"> can be replaced by the new <f:viewAction> which is more self-documenting:

<f:metadata>
    <f:viewParam name="id" value="#{cars.id}" />
    <f:viewAction action="#{cars.init}" />
</f:metadata>

See also:

Upvotes: 2

Related Questions