what is Ajax, Why use Ajax and How to implement in Java


Some use for Ajax interactions are following:

1. Real time form data validation
e.g. UserID, EmailID, Serial No, Postal Code etc.
2. Load on demand
e.g. fetch data in background, allowing browser load page quickly
3. Sophisticated user interface controls and effects
e.g. control such as calendar, trees, menus, data tables ,rich text editor.
4. Refreshing data and server path
e.g. such as scores, stock quotes, weather, or application specific data.
5. Partial submit
6. Page as an application
e.g. single page application that look and feels like desktop application.

XMLHttpRequest:

A JavaScript object, it allow client-side script to perform HTTP Request, and it will parse an xml server response. Ajax stands for asynchronous; when you send that HTTP request you don’t want the browser to hand around waiting for the server to respond. Instead, you want to continue reading to the user’s interaction with the page and deal with the server’s response when it eventually arrives. To accomplish this, you can register a callback function with the XMLHttpRequest and the dispatch the XMLHttpRequest asynchronously; control then return to the browser, but the callback function will be called when the server’s response arrives.

On the java web server, the request arrives just like any other HttpServletRequest. After parsing the request parameter, the Servlet invokes the necessary application logic serializes its response into xml and writes it to the HttpServletResponse.

Back on the client side, the callback function registered on the XMLHttpRequest is now invoked to process the xml document returns by the server.

Finally, the user interface is updated in response to the data from the server, Using JavaScript to manipulate the page’s HTML DOM.


XMLHttpRequest’s method:

Open(): set the stage for call to the server. The method argument can be GET, POST, or PUT. The url argument can be relative or absolute. This method includes three optional arguments.

Void open(String method, String url, Boolean asyn, String username, String password)

Send(): sends the request to the server

Void send(String content)

setRequestHeader(): set the specified header for supplied value. Open() method must be call before attempting to set any header.
Void setRequestHeader(“header”,”value”)
Properties:
Onreadystatechange : The event handler that fires at every state change, typically to a java script function.
readyState: the state of the request. The five possible values are
0 : uninitialized
1 : loading
2 : loaded
3 : Interactive
4 : Complete
responseText : The response form server as a String.
responseXML
status

Example:
Ajax.js
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * by Navindra K. Jha
 */
var xmlhttp=null;
function loadContentfromjsp()
{
    xmlhttp=getXMLHttpRequest();
    if(xmlhttp==null)
        {
            alert("Browser not support Ajax");
        }
        url="Result.jsp";
        xmlhttp.onreadystatechange=callback;
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.send("name=raj");
}
function loadContentfromservlet()
{
    xmlhttp=getXMLHttpRequest();
    if(xmlhttp==null)
        {
            alert("Browser not support Ajax");
        }
        url="hello"; // Servlet name in dd
        xmlhttp.onreadystatechange=callback;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
}
function callback()
{
   if(xmlhttp.readyState==4)
       {
           document.getElementById("result").innerHTML=xmlhttp.responseText;
       }
}
function getXMLHttpRequest()
{
    var xmlhttp;
    try{
        xmlhttp=new XMLHttpRequest();
    }catch(e)
    {
        try{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e){
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");  
        }
    }
    return xmlhttp;  
      
}

Index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="Ajax.js" language="javascript" ></script>
</head>
    <body>
        <h2>Hello World!</h2>
        <a href="javascript:loadContentfromjsp()">Content From Server Using Jsp</a><br/>
        <input type="button" onclick="loadContentfromservlet()" value="servlet"/>

        <div id="result"></div>
    </body>
</html>

result.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h2>Hello <%=request.getParameter("name")%>,Contents From GlashFish Server For Ajax</h2>
    </body>
</html>

Hello.java
package pack;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
          
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet hello</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet hello at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
          
        } finally {
            out.close();
        }
    }

  
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

}

No comments:

Post a Comment