Pages Navigation Menu

Coding is much easier than you think

Ajax implementation in Struts 2 without jQuery plugin

Ajax in Servlet without jQuery
 
AJAX is 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 transfer data with a web server, without reloading the page.
 
This post elaborates on how to implement Ajax in Struts 2 application.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Action class

 

package com.simplecode.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.Action;

public class AjaxAction implements Action 
{

   private String userName;
   private InputStream inputStream;
	
   public String ajaxMethod() 
   {
	System.out.println("ajaxMethod() is called");
	byte[] bArray;
		
	if(!userName.isEmpty())
	{
	bArray = ("Welcome " + userName).getBytes();
	inputStream = new ByteArrayInputStream(bArray);	
	}
	else
	{
	bArray = ("User name cant be blank").getBytes();
	inputStream = new ByteArrayInputStream(bArray);
	}
	
	return SUCCESS;
  }

  public String execute() 
  {
	return SUCCESS;
  }
	
  public String getUserName() 
  {
	return userName;
  }

  public void setUserName(String userName) 
  {
	this.userName = userName;
  }

  public InputStream getInputStream() 
  {
	return inputStream;
  }
}

 

Recommended reading:

 

Jsp Pages

 

<%@taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<title>Ajax implementation in Struts 2 </title>

<script type="text/javascript">

//Get XMLHTTP Object
function getXMLHTTPObject() 
{
var xmlhttpObject = null;
try 
{
 // For Old Microsoft Browsers
 xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP"); 
}
catch (e) 
{
	try 
	{
        // For Microsoft IE 6.0+
	xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP"); 
	}
	catch (e1) 
	{
        // No Browser accepts the XMLHTTP Object then false
	xmlhttpObject = false; 
	}
}

if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined') 
{
        //For Mozilla, Opera Browsers
	xmlhttpObject = new XMLHttpRequest(); 
}
        // Mandatory Statement returning the ajax object created
	return xmlhttpObject; 
}

	
// Change the value of the outputText field
function setAjaxOutput() 
{
document.getElementById('userNameDiv').innerHTML = xmlhttpObject.responseText;
}

function handleServerResponse() 
{
	if (xmlhttpObject.readyState == 4) 
	{
		if (xmlhttpObject.status == 200) 
		{
		setAjaxOutput();
		}
		else 
		{
		    alert("Error during AJAX call. Please try again");
		}
	}
}
	
// Implement business logic
function doAjaxCall() 
{
   xmlhttpObject = getXMLHTTPObject();
   if (xmlhttpObject != null) 
   {
   var URL = "myAjaxAction.action?userName=" + document.getElementById('userName').value;
   xmlhttpObject.open("POST", URL, true);
   xmlhttpObject.onreadystatechange = handleServerResponse;
   xmlhttpObject.send(null);
   }
}	
</script>
</head>

<body>
<h3>Ajax implementation in Struts2</h3>
<br/>
<div id="userNameDiv" style="color: red; font-weight: bold"></div>
<br/>
Please Enter your Name :
<s:textfield id="userName" theme="simple" name="userName" onblur="doAjaxCall();"/>
<br />
	
</body>
</html>

 

Also read:

 

Struts.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="default" extends="struts-default" namespace="/">
<action name="ajaxExample" class="com.simplecode.action.AjaxAction">
  <result>/ajax.jsp</result>
</action>
<action name="myAjaxAction" class="com.simplecode.action.AjaxAction" method="ajaxMethod">
  <result type="stream">
     <param name="contentType">text/html</param>
     <param name="inputName">inputStream</param>
  </result>
</action>
</package>
</struts>

 

Demo

 
On running the application
 
ajax in struts 2
 
Now giving the input as Jamil, the following output is obtained
 
ajax in struts 2 output
 
Here the struts 2 action is called onBlur() event automatically , and hence the above response is obtained in the webpage without refreshing the page.
 
download

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • kaviarasu

    Hi Mohaideen Jamil,

    Please help me to Configure Struts2 Application,I am new to this framework,I tried lot of times,it showing resource not available error Please Help me ASAP

  • Murugasen

    This page rocks. thanks