Home > DWR > Resource Forwarding – Getting Page Response using DWR in Spring MVC

Resource Forwarding – Getting Page Response using DWR in Spring MVC


By this post I would like to describe my recent exposure with DWR2.0 and Spring2.0.Recently I got chance to develop my projects using Spring2.0 Framework. I really enjoyed working with Spring.

Technologies reuired :

1).Spring MVC
2).DWR for AJAX calls
4).Acegi security
5).Tiles 1.3
6).JSTL 1.1

DWR provides sufficient amount of support to all our ajax calls requirement.It allows code in a web browser to use Java functions running on a web server as if those functions were within the browser.While developing the module of search it was required that in the search result page when user clicks for detail view of the result, It was required to call a javascript methods which has to fetch the data (detail information) from the DB and has to be shown at a div location on that page. That is , I have to get a page response through DWR call against an ID.

Approach that worked for me as follows:

1. Search Result JSP page:

Add following lines to jsp page:

<script type='text/javascript' src='/spring/dwr/interface/AjaxCall.js'></script>
<script type='text/javascript' src='/spring/dwr/engine.js'></script>
<script type='text/javascript' src='/spring/dwr/util.js'></script>

and these below lines as sample :

<div class="view_word_resume" id="viewWordRes" style="vertical-align:top;">
<a id="vwResShow" href="javascript:callViewResume(id,'box_viewWordRes')">View Detail</a>
<div id="box_viewWordRes" style="display:none;"></div>

Here when user clicks the view Detail links it calls a javascript method callViewResume(id,divid) which takes two argument, first is id against which it will fetch the data from DB and next one is divId where the fetched jsp page response would be shown.

2. Javascript method call:

Define call back javascript function and attach that to some event to it.

function callViewResume(id,divId){

getDetailByDwr() method is a dwr method which is written in the service layer of the module , which takes id as argument and calls a URL with id as query string which in return fetches a page response as String and gives that response to the callback function of our javascript method. And this javascript method puts that string value to the divId specified.

3. Java method at service layer

import these two classes :

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

below method for fetching page response:

public String getDetailByDwr(String id,HttpServletRequest request) throws IOException,ServletException{
    WebContext wctx = WebContextFactory.get();
    return wctx.forwardToString("/detailView.html?id="+id);

Here first we are creating an object for WebContext using the WebContextFactory. From the object of WebContext we are calling a function forwardToString() which takes a URL as an argument and reurns the html response of that url as String.