tags:

views:

27

answers:

1

I need to render an HTML table from a Servlet, in response to an AJAX request. I'm wondering what the best way to go about this is? I've explored using an javax.faces.component.html.HtmlDataTable. One of the questions I have regarding this method is how to render the HTML once the table has been populated. From the looks of it, a FacesContext is required.

Any ideas?

+2  A: 

JSF isn't what you're looking for. It's a component based MVC framework. Just do it either the easy and ugly way in a simple loop in the servlet:

writer.write("<table>");
for (Item item : items) {
    writer.write("<tr>");
    writer.write(String.format("<td>%s</td>", item.getFoo()));
    writer.write(String.format("<td>%s</td>", item.getBar()));
    writer.write("</tr>");
}
writer.write("</table>");

Or store it as request attribute and forward to a JSP

request.setAttribute("items", items);
request.getRequestDispatcher("items.jsp").forward(request, response);

Which in turn basically contains the following:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<table>
    <c:forEach items="${items}" var="item">
        <tr>
            <tr>${item.foo}</td>
            <tr>${item.bar}</td>
        </tr>
    </c:forEach>
</table>

Or rather look for a different and more flexible data format like JSON so that the client has the freedom how to render it. Here's an example which uses Google Gson.

writer.write(new Gson().toJson(items));

Which you can render into a table using jQuery as follows:

$.getJSON('json/items', function(items) {
    var table = $('#someelement').append('<table>');
    $(items).each(function(i, item) {
        var row = table.append('<tr>');
        row.append('<td>').text(item.foo);
        row.append('<td>').text(item.bar);
    });
});

See also:

BalusC
Thanks BalusC. I used a StringBuilder to do it. Seems pretty light weight.I actually got the HtmlDataTable idea from your blog. --> http://balusc.blogspot.com/2006/06/using-datatables.html#PopulateDynamicData
Andrew