Sei sulla pagina 1di 47

AJAX, DWR and Spring

Bram Smeets Interface21

Topics
History of dynamic web applications Web 2.0 and AJAX The DWR approach to AJAX Using Spring & DWR (by example) Best practices Tools and widgets DWR roadmap Conclusion

History of dynamic web applications

Web 2.0
The term "Web 2.0" refers to development of the World Wide Web, including its architecture and its applications. As used by its proponents, the phrase currently refers to one or more of the below : a transition of websites from isolated information silos to sources of content and functionality, thus becoming a computing platform serving web applications to end users a social phenomenon referring to an approach to creating and distributing Web content itself, characterised by open communication, decentralization of authority, freedom to share and reuse, and "the market as a conversation" a more organized and categorized content, with a more developed deeplinking web architecture. a shift in economic value of the web, potentially equalling that of the dot com boom of the late 1990s However, a consensus upon its exact meaning has not yet been reached. Skeptics argue that the term is essentially meaningless, or that it means whatever its proponents decide that they want it to mean in order to convince the media and investors that they are creating something fundamentally new, rather than continuing to develop and use well-established technologies. Many recently developed concepts and technologies are seen as contributing to Web 2.0, including weblogs, wikis, podcasts, rss feeds and other forms of many to many publishing; social software, web APIs, web standards, online web services, AJAX, and others.

Wikipedia, November 29, 2005

Web 2.0 (continued)


the Web 2.0 seems carefully crafted as a way to denegrate the clueless "Web 1.0" idiots, poor children, in the same way the first round of teenagers starting dotcoms in 1999 dissed their elders with the decade's mantra, "They just don't get it!" I'll do my part. I hereby pledge never again to use the term "Web 2.0" on this blog Joel Spolsky, October 21, 2005

What is AJAX?

AJAX The Hype

March 16, 2005

AJAX Example
Google Suggest

AJAX
Not one technology, several technologies
XHTML and CSS Document Object Model (DOM) XML (and XSLT) XMLHttpRequest (XHR) JavaScript

Asynchronous JavaScript And Xml


Jesse James Garrett, 2005

AJAX = DHTML + XHR

AJAX Architecture (1)


Classic MVC vs. AJAX

Jesse James Garrett, 2005

AJAX Architecture (2)


Classic MVC vs. AJAX

Jesse James Garrett, 2005

AJAX - Issues
Browser incompatibilities
ActiveX in IE Native in Mozilla/Firefox

Back button and browser history Working with XML in JavaScript Accessibility

AJAX Framework overview


JSON-RPC Sajax DWR Many more Why DWR?
Mostly used framework (according to Google and Burton Group) Integrates best with Spring!

DWR Architecture (1)

DWR Architecture (2)


Java to JavaScript marshalling (and vice versa)
Uses JavaScript objects

Facilitate browser incompatibilities


Supports most browsers Even allows fallback to iframes

DWR Configuration (1)


Declare DWRServlet in web.xml
<servlet> <servlet-name>dwr</servlet-name> <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>

DWR Configuration (2)

Add dwr.xml in /WEB-INF


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.1//EN" "http://www.getahead.ltd.uk/dwr/dwr11.dtd"> <dwr> <allow> <create creator="new" javascript="AjaxFacade"> <param name="class" value=com.interface21.dwr.AjaxFacade"/> </create> </allow> </dwr>

AJAX Debug pages


Set the init-param of the DWRServlet to true

DWR A sample web page


In your web page add:
<script type="text/javascript" src="/dwr/interface/AjaxHelper.js"></script> <script type="text/javascript" src="/dwr/engine.js"></script>

Call methods on the exposed object


<script type=text/javascript> function getData() { AjaxHelper.getData(handleData); } function handleData(data) { alert(data: + data); } </script>

DWR Creators (1)


Creates Java objects to call Most needed creators are build-in
new scripted spring

Allows scoping of created objects


Page Request Session Application

DWR Creators (2)


Servlet Container Creator

getInstance(AjaxHelper)

AjaxHelper.getData()

DWR Handler

< creates >

getData()

Ajax Helper

DWR Creators (3)

Using the new creator


<create creator="new" javascript="AjaxHelper" scope="session"> <param name="class" value="com...AjaxHelper"/> </create>

Using the spring creator


<create creator="spring" javascript="AjaxHelper"> <param name="beanName" value=ajaxHelper"/> </create>

DWR Custom creators Implement custom creator...


public interface Creator { void setProperties(Map params) throws IllegalArgumentException; Class getType(); Object getInstance() throws InstantiationException; String getScope(); }

Declare the Creator implementation


<init> <creator id=mine" class=com.interface21.dwr.create.MyCreator"/> </init>

DWR Converters (1)


Converts Java objects to JavaScript objects
and vice versa

var customer = new Object(); customer.firstName = Joe; customer.address.street = Collins Avenue; .

Customer customer = new Customer(); customer.setFirstName(Joe); Address address = new Address(); address.setStreet( Collins Avenue); customer.setAddress(address); .

DWR Converters (2)


Many build-in converters
Primitives Collections JavaBeans (supports compound objects) Many more

Declare converters for domain objects


<convert converter=bean match=com.interface21.dwr.data.Customer/>

DWR Custom converters


Implement custom converter...
public interface Converter { void setConverterManager(ConverterManager config); Object convertInbound(Class paramType, InboundVariable data, InboundContext inctx) throws ConversionException; OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws ConversionException; }

Declare the Converter implementation


<init> <converter id=mine" class=com.interface21.dwr. MyConverter"/> </init>

Security
All methods on exposed objects are exposed by default
Use include/exclude rules per method

Only objects are marshaled for which a converter is registered Role restrictions
Use security constraints on DWR paths Specify an auth constraint per creator (JAAS) Use Spring Security interceptors

Disable debug mode in live environment!!

DWR Utilities
Include the utility script
<script type="text/javascript" src="/dwr/util.js"></script>

Among others, it offers:


$(id) Works on most browsers DWRUtil.toDescriptiveString(val) Generic toString() method DWRUtil.useLoadingMessage() DWRUtil.setValue(element, val) DWRUtil.getValue(element) DWRUtil.addOptions(list) DWRUtil.removeAllOptions(element) DWRUtil.addRows(element, data, ) DWRUtil.removeAllRows(element);

Demo
DWR

DWR & Spring

DWR = AJAX with Spring made easy! Expose Spring-managed beans by means of JavaScript

DWR & Spring Option 1


Define a ContextLoaderListener in web.xml to load the beans to expose
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>

Add a create statement to dwr.xml


<create creator="spring" javascript="CustomerManager"> <param name="beanName" value="customerManager"/> </create>

DWR & Spring Option 2


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

Pros Reuse Spring MVC services (LocaleResolver, etcetera) No need to define a ContextLoaderListener Cons Need to use Spring MVC

DWR & Spring Option 3


Have DWR load the application context(s)
<create creator="spring" javascript="CustomerManager"> <param name="beanName" value="customerManager"/> <param name="location-1" value="persistence-tier.xml"/> <param name="location-2" value="business-tier.xml"/> </create>

Pros
No need for ContextLoaderListener or Spring MVC

Cons
Creates an application context for each creator
Use SpringCreator.setOverrideBeanFactory(BeanFactory) to create global application context for all spring creators

Demo
DWR & Spring

DWR Advanced features (1)


Batching beginBatch(); Make some DWR requests endBatch(); Signatures Explicitly specify method signatures
<signatures> <![CDATA[ import java.util.List; import com.interface21.dwr.data.Customer; CustomerManager.batchUpdate(List<Customer> list); ]]> </signatures>

DWR Advanced features (2)


Accessing servlet parameters
Use WebContext
WebContext ctx = WebContextFactory.get(); ctx.getHttpServletRequest(); ctx.getHttpServletResponse(); ctx.getServletContext(); ...

Or add them to the method signature on your exposed beans


Auto filled in by DWR
List getCustomer(HttpServletRequest request, Long id);

DWR Advanced features (3)

GMail style loading messages


DWRUtil.useLoadingMessage(); DWRUtil.useLoadingMessage(Waiting); Customize even further:
$('disabledZone').style.color = white;

DWR Advanced features (4)


Other options
Globally: DWREngine.setX() Per call: { timeout: 500, callback: myCallback }

timeout errorHandler/warningHandler preHook/postHook method (DWREngine.XMLHttpRequest or DWREngine.IFrame) verb (GET or POST)

Best practices (1)

Avoid overuse
Use when appropriate

Single Page vs. Multi Page

Best practices (2)


Reuse of domain objects
Hibernate lazy-loading issues

Special facades or service objects No HTML over the wire

Tools

Venkman Selenium Log4js

Widgets
DOJO Prototype Script.aculo.us And many, many others

DWR Roadmap (1)


AJAX Filters, transparently filter requests
Latency filter (simulate actual latency with connection)

Reverse AJAX
Send JavaScript to the browser

Back button support

DWR Roadmap (2)


Tighter integration with Spring
No more dwr.xml but ordinary Spring XML DWR controller (instead of DWR Servlet) Extra form controllers e.g. for validation Use Spring scoping

What feature(s) would you like?

Demo
Spring integration

Conclusion
AJAX improves the user experience Avoid overuse DWR provides easy AJAX DWR integrates nicely with Spring Still more to come

Questions?

Potrebbero piacerti anche