Blog

How to make Displaytag ajax enabled using DWR?

10 Dec, 2007
Xebia Background Header Wave

Displaytag is an open source suite of custom tags with which you can easily display a collection of Objects as a table including direct support for paging and sorting. Normally selecting a new page, or sorting the tables leads to a complete page-refresh. It is more user-friendly to refresh only the data in the table using Ajax technology, however Displaytag doesn’t offer this out-of-the-box. But we can of course try to add support for this using one of the many Ajax frameworks that are currently available.
A non ajax enabled Displaytag would do a request to a controller for every action such as a sorting or selecting a next page. This would result in a complete page refresh (step 1-8 ). When we Ajax enable the Displaytag we skip the page refresh and only refresh a specific piece of the page using an exposed service which provides the updated HTML fragment (step 1a-8a).


flow

In the example I am going to use the following technologies:

The senario is as follows: We want to display episodes in a table. We want to do this in an Ajax way by using DWR. But where do we start?
Well, first of all we create a domain object called Episode.

public class Episode {
   long id;
   String show;
   String name;
   String episode;
   String airDate;
....
}

Next we create a repository.

public class EpisodeRepository extends HibernateDaoSupport {
    public List getAllEpisodes(int firstResult, int maxResults, String orderBy,
    boolean ascending) {
        Criteria criteria = getSession().createCriteria(Episode.class)
            .setFirstResult(firstResult)
        .setMaxResults(maxResults)
        .addOrder(ascending ? Order.asc(orderBy) : Order.desc(orderBy));
        return criteria.list();
    }
    public int getNumberOfEpisodes() {
        Criteria criteria = getSession().createCriteria(Episode.class);
    criteria.setProjection(Projections.count("id"));
    return (Integer)criteria.uniqueResult();
    }
}

And a Jsp containing the Displaytag for presenting the collection of Episodes.
<display:table id="ep" name="<i><b>eps</b></i>" sort="external" requestURI="<i><b>replaceURI</b></i>" pagesize="30" partialList="true" size="${<i><b>nrOfEps</b></i>}">
<display:setProperty name="basic.empty.showtable" value="true" />
<display:column title="Show" property="show" sortable="true" sortName="show" />
<display:column title="Name" property="name" sortable="true" sortName="name" />
<display:column class="Episode" property="episode" sortable="true" sortName="episode" />
<display:column title="Airdate" property="airDate" sortable="true" sortName="airDate" />
</display:table>

Note that I use replaceURI as requestURI. This is very important because we are going to replace this with a call to a javascript method. Displaytag creates links like <a href="repaceURI?d-2332-o=1…."> and this should be replaced by <a href="javascript:update(‘d-2332-o=1…’)> so that we the links will be Ajax enabled too. Unfortunatly this is not the only thing that we need to update. We need to update the range we are displaying, the page we are currently on and how the data is sorted.
So how do we do that?
Well, we need to expose a service using DWR. DWR is an Ajax toolkit which make it possible to expose services which can then be called from JavaScript. I created an abstract generic class so that you can use it to enable any service you like. The abstract class contains the following method:

public abstract class AbstractExposedDisplayTagService implements InitializingBean {
    public void afterPropertiesSet() throws Exception {
        ....
    }
    public String findAllObjects(String criteria) {
        WebContext wctx = WebContextFactory.get();
    HttpServletRequest request = wctx.getHttpServletRequest();
    // split results and set values;
    int maxResults = Integer.parseInt(getCriterionValue(criteria, "maxResults", DEFAULT_MAXIMUM_RESULTS));
    int page = Integer.parseInt(getCriterionValue(criteria, displayTagPage, "1"));
    boolean ascending = Integer.parseInt(getCriterionValue(criteria, displayTagSortOrder, "1")) == 1 ? true : false;
    String orderBy = getCriterionValue(criteria, displayTagOrderBy, "id");
    int firstResult = (page - 1) * maxResults;
    int numberOfObjects = getNumberOfObjects();
    // set the episodes on the request so dwr can reload the jsp part.
    request.setAttribute(getObjectsName(), getObjects(firstResult, maxResults, orderBy, ascending));
    request.setAttribute(getNumberOfObjectsName(), numberOfObjects);
    try {
        String html = wctx.forwardToString(viewFragment);
        html = DisplayTagReplacementUtil.updatePagingHtml(html, page, maxResults, numberOfObjects, displayTagPage);
        html = DisplayTagReplacementUtil.updateSortOrderHtml(html, ascending, displayTagSortOrder);
        html = DisplayTagReplacementUtil.updateHtmlLinks(html);
        return html;
    } catch (ServletException e) {
        return "";
    } catch (IOException e) {
        return "";
    }
}
}

And here is the implementation.

public class EpisodeService extends AbstractExposedDisplayTagService {
    private EpisodeRepository episodeRepository;
    @Override
    public int getNumberOfObjects() {
        return episodeRepository.getNumberOfEpisodes();
    }
    @Override
    public String getNumberOfObjectsName() {
        return "numberOfEpisodes";
    }
    @Override
    public List getObjects(int firstResult, int maxResults, String orderBy, boolean ascending) {
        return episodeRepository.getAllEpisodes(firstResult, maxResults, orderBy, ascending);
    }
    @Override
    public String getObjectsName() {
        return "episodes";
    }
    public void setEpisodeRepository(EpisodeRepository episodeRepository) {
        this.episodeRepository = episodeRepository;
    }
}

Now you see that the findAllObjects method calls 3 static update methods on the DisplayTagReplacementUtil class.
These are responsible for the actual Ajax enabling. They use regular expressions to update the links, sorting etc..
Finally we need to add some JavaScript to be able to call the exposed service methods.
The following piece of code should be in the head of the jsp , in which you include the jsp containing the displaytag shown above in.
<script type='text/javascript' src='<c:url value="/dwr/interface/EpisodeService.js"/>'></script>
<script type='text/javascript' src='<c:url value="/dwr/engine.js"/>'></script>
<script type='text/javascript' src='<c:url value="/dwr/util.js"/>'></script>
<link rel="stylesheet" type="text/css" href='<c:url value="/css/displaytag.css"/>' />

and the javascript:
<script type="text/javascript">
function update(criteria) {
EpisodeService.findAllObjects(criteria, function(data) {
dwr.util.setValue("displayTable", data, { escapeHtml:false });
});
}
update("");
</script>

It is now a simple matter of extending the abstract class and you have Ajax enabled your Displaytag .
I have attached the example project here so you can look into the code yourself.

Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts