Sunday, March 28, 2010

Using Ajax with Struts

In this post we will go through the easiest way to add Ajax support in struts application, this means using the Action class not Servlet in the Ajax URL..

We will go through adding Ajax support to check on the uniqueness of login-name (i.e. availability for the user to register using the name) , we will do the following simple steps to achieve this:

1. Create the Java Script method that call our action class:
//this is the request object
var request= null ;
//this is the function that will be called to submit our request, it is generic function that accept URL and value and param so it can be used by different components:

function isUniqueName(url,value,param){
if(value==null || value==""){
alert("Please Enter Valid "+param+"!");
return false;
request.onreadystatechange = handleRequest;"POST",url+value,true);
request.send("<?XML version=\"1.0\" encoding=\"UTF-8\"?>");
//This function to create our request object for different browsers
function createXmlHttpRequest(){
request = new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest){
request = new XMLHttpRequest();
//this is the function that handle the response and update the UI, it assume there will be div named "Output" to recieve the outcome of the http request made:
function handleRequest(){
if(request.readyState == 4 && request.status == 200){
if(value == null){
value = request.responseXML;
document.getElementById("output").innerHTML = value;

2.Import Java script file in the html page:

<script language="JavaScript" src="/..../ajax_check_name.js">

-This is the name of our java script file.

3.Add html components that will use these functions:

//login field:

Login Name <html:text property="loginName" maxlength="16" style="width:250pt" onblur="isUniqueName('/..../',this.value,'loginName');"/>

//check button
<img src="/..../images/question.jpg" alt="Check Availability?" onclick="isUniqueName('/.../',document.forms[0].loginName.value,'loginName');" style="cursor:pointer">

//output div
<div id="output"></div>

- As you can see we call the Ajax function 2 times one on leave the text field and another one when click on check ourselves.

4.In Action Class:

String stepId=request.getParameter(IActions.STEP_ID);

String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.write("< src='/.../images/not_available.jpg' />");return null;
out.write("< src='/..../images/available.jpg' />");return null;

- Of course the logic here , if login name already exist , show not available image to the user, otherwise it is available to use it.

- You should notice the null return here , is to by-pass struts forwards return from the mapping files, this behave as if you are using Servlet directly.

* The Output will looks like :
Name already exist.
Name available for use.

No comments:

Post a Comment