Monday, July 27, 2009

AJAX with jQuery and EasyWeb4J

All modern web applications use AJAX to communicate asynchronously with the web server. EasyWbe4J does not include any tag library for AJAX support. Instead it allows you to use any JavaScript library to communicate with your application and perform AJAX operations. One of the benefits of this approach to AJAX is that it allows the developers to use Unobtrusive JavaScript.

We'd be using jQuery along with EasyWeb4J to build a simple adder which adds two numbers on the server and provides the sum in the response. The completed application would look like this.


Download the complete source code for this application.

The primary difference between the response for a normal request and an AJAX request is that, the response for the AJAX response does not contain the layout components of the page. It would send only the content which needs to be updated in the browser by JavaScript.

Create a new EasyWeb4J Hibernate Project as described in the tutorial. Since we do not need a database for this demo, delete src/main/resources/repositories.properties from the newly created project.

The JavaScript

/src/main/webapp/js/script.js

The Layout File

src/main/webapp/WEB-INF/layouts/Application.jsp

It is important to notice how we pass the context's root path to our script which would use it to post the input to the "add" action. We create a global variable named "contextRoot" just before including our script. The script can use this variable to post the request to our action.

The Model

src/main/java/org/ajax/models/Adder.java

The Controller

src/main/java/org/ajax/controllers/HomeController.java

The add action in our controller renders its default view (add.jsp) without the layout using the renderWithoutLayout() method.

Home View

src/main/webapp/WEB-INF/views/Home/index.jsp

AJAX Response View

src/main/webapp/WEB-INF/views/Home/add.jsp

1 comments:

  1. Nice tip.. hoping to get it ported to wordpress somehow

    ReplyDelete