BACKGROUND
I am learning Java and currently on JSF. I come from an ASP.NET MVC background and have only recently been exposed to the Java world, so be gentle 😉
PROBLEM
I can’t quite figure out how to get a model (which is of List<T>) into the JSF view. What I did when recently learning Struts was the following:
-
Created a Servlet like this:
@WebServlet(name = "ViewProductsServlet", urlPatterns = {"/ViewProductsServlet"})public class ViewProductsServlet extends HttpServlet {protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProductRepository repository = new ProductRepository(); List<Product> model = repository.getAll(); request.setAttribute("model", model); request.getRequestDispatcher("/viewProducts.jsp").forward(request, response); } -
Linked to the view products page like this:
<html:link forward="viewProducts" styleClass="btn btn-primary">View Products</html:link>
-
In the view, I got the model like this:
<%
List<Product> model = (List<Product>)request.getAttribute("model");
%>
and then I just iterated over the items with JSTL tags.. not sure if that was the “correct” way to do it, but it worked..
Now for the JSF stuff, I am trying to take a similar approach but I noticed that the <% %> tags don’t work in xhtml pages. Fair enough, but then how do I pass a collection to a page so I can display the items in a table/grid?
EDIT
Thanks to Sanjeevi.V, I can see that I am supposed to use the h:dataTable tag. However, it is not displaying data. Here is my code:
MODEL/Manage Bean:
@ManagedBean
@SessionScoped
public class EmployeeCollection {
private List<Employee> items;
public List<Employee> getItems() {
if (items == null) {
EmployeeRepository repository = new EmployeeRepository();
items = repository.getAll();
}
return items;
}
}
View Markup:
<div class="container-fluid">
<div class="row-fluid">
<div class="span8 offset2">
<h:dataTable class="table table-striped" value="#{EmployeeCollection.items}" var="item">
<h:column>
<f:facet name="header">First Name</f:facet>
#{item.getFirstName()}
</h:column>
<h:column>
<f:facet name="header">Last Name</f:facet>
#{item.getLastName()}
</h:column>
<h:column>
<f:facet name="header">Date of Birth</f:facet>
#{item.getDateOfBirth().toString()}
</h:column>
</h:dataTable>
</div>
</div>
</div>
I tried to follow that tutorial, so I’m not sure where I am going wrong. Personally, I don’t understand how it could work.. how does the EmployeeCollection bean get wired up? Is it because it’s got @SessionScoped that there is only ever one per session and so will use that? Even so, at the time of running, it would be a null object. What am I missing here? How can I make this work? I do indeed have rows in the database, so don’t ask about that. 🙂
Try the following code,
Managed Bean:
Markup:
source : http://www.mkyong.com/jsf2/jsf-2-datatable-example/
Hope this helps.