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"%>



Ajax implementation in Struts 2 





Ajax implementation in Struts2



Please Enter your Name :

 

Also read:

 

Struts.xml

 







  /ajax.jsp


  
     text/html
     inputStream
  



 

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

2 Comments

  1. 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

  2. This page rocks. thanks

Leave a Comment

Your email address will not be published. Required fields are marked *