S U N D A R R A J A N

Google Search Engine

Thursday, September 27, 2007

Ajax Implementation in spring framework

Ajax Implementation in spring framework

Spring framework doesn’t support Ajax directly we need to use XT or DWR framework to have Ajax in spring application. Recently I have used XT framework to make Ajax work in my spring web application. Let share my ideas and experience to you all. Of course, your ideas and feedbacks are welcome to improve my technical skills. Find below the detailed step by step procedure for this.

Before getting into Ajax with spring framework, let me first explain what Ajax is and how it became more popular.

What is Ajax?

1. AJAX stands for Asynchronous JavaScript And XML.

2. It’s a type of programming made popular in 2005 by Google (with Google Suggest).

3. It’s not a new programming language, but a new way to use existing standards.

4. With AJAX you can create better, faster, and more user-friendly web applications.

5. AJAX is based on JavaScript and HTTP requests.

Introduction:

AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly. AJAX is a browser technology independent of web server software.

AJAX is Based on Web Standards

AJAX is based on the following web standards:

  • JavaScript
  • XML
  • HTML
  • CSS

The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.

AJAX is about Better Internet Applications

Web applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop.

However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications. With AJAX, Internet applications can be made richer and more user-friendly.

AJAX Uses HTTP Requests

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, and then a new page will load with the results.

Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object

With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

The XMLHttpRequest Object

By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded!

AJAX was made popular in 2005 by Google (with Google Suggest).

Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.

The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.

Now let’s see about Ajax XT Frame work.

The XT Framework is a Spring module for developing applications with ''richer domain models and richer user interfaces'', following the Domain Driven Design practices.

Domain Driven Design puts the domain model in the heart of the development process. The domain model becomes the core of your application and the main focus of your development. It concentrates all business logic, rules and constraints, being totally independent from other application parts. In particular, considering a well-known layered architecture, domain models are designed to be independent from the so called presentation layer and infrastructure/data access layer. Unfortunately, practically speaking, this causes a sort of impedance mismatch among layers, causing code duplication, domain model corruption, or the shy anemic domain model.

The XT Framework aims at solving this mismatch providing the so called XT Modeling Framework for developing rich domain models, which gracefully adapt to other layers.

And if you have a rich domain model, why not having a rich user interface? The XT Framework provides also the XT Ajax Framework, which integrates Spring and its MVC framework with AJAX technologies.

Points to be noted:

1. The XT Framework needs Java 1.5 or later: it will not work in older environments.

2. Version 0.6 comes with several packages and interfaces whose name and position have been refactored for better usability. These changes are not backward compatible and require changing your code.

3. In version 0.6, the XT Framework Utils packages have been moved to the SpringMVC-extra web module.

Sample application:

Ajax is mainly meant for fetching data or adding dynamic changes in our application without submitting the page. In order to do this, we need to generate XMLHTTPRequest instead or HTTPRequest. Our page should not go to controller, before going in to controller we need to catch it and pass it to a handler using Interceptor concept in spring framework. For example if we want to catch the HTTPRequest before going to logincontroller we have to do something like this.

<bean id="publicUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >

<property name="interceptors">

<list>

<ref bean="ajaxInterceptor"/>

list>

property>

<property name="mappings">

<props>

<prop key="**/login.htm">loginControllerprop>

<bean id="ajaxInterceptor" class="org.springmodules.xt.ajax.AjaxInterceptor">

<property name="handlerMappings">

<props>

ajaxLoginActionHandler

props>

property>

bean>

Point your class to ajaxLoginActionHandler.

And in the AjaxLoginActionHandler we need to build dynamic content.

For example:

Public class AjaxLoginActionHandler extends AbstractAjaxHandler {

Public AjaxResponse validateLogin(AjaxActionEvent event) {

// building ajax response to send it back

AjaxResponse response = new AjaxResponseImpl();

// Inside this we can show or hide div tags in our JSP page

// Show elements inside div tag, here “exportToExcel” should be a

// div tag id

ShowElementAction showAction = new ShowElementAction("exportToExcel");

response.addAction(showAction);

// Hide elements inside div tag, here “exportToExcel” should be a div tag id

HideElementAction hideElementAction = new HideElementAction("exportToExcel");

response.addAction(hideElementAction);

// To build a dynamic table

// Create a table

Table table = new Table();

String[] headers = { "heading1", "heading2" };

// Create header for table

TableHeader header = new TableHeader(headers);

// add header to table

table.setTableHeader(header);

// in table we have addAttribute() method which is used to attribute for the // table for example, here we are adding header attribute and table // attributes.

table.addTableHeaderAttribute("class", "fixedHeader");

table.addAttribute("id", "normalTableNostripe");

// Table header has been added, now we need to create a row and column for // the table

TableRow row1 = new TableRow();

// Same as table object, TableRow object also have addAttribute() method // which is again used to set attribute for that particular row.

row.addAttribute("class", "normalRow");

// creating column for those tables

TableData column1 = new TableData(new SimpleText(“Test data”));

// adding column to row

row.addTableData(column1);

// finally add tableData (column) to table

table.addTableRow(row1);

// Then we need to decide whether the table which we created needs to append // with any content or replace existing content

// To append content, here “report” should be a div tag in our JSP

AppendContentAction appendContentAction = new AppendContentAction("report", table);

response.addAction(appendContentAction);

// to replace content, here “report” should be a div id in our JSP

ReplaceContentAction action = new ReplaceContentAction("report", table);

response.addAction(action);

// returning response to jsp page

return response;

}

}

Now comes our JSP part.

In Jsp we need to have some javascripts, this will create a XMLHTTPRequest and send it to handler.

We need to have this div tag in our jsp page so that dynamically created table will be appended or replaced here.

<div id="report" style="overflow: auto; height: 350px;"> div>

Content inside this div tag is hidden and showed using show and hide elements method

<div align="right" id="exportToExcel" style="display: none;">

<b> <a href="#" name="excel" onclick="javascript:exportToExcel();" target="_self"> Export to Excel a> b>

This how we are going to invoke ajax once a button is clicked

<input type="button" value="Filter" onclick="XT.doAjaxAction('validateLogin', this)">

Here this validateLogin is a method name which we used in the handler. Just by invoking this java script it will call that method inside the handler.

Find below the sites which I referred and downloaded javascript & jar files, Hope it will be useful for you also.

http://springxt.sourceforge.net/index.php/Main_Page

https://springmodules.dev.java.net/

https://springmodules.dev.java.net/servlets/ProjectDocumentList?folderID=7051&expandFolder=7051&folderID=7051

Still lot to go and lot to learn in this…. Will keep you posted J J

Keep watching…………… J J J

Is this bolg useful?

Rate

S U N D A R R A J A N

Followers