JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Get Best Tutorial on all major programing language

Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







AJAX with Struts

Struts-AJAX Integration Application


Example:-
  • In this example we are fetching no of employee statically on the fly with the help of AJAX.
index.jsp
  • Add JavaScript for performing the AJAX call to the CountAction and
    for updating the page's HTML.

  • Add a section of HTML inside a <div> tag that will be updated by the JavaScript.

  • Add an HTML button that invokes the JavaScript that makes the AJAX call
    and updates the page's HTML.

<html>
  <head>
     <script language="JavaScript">
  var request;
   
  function getCount() {
    var url = "/StrutsAJAXApplication/count.do";
   
    // Perform the AJAX request using a non-IE browser.
    if (window.XMLHttpRequest) {
      request = new XMLHttpRequest();
   
      // Register callback function that will be called when
      // the response is generated from the server.
      request.onreadystatechange = updateCount;
   
      try {
      request.open("POST", url, true);
      catch (e) {
         alert("Unable to connect to server to retrieve count.");
      }
   
      request.send(null);
    // Perform the AJAX request using an IE browser.
    else if (window.ActiveXObject) {
      request = new ActiveXObject("Microsoft.XMLHTTP");
   
      if (request) {
        // Register callback function that will be called when
        // the response is generated from the server.
        request.onreadystatechange = updateCount;
   
        request.open("GET", url, true);
        request.send();
      }
    }
  }
   
  // Callback function to update page with count retrieved from server.
  function updateCount() {
    if (request.readyState == 4) {
      if (request.status == 200) {
        var count = request.responseText;
   
        document.getElementById('employeeCount').innerHTML = count;
      else {
        alert("Unable to retrieve count from server.");
      }
    }
  }
</script>

  </head>

  <body>

    <H3>Struts-Ajax Application</H1>

    <form>
      <input type = "button" value = "Get Employee Count"
        onclick = "getCount();">
    </form>
    
    <div id="employeeCount">
      Employee Count Appear here on the fly
    </div>

  </body>
</html>


Employee.java
package mypack;

public class Employee {
  private String name;

  public Employee() {

  }

  public Employee(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

}

EmployeeAction.java
  • It instantiates the EmployeeCount service and retrieves the current employee count.
  •  The count is then written directly to the HTTP response so that it can be read by an AJAX call. 
  • Finally, null is returned to indicate to the Struts controller servlet
    that the response has been generated and no further processing is required.

package mypack;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class EmployeeAction extends Action{
  @Override
  public ActionForward execute(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    
    EmployeeCount service = new EmployeeCount();
     // Retrieve employee count.
      int employeeCount = service.getEmployeeCount();
     
      // Write employee count to HTTP response.
      PrintWriter out = response.getWriter();
      out.print(employeeCount);
     System.out.println("In Action Class..........");
      // Return null to inform the controller servlet
      // that the HTTP response has been handled.
      return null;
    }


    
  

}

EmployeeCount.java
  • It is a helper Class.
  • If EmployeeSearchService were a more sophisticated implementation that interfaced
    with a dynamic data source, 

  • The getEmployeeCount( ) method would make a query to obtain the count instead
    of returning the static count in the current implementation.

package mypack;

public class EmployeeCount {
  
  /* Hard-coded sample data. Normally this would come from a real data
    source such as a database. */

  private static Employee[] employees =
      {
        new Employee("Javed"),
        new Employee("Shankar"),
        new Employee("Subodh"),
        new Employee("Raj"),
        new Employee("Sagar"),
        new Employee("Sachin")
      };
    // Calculate count of employees.
    public int getEmployeeCount() {
      return employees.length;
    }


}


struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
    
    <action-mappings>
        
        <action path="/count"
            type="mypack.EmployeeAction">
    </action>
  
    </action-mappings>
    
  </struts-config>


web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
  <!DOCTYPE web-app PUBLIC
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <display-name>Struts-AJAX  Application</display-name>
  
  <!-- Standard Action Servlet Configuration -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
 </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>


Output:-
  • Run the index.jsp file.
  • The following page will appear.
  • Now click on the button "Get Employee Count".
  • Only the below part of the page will get refreshed not whole index.jsp on the fly.
  • Showing the no of empoloyees...





Download Zip code