Bram Smeets Blog

 

Blog on Spring and DWR. AJAX with Spring made easy!

Your first cup of DWR…

Filed under: Ajax, Java, Spring — Bram Smeets at 9:08 pm on Sunday, April 24, 2005

Ok, so you want to create a more intuitive and responsive web application?
And you’ve decided to give AJAX, HttpXmlRequest, DWR or any other buzzword of the last few months, a try?
Now, if you’re also using the Spring framework for building you’re applications, than you’ve come to the right blog..This blog entry provides you with an introduction to Direct Web Remoting (DWR) in conjunction with Spring. It assumes a basic knowledge of both JavaScript and building applications using Spring.

DWR

DWR makes it easy to use of Asynchronous JavaScript and XML (AJAX) for calling methods in your business layer. It allows you to use the AJAX technology without having to deal with the implementation details and cross-browser issues.
Although DWR comes with some build-in Spring support, there is no out-of-the-box seamless integration with your Spring web application. For instance, it requires a separate servlet to be defined in your web.xml and has no means of accessing beans from your web application context.

Let’s get started

Ok, first of all let’s configure the DwrServlet as a Spring MVC controller instead of a separate servlet. Luckily for us, Spring provides a controller which does just that, the ServletWrappingController. Add the following code to your dispatcher servlet application context in order to enable DWR as a standard controller.

<bean id="dwrController" class= "org.springframework.web.servlet.mvc.ServletWrappingController">
<property name="servletClass">
<value>uk.ltd.getahead.dwr.DWRServlet</value>
</property>
<property name="initParameters">
<props>
<prop key="debug">true</prop>
</props>
</property>
</bean>

Note the debug init parameter, which is recommended during development, as it provides useful bean listings. More importantly, note the way to specify init parameters to configure DWR.
Add an entry to your url mapping which maps all requests for a certain context path to this controller. Note that the example below is just one example of how to map all request for an entire path. Note that the mapping of the dwrController should be the last mapping as it catches all requests.

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/**/*.html">defaultController</prop>
<prop key="/**/*">dwrController</prop>
</props>
</property>
</bean>

Also make sure to map requests for files with all extensions (and without extensions) to the Spring dispatcher servlet in your web.xml. So, instead of mapping just JSP or HTML extensions, make sure to map request for all file extensions like in the example below. The example assumes a Spring DispatcherServlet to be defined, named main.

<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

Configure DWR

The DWR servlet assumes a configuration file: /WEB-INF/dwr.xml, although this is configurable as an init parameter. Below is a sample configuration file, which assumes a bean with id productManager in your application context.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr10.dtd">

<dwr>
<allow>
<convert
converter=”bean”
match=”your.package.*”/>

<create
creator=”spring”
javascript=”productManager”>
<param name=”beanName” value=”productManager”/>
</create>
</allow>
</dwr>

First of all, note that currently DWR includes a Spring creator by default. This creator allows you to expose the productManager which is defined in your web application context. This can either be used to create a new application context, or to lookup an existing servlet application context or global web application context. This example assumes an existing application context to be available.

In the &lt;allow&gt; section of your configuration you first of all define a converter for converting standard JavaBeans to JavaScript objects. Although this comes with DWR it is not enabled by default. DWR does support conversion of amongst others primitives, Strings, Collections and Maps. Note, that you enable the bean converter only for the packages in which your data classes exist.

Last, you define a &lt;create&gt; entry for each bean you want to expose through DWR. In this example we expose a bean with id productManager. Note the javascript attribute which specifies the name of the JavaScript file to include in your page, as discussed below.

Access your bean

Now that we’re all set up, let’s access our exposed product manager. Assume the product manager has a method getAllProducts() which returns a List of all known products (which are JavaBeans). First we have to include the following two JavaScript files in our page:

&lt;script type='text/javascript' xsrc='/dwrPath/interface/productManager.js'&gt;&lt;/script&gt;
&lt;script type='text/javascript' xsrc='/dwrPath/engine.js'&gt;&lt;/script&gt;

Where ‘dwrPath‘ is the path under which you mapped the dwrController. Now, the only thing you have to do is call the method on the product manager. Assume we want have a button to retrieve the information and a span to display the product information in an unordered list:

&lt;input type="button" onclick="productManager.getAllProducts(productCallback);" value="Get all products"/&gt;
&lt;script type="text/javascript"&gt;
var productCallback = function(products) {
var text = 'Products: &lt;br&gt;&lt;ul&gt;';
for(i = 0; i &lt; products.length; i++) {
text += '&lt;li&gt;';
text += products[i].name;

text += ‘ (’;
price= products[i].price;
text += price.currency;
text += ‘ ‘;
text += price.value;
text += ‘)’;
text += ‘</li>’;
}
document.getElementById(’productlist’).innerHTML = text;
}
</script>
<span id=”productlist”>

Note the nested properties price.currency and price.value. They are resolved correctly only when the Product and Price class are under the path matched by the bean converter (i.e. your.package. in this example). Posting nested properties back to the server is not yet supported.

Debugging

DWR has some build in debugging support. As we set the debug init parameter to true, this debugging support is enabled. Point your browser to the path /dwrPath, where ‘dwrPath‘ is the path under which you mapped the dwrController. You will now get a listing of all beans that are exposed through DWR. By clicking one of them, you get a listing of all methods that are exposed. You can use this page to get examples of how to call the method (in the source).

Utilities

DWR has also some build in utility functions and means to perform error handling. More information on this can be found here. Also note that DWR claims to fallback to iframes for invoking methods on the server on platforms that do not support the HttpXmlRequest method, which should ensure high browser compatibility.

Good luck

I hope this small tutorial has given you some inside into how to use DWR in conjunction with Spring and help you to easily build web application using the AJAX technology. I’m currently looking into real-time, server-side form validation using this technology. Check back on this blog in order to stay up to date on the progress.

73 Comments »

Comment by joseph yi

April 27, 2005 @ 1:05 am

i got your email! thanks for notifying me about my comments being broken. :) i will look into the ServletWrapperController and the springmodules to see if i can be of any help. I’m not that familiar with Spring’s MVC, but it’d be nice if all this AJAX stuff was built-in. Thanks again!

Comment by Dan

June 6, 2005 @ 2:17 am

I think these instructions have been superseded by those found on the DWR website…

http://www.getahead.ltd.uk/dwr/spring.html

Comment by Vortex

June 18, 2005 @ 9:45 am

I can’t find ServletWrapperController in springmodules 0.2, was it removed or am I missing something?

Comment by Cristiane

June 22, 2005 @ 3:02 pm

I could’t find either the ServletWrapperController in any springmodules. Which version are you using?

Comment by Bram Smeets

June 22, 2005 @ 4:07 pm

The ServletWrappingController is part of the Spring Framework. It is not part of the Spring Modules.

The JavaDoc can be found here

Comment by ijoyce

June 23, 2005 @ 10:31 am

Add an entry to your url mapping which maps all requests for a certain context path to this controller. Also make sure to map requests for files with all extensions (and without extensions) to the Spring dispatcher servlet in your web.xml.

How about an example both of the web.xml and dispatcher servlet mappings?

Comment by Bram Smeets

June 23, 2005 @ 11:55 am

I have updated this blog entry to resemle the latest DWR release (including the spring creator by default).

Furthermore, I’ve added an example of both the servlet mapping in web.xml and the Spring MVC handler mapping.

Ian, I hope this answers your question?

Comment by Cristiane

June 23, 2005 @ 1:57 pm

Do you know why I’m getting this error when I start the server??? I’m using DWR 0.9.2b and Spring 1.2 RC2 version.

The bean ‘jcriteria’ that it’s complaining, is the javascript name … I don’t know how to solve it. Any idea??

My DWR.xml definition:

Log error:
[6/23/05 8:52:31:891 BRT] [Servlet.LOG]: dwrController: init
[6/23/05 8:52:32:062 BRT] 301f9491 SystemErr R [uk.ltd.getahead.dwr.impl.DefaultCreatorManager] [2005-06-23 08:52:32,062] [ERROR][Severity 2] Error loading class for creator ’spring’.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘jcriteria’ is defined: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans

Comment by Bram Smeets

June 23, 2005 @ 2:16 pm

First, I like to suggest posting these kinds of questions to the DWR user mailing list “users at dwr dot dev dot java dot net” and subscribing to it.

But to try to answer your question: I read a message on the DWR mailing list about the beanName being ignored in an earlier version of the SpringCreator. Also note the change I made to the syntax of defining the the <create> tag for a spring creator.

To solve the problem, I would first of all upgrade to Spring 1.2.1 instead of the RC version. Second, upgrade to the latest DWR release (Version 1.0RC1). This will probably solve your problem.

In case the problem persists, send a message to the mailing list or email me directly (bram at interface21 dot com).

Good luck!

Comment by Bavo

June 24, 2005 @ 3:48 pm

Thx, was useful to me

Comment by aniesh

August 4, 2005 @ 9:07 am

what does productmanger.js contain

Comment by Bram Smeets

August 4, 2005 @ 11:30 am

The productmanager.js content is generated by DWR. It contains the JavaScript that allows the convenient calling of methods on the exposed Spring-managed product manager.

Comment by aniesh

August 17, 2005 @ 1:17 pm

hai bram
how to prevent the access of “http://localhost:8080/appname/dwr”

Since this is a threat i need a good idea.

Thanks
anieshuk

Comment by Bram Smeets

August 17, 2005 @ 1:28 pm

First of all, you should disable the debug mode to disallow access to the debug pages.

But for the rest of the paths (javascripts and action paths), access to it can not be prevented (as far as I know), except by hiding them behind in a secure/restricted context. However, putting a securty constraint on the /appname/dwr path requires the using page to be in the same restricted context in order for it to work.

Comment by anieshuk

August 23, 2005 @ 8:08 am

Hai bram
Thanks for u r suggestion.When the debug mode is set to false it prevents the access.This is what i need.
Thanks
aniesh uk

Comment by Franklin Samir

October 22, 2005 @ 6:00 pm

Vry usefull example.

Just take care with he Javascript declarations:
… src=’/dwrPath/interface/productManager.js’>

You have two different kind of quotas. Make sure to use only ‘ rather than `.

Comment by Climbnus

October 28, 2005 @ 7:52 am

I have error: DWR can’t find a spring config.

I’m using spring 1.2.x, dwr 1.1 beta, jetty

Comment by Climbnus

October 28, 2005 @ 10:50 am

ok, its working.

Solution:
https://dwr.dev.java.net/servlets/ReadMsg?list=users&msgNo=1167

Pingback by Spring and DWR | theBaz.it

November 8, 2005 @ 10:35 am

[…] There is Spring a very good and clean integration between this two technologies as explained here by Bram Smeets one of Interface21 consultants. […]

Comment by Vincent Partington

November 11, 2005 @ 4:30 pm

Hi Bram,

I configured DWR 1.0 and Spring 1.2.4 according to the instructions on the DWR site and the ones here.

Apart from the DWR servlet being defined as a Spring WevMBC controller, I can’t see much of a difference. In both cases, I can only access beans from the application context container (e.g. applicationContext.xml) and not from the dispatcher servlet specific one (e.g. main-servlet.xml).

Did I miss something?

BTW, it would be sweet if DWR itself could be configured using Spring (so we could do away with dwr.xml) and if DWR used Spring’s conversion features. Any idea’s on that?

Regards, Vincent.

P.S. See you tonight at the Dutch Java Meetup. I’m all for free as in free beer. ;-)

Pingback by Just another DWR cup | theBaz.it

November 11, 2005 @ 6:53 pm

[…] In my previuos post “Spring and DWR” I talked about a solution I implemented using Spring Framework and Direct Web Remoting. Here I want to dig in my solution: focusing on communication model and form submission.Indeed I created a bean as suggested by Bram Smeets and DWR documentation and used it “ajaxing” interface. Permalink | Comment | Print | Trackback url […]

Comment by Marcelo R. Sosa

November 16, 2005 @ 10:09 pm

Thanks very much, from Argentina.

This solutions, its working, for me.

With Tomcat 5.5.12, Spring 1.2.3 and Hibernate 2.1.8

MRS

Comment by Ramesh

November 20, 2005 @ 9:13 am

Thanks very much but unfortunately i think i am making mistake in creating bean with id productManager

If you could explain on this my integratin will be successful

Comment by Bram Smeets

November 21, 2005 @ 10:46 am

Hi Ramesh,

You should expand a little more on the problem you are experiencing, otherwise I’m unable to help you.
What are the errors/problem and what is your configuration setup?

The best thing to get help on using DWR is subscribe to the DWR user (dwr-user) mailing list at java.dev.net
That way, the DWR community is able to help you solve your problem.

Greetings,
Bram

Comment by xuj

November 23, 2005 @ 5:48 am

Hi Bram

The tomcat server had some errors , I had think it long time,but I don’t konw why,can you help me?

ERROR - CommonsLoggingOutput.error(83) | Error loading class for creator ‘Spring Creator[ApplicationFormService]’.
java.lang.NullPointerException
at uk.ltd.getahead.dwr.create.SpringCreator.getInstance(SpringCreator.java:142)
at uk.ltd.getahead.dwr.create.SpringCreator.getType(SpringCreator.java:104)
at uk.ltd.getahead.dwr.impl.DefaultCreatorManager.addCreator(DefaultCreatorManager.java:146)
at uk.ltd.getahead.dwr.impl.DefaultCreatorManager.addCreator(DefaultCreatorManager.java:128)
at uk.ltd.getahead.dwr.impl.DefaultConfiguration.loadCreate(DefaultConfiguration.java:254)
at uk.ltd.getahead.dwr.impl.DefaultConfiguration.loadAllows(DefaultConfiguration.java:195)
at uk.ltd.getahead.dwr.impl.DefaultConfiguration.addConfig(DefaultConfiguration.java:89)
at uk.ltd.getahead.dwr.impl.DefaultConfiguration.addConfig(DefaultConfiguration.java:65)
at uk.ltd.getahead.dwr.DWRServlet.readFile(DWRServlet.java:214)
at uk.ltd.getahead.dwr.DWRServlet.init(DWRServlet.java:143)
at org.springframework.web.servlet.mvc.ServletWrappingController.afterPropertiesSet(ServletWrappingController.java:158)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:348)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:147)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:275)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:317)
at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:134)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:230)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:156)
at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:81)
at javax.servlet.GenericServlet.init(GenericServlet.java:211)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1029)
…..

Comment by Bram Smeets

November 23, 2005 @ 12:45 pm

I’m not quite sure what causes this error. You said Tomcat reports errors on startup.

Are you using the latest DWR release?
Did you define the ContextLoaderListener and is it started succesfully?

Again, it is better to post questions like these at the [dwr-user] mailing list at java.dev.net as there is a big community available to help you.

Greetings,
Bram

Comment by Scott

December 10, 2005 @ 12:31 am

Bram,

Great info in your blog. I want to pass my command object to a method call e.g.

How can this be done?

Thanks,
Scott

Comment by Scott

December 10, 2005 @ 1:07 am

Bram (or anyone who can answer),

This is a follow to my incomplete post before. Your original code fragmnet to call a method with no arguments is:

onclick=”productManager.getAllProducts(productCallback);”

I want to be able to call a method like this passing in the Command object on my form ( e.g. onclick=”productManager.getAllProducts(commandObject,productCallback);”

What do I need to do to make this work?

Thanks,
Scott

Comment by Bram Smeets

December 10, 2005 @ 4:57 am

The syntax you use is the correct one. You need to create and populate the commandObject as a JavaScript object and populate the fields.

The second thing you need to do is register a converter for the command object class (and any compound objects) with DWR using the convert tag.

If you have any more questions, post them to the DWR user mailing list, you’ll get a lot more (and quicker) response there ;-)

Trackback by Ajaxian

December 12, 2005 @ 4:48 pm

Spring and DWR integration

Dejan Bosanac recently posted about integrating Spring and with the Java ajax library DWR. His entry builds upon previous work done by Bram Smeets, and Bram actually comments on some possible improvements to Dejan’s setup. Bram is also working…

Comment by Akila

March 6, 2006 @ 8:07 pm

Will I be able to walk the object graph when I retrieve the object using DWR? For example, if the name of the product were of type FullName instead of string, can I do something like

product[i].name.firstname ?

Thanks
Akila

Comment by Bram Smeets

March 7, 2006 @ 1:13 pm

Yes.
DWR supports nested properties and will convert your FullName instance to a JavaScript representation of the object.

Comment by Slava Lovkiy

March 9, 2006 @ 10:33 pm

THere is DWRUtil.setValues(bean) function which populates DOM elements with id=”propertyName”. But I found that it doesn’t work for nested properties, say, ‘person.name’ or something like that. Are there any movements toward handling nested properties writing/reading with help of DWRUtil.getValues()/setValues()?

Comment by Bram Smeets

March 10, 2006 @ 11:37 pm

Actually I’m not sure.
Please ask your question on the DWR mailing list. See http://getahead.co.uk/dwr for more information on how to subscribe to the mailing list.

Comment by SC

March 13, 2006 @ 8:52 am

If I am passing the whole form as object, i.e. com.web.SubmitForm (Bean class) using Spring MVC and I would like to pass back this whole form using AJAX, so I tried onclick=”productManager.getAllProducts(_thisForm,productCallback);”
I have convert the SubmitForm to bean but I failed to pass back this whole form to my BusinessDelegate.
Any thinker that I can achieve this?

Comment by Bram Smeets

March 13, 2006 @ 9:33 am

I am not completely sure why this should not work. Your setup seems to be correct based on the information you provided.
Maybe you can give me some more details on the exact setup and the error you are getting.

Did you go to //dwr/ to view the debug pages. Just to make sure DWR is setup correctly.

You can contact me by email (bram at interface21.com) directly if you want to.
Bram

Comment by SC

March 15, 2006 @ 3:04 am

I am trying to pass the entire submit form back and I have convert the form i.e. com.web.SubmitForm in dwr.xml. I am just wondering if I am able to have the Spring binding that will post the objects binded back to the server through DWR.

Comment by Nuri

March 20, 2006 @ 11:43 am

when trying to use this library I have couple questions:
- SpringCreator in 1.1 still only picks up the application context beans and not the servlet env beans. Correct? So, I resolved the issue as descirbed by a Wrapper for the servlet.
- if my bean is to a bean who has an inner reference to another bean, how can I declare so that I can call the inner bean methods from javascript.
ex: userManager.testManager.getAllUsers()
Thanks,

Comment by Bram Smeets

March 20, 2006 @ 2:38 pm

1) This is correct, due to the fact that DWR initializes all created beans on startup we can not lookup the bean from the servlet context (as we have no request available to determine which context to use). I am not sure what you mean by “I have resolved…”.

2) That is currently not possible except for of course adding a method on the userManager which proxies to the actual method on the testManager. DWR can not remote inner classes directly from Spring beans. You could have a look at the ScriptCreator which might be able to do this for you. However, I’m not sure it will help you solve this.

Comment by johnhzjx

April 6, 2006 @ 8:51 am

hello,i have a problem about use href target to a frame,when i direct use url http://localhost:8080/project/a.jsp ,it’s ok,but when i use http://127.0.0.1:8080/project/a.jsp ,first the js alert(”no permission”),but refresh the page it’s ok..
now ,my web have two frame,one menu.jsp,one main.jsp,when i use <a href=”a.jsp” rel=”nofollow”> JS alert(”object error”);
the a.jsp all same code..

my email:johnhzjx at eyou.com

Comment by Bram Smeets

April 6, 2006 @ 4:25 pm

Hi John,

You should clarify your problem a little bit more, because I am not completly sure what the problem. is.

It appears that your having problems accessing different frames? I think normally you can only access frmae contents either from the same domain or opened by a certain frame.

Does this help?

Bram

Comment by johnhzjx

April 7, 2006 @ 2:34 am

I may discover the problem, I adjust to do a JS of tree with born dynamic state in page of use the DWR, possible of problem at the JS and DWR JSs that this dynamic state add to carry adjust the relation for use.
thank for you help~:)

Comment by johnhzjx

April 7, 2006 @ 10:01 am

The SPRING that I use now is to pass the DispatcherServlet to add to carry, if the BEAN method that the demand adjusts to use the SPRING in DWR BEAN, I should if install in the WEB.XML and DWR.XML?

public class DwrFolderListOpBean {
private ConfigFileAccessor configFileAccessor;
public void setconfigFileAccessor(ConfigFileAccessor
configFileAccessor) {
this.configFileAccessor = configFileAccessor;
}
public a(){
configFileAccessor.get();
}
}

The WEB.XML install

dnsMonDispatcher
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

WEB-INF/contexts/database-config.xml
WEB-INF/contexts/messages-viewresolver.xml
WEB-INF/contexts/exception-config.xml
WEB-INF/contexts/mapping-config.xml
WEB-INF/contexts/manage_namedconf.xml
WEB-INF/contexts/manage_namedhost.xml
WEB-INF/contexts/login.xml
WEB-INF/contexts/file_properties.xml
WEB-INF/contexts/buffalo_properties.xml

1

Comment by johnhzjx

April 7, 2006 @ 11:47 am

[17:45:13] [INFO ] [Converter ‘hibernate’ not loaded due to ClassNotFoundException. Thi
s is only an problem if you wanted to use it. Cause: Failed to find either org.hibernate.Hibernate or net.sf.hibernate.H
ibernate.]
[17:45:13] [ERROR] [DWR can’t find a spring config. See following info logs for soluti
ons]
[17:45:13] [INFO ] [- Option 1. In dwr.xml, add for each spring config file.]
[17:45:13] [INFO ] [- Option 2. Use a spring org.springframework.web.context.ContextLoa
derListener.]
[17:45:13] [INFO ] [- Option 3. Call SpringCreator.setOverrideBeanFactory() from your w
eb-app]
[17:45:13] [ERROR] [Error]
java.lang.InstantiationException: DWR can’t find a spring config. See the logs for solutions
at uk.ltd.getahead.dwr.create.SpringCreator.getInstance(SpringCreator.java:140)
at uk.ltd.getahead.dwr.create.SpringCreator.getType(SpringCreator.java:104)
at uk.ltd.getahead.dwr.impl.DefaultCreatorManager.addCreator(DefaultCreatorManager.java:146)
at uk.ltd.getahead.dwr.impl.DefaultCreatorManager.addCreator(DefaultCreatorManager.java:128)

folderListOpBean

Comment by Bram Smeets

April 10, 2006 @ 11:04 am

It appears that DWR can not find your Spring application context.
You should load the beans you want to remote using DWR using a ContextLoaderListener. In your web.xml you need to declare a ContextLoaderListener which loads the application contexts containing the beans you want to remote.

PS. The first INFO statement is just an info statement and can be ignored if not using the hibernate converter.

Comment by Ganesh Prasad

April 22, 2006 @ 5:47 pm

Bram,

Could you please make your example code available as a zip for download? I would like to study that in detail. (The bean definition for “defaultController” would be of particular interest, because I think I’m having some problems there.)

Thanks and regards,
Ganesh

Comment by Bram Smeets

April 23, 2006 @ 3:51 pm

Hi Ganesh,

I’ve posted the demo I did for The Spring Experience on my blog. Maybe you can have a look at that. You can download them here

If you need to have more information just let me know.

Greetings,
Bram

Comment by Ganesh Prasad

April 24, 2006 @ 6:30 am

Bram,

Thanks for putting up the zip file. I had a look at the web.xml and main-servlet.xml files. The web.xml is splitting traffic by URL, sending them to Spring’s dispatcher servlet or to the DWR servlet as the case may be.

I thought the idea was a bit different:
Send *all* requests for this application (”/myproj”) at the web container level to Spring’s dispatcher servlet (named “main”), then use main’s configuration file (”main-servlet.xml”) to load the application context. Within this application context, define a URL mapper that once again splits traffic between DWR requests (”/myproj/dwr/*”) and other default requests (”/myproj/*”) . The DWR requests go to a Spring ServletWrappingController, and the non-DWR requests go to some other Spring controller (e.g., The UrlFilenameViewController called “defaultController”). The ServletWrappingController in turn, delegates to the DWRServlet, but not before loading the “beans.xml” config file containing details of the beans. This way, by the time the DWRServlet reads the “dwr.xml” file and knows which beans are to be created by Spring, Spring knows all about them.

At least, that’s the way I understood the architecture as you described it, but I couldn’t get it to work. I kept getting “resource /myproj/dwr/ not found” kind of error pages.

In your zip, the web container itself sends DWR traffic directly to the DWRServlet without a Spring ServletWrappingController in between. So is this intermediary not required? Does Spring’s application context get loaded as a sort of side-effect?

Regards,
Ganesh

Comment by Bram Smeets

April 24, 2006 @ 12:38 pm

You are absolutely right.

The direct mapping to the DwrServlet is my preferred choice right now as a DwrController is not yet available. So I suggest taking the approach I took in my sample application.

The Spring application context is available by having the ContextLoaderListener defined in your web.xml. This will handle loading of the Spring application context. You just need to make sure that all the beans that need to be available to DWR are defined in this global application context (the configuration files loaded by the ContextLoaderListener) and *NOT* in hte ??-servlet.xml.

Greetings,
Bram

Comment by Robert Barr

April 24, 2006 @ 4:38 pm

The portal project that I’m working on would really benefit from some cool integration with DWR and Spring.

I’ve used the comments posted by Bram (props dude, helped a lot), but I need to take things to the next level.

The premise is that I want to be able to post back a form using DWR, invoke the correct Spring controller to render the JSP response and send the information back to the client.

So far all the examples I’ve seen of using DWR and Spring have been of invoking a server-side method that returns some simple text.
This is okay in the simple case, but I need to use tag libraries in a JSP page, so I need to invoke a Spring-MVC-style controller to manage the population of the request object to generate a groovily formatted response.

anyone tried anything like this?

Rob

Comment by Bram Smeets

April 24, 2006 @ 5:16 pm

Hi Rob,

You can use the following code to invoke a controller for rendering. The resulting String contains the HTML that was rendered as it would normally render when invloking the same page directly.

WebContext ctx = WebContextFactory.get();
String html = ctx.forwardToString("/myPage.html");

You can just return the HTML through DWR to the page and do whatever you want with it in the page.
Hope this will help. Of course you can contact me for more information.

Greetings,
Bram

Comment by Ganesh Prasad

April 25, 2006 @ 6:32 am

Bram,

Thanks, I got it working :-).

I think I understand now what you’ve done by splitting traffic by URL right in the web.xml. You’re managing the regular web page flow using Spring MVC by redirecting to Spring’s dispatcher servlet, and you’re using DWR only for AJAX/data stuff.

That’s a very clean separation.

I have a question, though: If the DWR beans (created by Spring) need to access session-scoped data over the course of a multi-page form managed by Spring MVC, how can they do so? What’s the cleanest way to hook these beans (which are strictly speaking DTOs rather than true domain objects) into the HTTP session?

Regards,
Ganesh

Comment by Bram Smeets

April 25, 2006 @ 10:21 am

You asked the right question ;-)

As of version 2.0 Spring provides the means to use scoping for your Spring managed beans. Out-of-the-box it provides request, session and application scope (where ofcourse the last is the default for singleton beans).

It takes a little to long to explain this feature right now. I’ll post a blog entry explaining it a little bit more in the next couple of days.

It is very simple to use, just know that you can.

Pingback by Peace Palace » Ajax — 新手上路 (using Appfuse 1.9)

May 2, 2006 @ 5:44 pm

[…] Appfuse 1.9 雖然支援 Ajax,不過可惜的是沒看到範例,也沒有 guideline 告訴你怎麼做。只好去看 DWR 的 doc,可惜 DWR Spring Integration 那個部份講得太模糊,還好有一篇介紹 Your first CUP of DWR,基本上我是 follow 這篇在做的,技巧上也沒有超出它的範圍,只是我以 Appfuse 為基礎來做會比較快設定好。如果你不是用 Appfuse,就請以該篇文章為主去操作。 […]

Comment by Egor

May 18, 2006 @ 10:48 am

Hi, the problem I’ve faced is the next, - when I’ve pointed to the file with my beans in dwr.xml, I’ve got an Unexpected for me! error…
Please help my with solving this error, 3rd day I can’t solve it myself.

12:43:56,190 FATAL [DWRServlet] init failed
java.lang.IllegalStateException: WebApplicationObjectSupport instance [org.springframework.web.servlet.mvc.ServletWrappingController@4589eb] does not run in a WebApplicationContext but i
n: org.springframework.context.support.ClassPathXmlApplicationContext: display name [org.springframework.context.support.ClassPathXmlApplicationContext;hashCode=5933694]; startup date [T
hu May 18 12:43:55 MSD 2006]; root of context hierarchy
at org.springframework.web.context.support.WebApplicationObjectSupport.getWebApplicationContext(WebApplicationObjectSupport.java:62)

Comment by Egor

May 18, 2006 @ 10:58 am

Can you mail me a sources please - the task which I’m trying to solve is very similar to described

Comment by Egor

May 18, 2006 @ 11:15 am

So, question in common is - why DWR task does trying to Create beans which were already created in my WebApp context?

Comment by Egor

May 18, 2006 @ 1:46 pm

I’m writing now my own
class SpringWebContextCreator extends AbstractCreator implements Creator

and the last the problem still need to be solved - how to get spring application context?

anyone faced with it?

Comment by Bram Smeets

June 19, 2006 @ 2:32 pm

Hi Egor,

Sorry for the late reply, but I’ve been very busy lately.

To answer your question: I would not go about writing my own creator implementation. The problems you encountered are known but have been solved in the latest version of DWR.
Hopefully version 2.0-M3 will be out soon. This release will contain the new DWR namespace support for Spring. This namespace support will make using DWR in conjunction with Spring much more easy. And more important to you, it will solve the issues you describe.

Hope this will help.
Bram

Comment by John Dundon

October 5, 2006 @ 6:10 pm

Hi,
I’m trying to send a Dto from a spring controller to the browser and then back again. ie my controller has 2 methods:
MyDto getMyDto() and
MyDto getMyDtoAgin(MyDto d)
My base Dto contains an array of id’s of type Object[] which seems to be causing a conversion error since there is no convertor for type Object. I wonder would anyone have encountered this problem before and perhaps have a tidy solution?

Thanks

Comment by John Dundon

October 7, 2006 @ 12:24 pm

Well I put some convenience methods for accessing the Object[] from the Dto and then put an include filter for these methods in dwr.xml which seemed to do the trick!

Comment by abhay

December 30, 2006 @ 1:05 am

I get a javscript alert “[Object Error]” when i load a jsp page.
I checked the console and i dont see any errors there. Do you know anything about this?

Thanks
Abhay

Pingback by Bram Smeets Blog » Blog Archive » Spring & DWR - Ajax made Easy

January 31, 2007 @ 10:55 am

[…] For more information on how DWR was configured to work with Spring in the past see one of my earlier posts on using DWR in conjunction with Spring (note that it is fairly […]

Comment by vishnu

February 2, 2007 @ 7:29 am

Hi,

i would like to know how to configure portlet, spring with dwr.

pls any one help me…….its very urgent….

Thank you

Comment by Chris Buckley

April 3, 2007 @ 2:08 am

I’m really sorry but, who wants to do this:

var text = ‘Products: ‘;
for(i = 0; i ‘;
text += products[i].name;

text += ‘ (’;
price= products[i].price;
text += price.currency;
text += ‘ ‘;
text += price.value;
text += ‘)’;
text += ‘’;
}
document.getElementById(’productlist’).innerHTML = text;

Is there a good templating framework i can use, I’ve had tons of problems working with the DOM directly and cross browser support [especially with complicated UI’s, for simple usage yeah this is okay, but….]. So I really like the DWR and the Spring integration, but I want some kind of templating or some UI js components, ie. a predefined template that I combine with the List returned by dwr.

Comment by Bram Smeets

April 4, 2007 @ 9:41 am

One of the frameworks I have been using is AjaxPages (http://ajax-pages.sourceforge.net/).
The idea is that you use JSP-like templates, which are downloaded and executed in the web browser. The template works on the Javascript data that you retrieve from the server. An added benefit is that the templates can be largely cached by the browser.

The last time I checked / used this framework it was stil in development and needed some more work, but that has been some time ago.
So maybe you can have a look at it.

Comment by John

May 11, 2007 @ 3:23 pm

hi i’m using verion 1.1.4 of DWR and integrating into spring following the main post above, all works well accessing the DWR test page but I can’t access my application. I do not have a default controller because I’m using has anyone come across the same issue or have a fix?

defaultController
dwrController

Comment by mb

August 8, 2007 @ 5:33 am

I’m seeing
java.lang.InstantiationException: java.lang.InstantiationException: DWR can’t find a sprin
g config. See the logs for solutions

one difference is I have :

But in web.xml :

contextConfigLocation
/WEB-INF/spring/**/*-context.xml

org.springframework.web.context.ContextLoaderListener

thnaks for any help

Comment by David

August 9, 2007 @ 12:48 am

MB,
The reason for this is by default spring beans are singletons. And by default singleton beans are instantiated automatically. Because of this the dwrcontroller is being instantiated before the context is ready and dwr is choking. One way to temporarily resolve this is to make sure dwrcontroller is not a singleton. I am experimenting with the lazy-init attribute but it does not appear to work with singletons.

Comment by saurav

August 22, 2007 @ 3:43 pm

Hi,

I just wanted to know uf the DWR is compatible with Spring tlds.
Like i have seen the JS fucntion being called.
So is DWR works in this scenario?.

Thanks and Regards,
Saurav

Comment by arie

August 30, 2007 @ 10:40 am

Hello bram and any body here…. Can you all help me… i get problem integrating spring and hibernate and dwr. i am using spring 1.2.9 and dwr 2.0. i want to configure dwr.xml so dwr can lookup the beans that has been defined in the …-servlet.xml(application context). using the configuration like

in my application context there are bean with id playManager. but it seems wont work. if i turn the creator into “new”, it seems work but i get error message

thank you…

Comment by Mo

October 15, 2007 @ 2:07 pm

Please correct the tags, for example:

“<” -> “<”

Pingback by Marcels blog » Blog Archive » A Simple Ajax enabled Spring & DWR example

December 28, 2007 @ 11:29 am

[…] More about spring configuration with dwr Posted in dwr, java, spring | […]

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>