how to use a list containing the query result with hibernate and display it in jsp
In my servlet I construct the query like the following:
net.sf.hibernate.Session s = null;
net.sf.hibernate.Transaction开发者_JAVA百科 tx;
try {
s= HibernateUtil.currentSession();
tx=s.beginTransaction();
Query query = s.createQuery("select opcemployees.Nom,opcemployees.Prenom,dailytimesheet.TrackingDate,dailytimesheet.Activity," +
"dailytimesheet.ProjectCode,dailytimesheet.WAName,dailytimesheet.TaskCode," +
"dailytimesheet.TimeSpent,dailytimesheet.PercentTaskComplete from Opcemployees opcemployees,Dailytimesheet dailytimesheet " +
"where opcemployees.Matricule=dailytimesheet.Matricule and dailytimesheet.Etat=3 " +
"group by opcemployees.Nom,opcemployees.Prenom" );
List opdts= query.list();
request.setAttribute("items", opdts);
request.getRequestDispatcher("EspaceValidation.jsp").forward(request, response);
} catch (HibernateException e){ e.printStackTrace();}
But in the jsp I can't display the result correctly. I do the following in JSP:
<table>
<c:forEach items="${items}" var="item">
<tr>
<td>${item}</td>
</tr>
</c:forEach>
</table>
thanks for help.
You need to determine the object type of every list item. It should be an existing model object (a Javabean like class with private properties and public getters). The ${item}
in JSP would only display its Object#toString()
outcome, something like com.packagename.ClassName@hashcode
. Or if the toString()
method is overridden, then you would see a "human friendly" string. Other way to reveal the type would then be debugging the getClass()
of the list item:
System.out.println(opdts.get(0).getClass().getName());
Once the type is known and the property names are known, then you can just access its properties in EL like ${item.someProperty}
, ${item.otherProperty}
, etcetera.
Update: since the list seems to contain Object[]
as every item (thus the list signature is actually List<Object[]>
), here's how you could display it in JSP/JSTL:
<table>
<c:forEach items="${list}" var="objects">
<tr>
<c:forEach items="${objects}" var="object">
<td>${object}</td>
</c:forEach>
</tr>
</c:forEach>
</table>
This does basically the same as following in "raw" Java:
System.out.println("<table>");
for (Object[] objects : list) {
System.out.println("<tr>");
for (Object object : objects) {
System.out.println("<td>" + object + "</td>");
}
System.out.println("</tr>");
}
System.out.println("</table>");
精彩评论