Using AJAX with JSP

jsf ajaxAsynchronous JavaScript and XML (AJAX) is a concept used to develop web-based applications.In the context of web applications currently under development, fast reloading of pages is one of the most important properties. A slow application will cost you users and search engine rank, because slow load times are one of the biggest factors in website bounce rate.

The main advantage of AJAX is that it avoids refreshing the entire page. In older form submissions, the entire page reloads and processes on the server. The time it takes depends on the user’s connection and your server’s speed. Using AJAX, the time to load is drastically reduced, which makes AJAX a popular framework for web developers. We will discuss few examples in detail so that you learn how to bring AJAX and JSP together.

Learn AJAX by taking an online class at Udemy.com

Understanding AJAX

The most important point to remember is that AJAX is not a complex programming language or package. In fact, it’s a JavaScript library used along with the XML HTTP request. AJAX facilitates responding to browser events and refreshes the web page by dynamically working on the underlying DOM tree structure. You can use AJAX together with JSP to counter the problem or reload the entire page even when the changes pertain to a limited set of controls on the web page. AJAX achieves this by exchanging smaller amounts of data with the web server in each request. It is important to remember that you are working with individual fields rather than the entire page when you are working with AJAX.

Understanding JSP

Java Server Pages (JSP) are used for server-side programming for web based applications. It is used for building static as well as dynamic web content. JSP is based on the servlet technology and uses data in different formats such as HTML, XML and WML. If your web page uses a lot of server side programming, then it becomes very processing intensive. As the dynamic content in the page increases, the response time for server side processing increases.

For example, if you are updating a control selected from a drop down in a form that has twenty fields, then the typical JSP processing would send all the twenty values to the server even if only one value has been changed. This is not required and makes the processing on the server side really slow. Integrating AJAX with JSP helps developers save on such dynamic updates, because the AJAX framework allows you to refresh only the effected portion of the webpage keeping the other content unaffected.

JSP is a server side technology that focuses on implementing the business logic whereas AJAX is a collection of scripting tools such as JavaScript, CSS, HTML and XML used for ensuring that dynamic updates happen fast on the client side. This is done by refreshing the page’s partially based on the response received from the web server. The integration of AJAX with JSP gives you an important tool to maximize the performance of your web applications without compromising on correctness or security of the data.

Using AJAX in JSP

Let us consider an example of creating a JSP page that will query the database using AJAX. Consider the standard employee table as follows –

s1
You should have this table created in the database along with some sample records.

This example is intended to demonstrate selecting the “designation” from a drop down value that will call the “getempdetails” method. This will create an instance of the XMLHttpRequest object that will send the request to the server side “empdetails.jsp” .

Let’s create a sample JSP page –

<html>

<head>

<title>Employee Detail</title>

<script>

function showFields(string1)

{

var xRequest1;

if(string1=="")

{

document.getElementById("Show_update").innerHTML="";

return;

}

if(window.XMLHttpRequest)

{

xRequest1=new XMLHttpRequest();

}

else

{

xRequest1=new ActiveXObject("Microsoft.XMLHTTP");

}

xRequest1.onreadystatechange=function ()

{

if((xRequest1.readyState==4) && (xRequest1.status==200))

{

document.getElementById("Show_update").innerHTML

=xRequest1.responseText;

}

}

xRequest1.open("get","empdetails.jsp?q="+string1,"true");

xRequest1.send();

}

</script>

</head>

<body>

<form>

<select name="user_name" onchange="getempdetails(this.value)" >

<option value="">Employee Designations</option>

<option value="Officer">Officer </option>

<option value="Supervisor">Supervisor </option>

<option value="Manager">Manager </option>

</select>

</form>

<br />

<div id="Show_update">To Update the designation...</div>

</body>

</html>

In this code snippet, an instance of the XMLHttpRequest object is created and sent to the server. The server processes the request and sends back the response as XML data to the client. On the client side, the fields are refreshed based on the XML reply.

The XMLHttpRequest object handles both synchronous and asynchronous requests initiated by the client. By default, it operates in the asynchronous mode which is a no blocking mode where other fields on the page can be updated while the server side processing is in progress. On the other hand if the synchronous mode is used then no other interaction on the page is possible unless the current processing completes.

Learn more about AJAX development by taking a course at Udemy.com

A sample empdetails.jsp page will look like –

<%@page import="java.text.SimpleDateFormat"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import="javax.servlet.*" %>

<%@page import="javax.servlet.http.*" %>

<%@page import="java.util.*,java.sql.*,java.io.*" %>

 

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Employee Portal</title>

</head>

<body>

<%!Connection con; %>

<%!Statement s; %>

<%!ResultSetrs; %>

<% String name=request.getParameter("st");

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

con1=DriverManager.getConnection

("jdbc:oracle:employee:@localhost:1521:XE","username","password");

s1=con1.createStatement();

rs1=s1.executeQuery("select * from employee where

id='"+empId+"'");

}catch(Exception e){ e.printStackTrace(); }

%>

<div id="dt_table"><table border='4' cellpadding='6'

cellspacing='3' width="300px">

<trbgcolor="66FF00">

<th>Empolyee ID</th>

<th>Empolyee Name</th>

<th>Employee Age</th>

<th>Employee Designation</th>

</tr>

<tr>

<% while(rs1.next())

{ %>

<td><%=rs1.getString(1)%></td>

<td><%=rs1.getString(2)%></td>

<td><%=rs1.getInt(5)%></td>

<td><%=rs1.getString(6)%></td>

<% } %>

</tr>

</table></div>

</body>

</html>

Learn AJAX from scratch by taking a course at Udemy.com

Conclusion

AJAX is very helpful when used along with server side programming. Using AJAX, the web page on the client side will be refreshed only for the fields that are updated and the response time for the client will be very fast. As AJAX and JSP are both platform independent, the behavior will be identical across all platforms. In the examples here we have considered JSP, but AJAX can be integrated as easily with PHP or .Net based applications too.