• Home
  • RSS Feed
  • Log in

How to make Displaytag ajax enabled using DWR?
Posted by Mischa Dasberg late at night: December 10th, 2007

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:

  • Spring
  • Hibernate
  • Dwr
  • Displaytag

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<Episode> 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="eps" sort="external" requestURI="replaceURI" pagesize="30" partialList="true" size="${nrOfEps}">
    <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<T> 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<Episode> {
	private EpisodeRepository episodeRepository;
 
	@Override
	public int getNumberOfObjects() {
		return episodeRepository.getNumberOfEpisodes();
	}
 
	@Override
	public String getNumberOfObjectsName() {
		return "numberOfEpisodes";
	}
 
	@Override
	public List<Episode> 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.

  • Share/Bookmark

Filed under Ajax, Java | 16 Comments »



16 Responses to “How to make Displaytag ajax enabled using DWR?”



    AJAX coding school » Blog Archive » AJAX Code [2007-12-11 02:04:02] Says:
    Posted at: December 11, 2007 at 4:20 am

    [...] How to make Displaytag ajax enabled using DWR? By Mischa Dasberg 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. Xebia Blog – http://blog.xebia.com [...]



    Balaji D Loganathan Says:
    Posted at: December 11, 2007 at 4:22 am

    Very well written and useful.
    Good one Mischa.



    Bart Guijt Says:
    Posted at: December 11, 2007 at 10:27 am

    Well done, Mischa! I like the illustration.



    Krish Says:
    Posted at: December 26, 2007 at 1:08 pm

    hi,

    liked the article… i was wondering if you can provide a struts based path.. I am new to struts and my application is written in struts. Cant change the arch :(

    Thanks,
    Krish



    Krishna Says:
    Posted at: February 13, 2008 at 4:13 pm

    Where is the EpisodeService.js and what does it contain?

    U said exposing the class functionality (EpisodeService.findAllObjects(criteria, function(data)). How to do that?



    Mischa Dasberg Says:
    Posted at: February 14, 2008 at 11:05 am

    If you look at the attached project and look in the file displaytag-service.xml you see the episodeService bean definition. You also see a dwr:remote block.
    By exposing the Bean using DWR, it will create a Javascript file EpisodeService.js. So Javascript can access the exposed Service.



    Ana Says:
    Posted at: March 10, 2008 at 10:16 pm

    Amazing article! Just what I was looking for. Thanks!



    Alan Says:
    Posted at: May 28, 2008 at 2:15 pm

    I do not see where
    public void setViewFragment(String viewFragment)
    is being called? What is expected to be passed in the viewFragment?



    amurray Says:
    Posted at: May 28, 2008 at 4:21 pm

    In the sample code I do not see where

    public void setViewFragment(String viewFragment) {
    this.viewFragment = viewFragment;
    }

    is being called. What is the viewFragment? Is it the entire table before displayTag has processed it or after displayTag processed it?



    Mischa Dasberg Says:
    Posted at: May 28, 2008 at 9:10 pm

    viewFragment is injected in the springContext.
    It represents the part that will be rerendered.

    If you look in displaytag-service.xml you will see that I define the following bean.

    <bean id="episodeService" class="com.xebia.displaytag.service.EpisodeService">
    <property name="episodeRepository" ref="episodeRepository"/>
    <property name="viewFragment" value="/episodes.htm"/>
    <property name="tableId" value="episode"/>
    <dwr:remote javascript="EpisodeService"/>
    </bean>

    As you can see I the viewFragment that is injected is /episodes.htm which points to episodes.jsp (see viewResolver)



    Rahul Says:
    Posted at: June 5, 2008 at 11:17 am

    Hi,

    Is it required to have two files , episode.jsp and index.jsp?

    Can’t we just include/manually copy the episode.jsp in the index.jsp…

    What will be the effects….

    Anyways, very nice article..

    rahul



    amurray Says:
    Posted at: June 6, 2008 at 5:22 pm

    Mischa thanks for the clarification on the viewFragment. I have made a lot of headway since then. The question that I have now is how do you handle exports with this approach? The link:

    javascript:updateTableL4(’d-5302-e=2&6578706f7274=1′) is not sufficient to cause the save as dialog to open.

    Thanks for your help,
    Alan



    ck Says:
    Posted at: July 2, 2008 at 6:46 am

    really nice, but i don’t know how to make it work, any more easier way and less codes to do it?



    Mischa Dasberg Says:
    Posted at: July 6, 2008 at 9:03 pm

    Hi Alan,

    I haven’t implemented that, because I had multiple displaytags on one page and I wanted to export all that data in one export. Unfortunately you cannot do that, so I created a custom action that exported the data to excel using jexcelapi.

    But of course you can implement it. It should not be that hard as I have already done it for sorting etc.



    ppl Says:
    Posted at: August 12, 2008 at 1:52 pm

    Hi Mischa

    Very good example of ajax and displaytag. I got your example working fine but when I extended it I found that the criteria keep being null so my links broke. Any ideas?

    Thanks
    PPL



    Sarav Says:
    Posted at: January 19, 2009 at 5:54 pm

    Excellent work.. I learnt a new Idea.. going to implement in my project.. Great work. Appreciate your knowledge sharing.. thank you once again..



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    esb Spring Agile Awareness Workshop Hibernate IntelliJ Maven SOA qcon Grails Groovy Performance product owner Scala JavaOne Java Functional Programming XML Agile Lean Poppendieck Xebia Seam fitnesse Introduction to Agile Semantic Web Testing Architecture Ajax Closures Scrum
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs