TwitterFacebookGoogle PlusLinkedInRSS FeedEmail

Saturday, January 26, 2013

How to use AJAX in JSP

In this post, we will see how to use AJAX in JSP. Nowadays dynamic web pages are very popular in web, everyone want to create website using dynamic web pages. AJAX is a technique used for creating fast and dynamic web pages. AJAX allows us to update parts of a web page, without reloading the whole page.  AJAX is simple JavaScript script which work with XML Http request.

Example:

In this example we will create a JSP page that can fetch information from a database using AJAX.
Before proceeding further first create this table in your database which we will use in our example.
Name Branch Year Email id
abhi cse 2012 abc@gmail.com
alex ece 2011 alex@gmail.com
adam Mech 2012 adam@gmail.com

In this example we are using Oracle Database 10g Express Edition, so if you have some other database then you have to do some minor changes for connectivity with the database.

CREATE TABLE studentinfo
(name VARCHAR2(30),
 branch VARCHAR2(20),
 year VARCHAR2(20),
 email VARCHAR2(80) );

Create a home.jsp page: 

Examine this page carefully as this page contain javascript and ajax logic. 
<html>
<head>
<title>Jsp Page</title>
<script>
function showuser(str)
{
var xreq;
if(str=="")
{
document.getElementById("showtext").innerHTML="";
return;
}
if(window.XMLHttpRequest)
{
xreq=new XMLHttpRequest();
}
else
{
xreq=new ActiveXObject("Microsoft.XMLHTTP");
}
xreq.onreadystatechange=function ()
{
if( (xreq.readyState==4) && (xreq.status==200) )
{
document.getElementById("showtext").innerHTML 
                                   =xreq.responseText;

}
}
xreq.open("get","getuser.jsp?q="+str,"true");
xreq.send();

}
</script>
</head>
<body>
<form>
<select name="user" onchange="showuser(this.value)" >
<option value="">Select Student name....</option>
<option value="abhi">abhi</option>
<option value="alex">alex</option>
<option value="adam">adam</option>
</select>
</form>
<br />
<div id="showtext">The response will come here</div>
</body>
</html>

When a student is select from the drop down list javascript showuser( ) method will get fire and create an XMLHttpRequest object and create the function to be executed when the server response is ready, send the request off to a getuser.jsp page on the server. Notice that a parameter (st) is added to the URL. This parameter will be pass to getuser.jsp in request object.

Now lets see the getuser.jsp page

<%@page import="java.text.SimpleDateFormat"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*,java.sql.*,java.io.*" %>
<%@page import="javax.servlet.*" %>
<%@page import="javax.servlet.http.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsp Page</title>
</head>
<body>
<%! Connection con; %>
<%! Statement s; %>
<%! ResultSet rs; %>

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

try{

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

con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","password");

s=con.createStatement();

rs=s.executeQuery("select * from studentinfo where 
                       name='"+name+"'");

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

<div id="dtl_table"><table border='3' cellpadding='5' 
     cellspacing='2' width="400px">
<tr bgcolor="66FF00">
<th>Name</th>
<th>Branch</th>
<th>Year</th>
<th>Email id</th>
</tr>
<tr>
<% while(rs.next())
{ %>
<td><%= rs.getString(1) %></td>
<td><%= rs.getString(2) %></td>
<td><%= rs.getString(3) %></td>
<td><%= rs.getString(4) %></td>
<% } %>
</tr>
</table></div>
</body>
</html>

If everything works fine the home.jsp page will look something like this when you will select a student name from the drop-down list. Select other student name from the drop-down list, you will see the dynamic work of AJAX.

0 comments: