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.

Answers


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:

Need Your Help

Kendo TabStrip, getting error - microsoft jscript runtime error object expected when switching tabs

javascript jquery asp.net-mvc kendo-ui kendo-tabstrip

I am using the Kendo TabStrip control on my MVC view page. I have 4 tabs. I am using a partial view for each tab. I am using Ajax to render the HTML in each tab. I am also using jquery in my

Several MongoDB nodes in a single Datasource

mongodb jasper-reports sharding jasperserver mongodb-java

I need to apply a whole IP range as a Datasource for the reports,

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.