Saturday, May 30, 2009

Ajax and JSON example, How to use JSON with Ajax

In my previous post, I had explained easy example of JSON. In this post I am explaining how to use JSON with Ajax.
No need to require any other software, just create one dynamic web project and paste below code.

1. StudentInfo.java (This is a Servlet)

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

public class StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
out.println(getResult(roll));
}

public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
String[] subjects = new String[]{};
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
subjects= new String[]{"C++","JAVA","DataBase"};
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
subjects= new String[]{"C++","QT","Linux"}; }
else{ name = "Roll Number not found"; }

String result = "var student={"; result += "name:'" + name + "', ";
result += "hostel:'" + hostel + "', ";
result += "contact:'" +contact +"',";
result += "subject:[";
for(int i=0;i<subjects.length;i++){
if(i == subjects.length - 1){
result += "'"+subjects[i] + "']";
}
else{
result += "'"+subjects[i] +"',";
}
}
result += "};";
return result;

}
}

2. ShowStudentInfo.jsp

<html><head><
title>Binod Java Solution AJAX </title>
<script type="text/javascript">
var request; f
unction getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/Ajax_JSON/StudentInfo?roll="+roll;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send();
}

function showResult(){
if(request.readyState == 4){
var response = request.responseText;
eval(response);
document.getElementById("NamelH1").innerHTML = student.name; document.getElementById("HostelH1").innerHTML = student.hostel; document.getElementById("ContactH1").innerHTML = student.contact; document.getElementById("SubjectH1").innerHTML = student.subject; } }

</script>
</head><body>
<h2> GET STUDENT INFO </h2>
<br> Enter Roll Number <input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();"/> <br>
<table border=2>
<tr><td>Name</td><td><span id="NamelH1">
</span></td></tr> <tr><td>Hostel</td>
<td><span id="HostelH1"></span></td></tr> <tr><td>Contact</td><td><span id="ContactH1">
</span></td></tr> <tr><td>Subject</td>
<td><span id="SubjectH1"></span></td></tr>
</table>
</body>
</html>

After compile and start the server, open internet explorer and put URL (like http://localhost:8080/Ajax_JSON/ShowStudentInfo.jsp) and put roll no. 110

This is very basic and fundamental tutorial, you can build a good project on Ajax and JSON with the help of this easy example.

Please dont forget put your comment to enhance this blog. :)

How to get client and server side IP address in JSP Page

Please visit my another blog

http://binodjava.blogspot.com/2009/06/how-to-get-client-and-server-ip-address.html

Thanks,
Binod Suman

Thursday, May 28, 2009

Get Current Server Time on Client JSP Page using Ajax

Using AJAX, you can show the server current time on client page. Time would be update on every second. Even you can set the interval of fetching time from server.

For example I am showing one jsp page and servlet.
To use this tutorial, no need to download any jar file or extra files.
Just make one dynamic web project and use this jps and servlet file.

1. ShowServerTime.jsp

<html>
<head>
<title>Binod Java Solution AJAX </title>

<script type="text/javascript">
var request;
function init(){
window.setInterval("getTime()",1000);
}
function getTime(){
var url = "http://localhost:8080/ServerTime/GetServerTime";
if(window.ActiveXObject){
request = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}
request.onreadystatechange = showTime;
request.open("POST",url,true);
request.send();
}

function showTime(){

if(request.readyState == 4){
var response = request.responseText;
document.getElementById("TimeH1").innerHTML = response;
}

}


</script>

</head>
<body onload="init();">
<h1> Server Time :: </h1> <h1 id="TimeH1"/>

</body>
</html>


2. GetServerTime.java (This is a servlet file)

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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

public class GetServerTime extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print(new Date());
}
}

How to compare two images, check two image are same or not

Please visit my this blog
http://binodjava.blogspot.com/2009/06/how-to-compare-two-images-check-two.html

Thanks,
Binod Suman

Wednesday, May 27, 2009

How to setup JNDI for Postgres SQL Database in RAD (Rational Application Development)

How to setup JNDI in RAD (Rational Application Development)

1. Start the server

2. Run Administrative console

3. Resource -> JDBC Provider -> Select the database type (User-defined) -> Select the provider type (User-defined JDBC Provider) -> Select the implementation type (User-defined)

4. Name : jndipostgresql

5. Class path: c:\jar\postgresql-8.1dev-403.jdbc2ee.jar

6. Native library path : c:\jar\postgresql-8.1dev-403.jdbc2ee.jar

7. Implementation class name : org.postgresql.jdbc2.optional.ConnectionPoolApply

8. Click on Data sources, New-> dspostgresql JNDI name : jndipostgresql

9. Click on "Select a data source helper class" Apply

10. Click on J2EE Connector Architecture(J2C) authenticaiton data entries, New -> Alias -> postgresqluser User ID -> postgres Password -> sumanApply -> save -> Save
Again go to datasource (dspostgresql), component-managed authentication alias -> postgresqluser (2 places) Apply -> Save

11. Click on Custom properties, New -> Name -> databaseName value -> postgresapply -> Save

12. Click on Test Connection, you will get successful if every thing fine.

Sunday, May 24, 2009

JSON an easy example, get start with JSON, how to use JSON

JSON : JavaScript Ojbect Notation.

It contains name/value pairs, array and other object for passing aroung ojbect in java script. It is subset of JavaScript and can be used as object in javascript.

You can use JSON to store name/value pair and array of ojbect.

It has eval() method to assign value to variable.
In below example, I have put all things together.
Just make one html file and you can start your practice on it.

How to use this tutorial:
1. Make one file JSONDemo.html
2. And paste below code

<html>
<head>
<body>
<script language="javascript">
eval("var amount =10;");
alert("Value of amount :: "+amount);

var student = {
name : "Binod",
roll : 110,
subject : ["Java","Database","Networking"]

}
alert("Student Name :: "+student.name);
alert("Student All Subject :: "+student.subject);
alert("Student First Subject :: "+student.subject[0]);
alert("Student No. of Subject :: "+student.subject.length);

for(var i=0;i<student.subject.length;i++){
var value = student.subject[i];
alert(value);
}

var person = {
name : "Ambani",
books : [
{
title : "Java Programming",
author : "Binod Suman"
},
{
title : "XML",
author : "Don Box"
}
]

}

alert("Book Title :: "+person.books[0].title);
alert("Book Author :: "+person.books[0].author);


</script>

Please put your comment on this post for enhance this blog or this tutorial.

Thanks and have a nice day ............ :)

Monday, May 18, 2009

Parse XML file in JavaScript part 2

As one of reader asked about how to handle XML respone if we get more than records or if your XML file have many child nodes.
I gave here one complete example with XML file and JavaScript in JSP.

1. abc.xml

<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>

<Student> <Name>Pramod Kumar Modi</Name>
<Hostel>Godawari</Hostel>
<Contact>88888888</Contact>
</Student>

<Student>
<Name>Sanjay Kumar</Name>
<Hostel>Satjal</Hostel>
<Contact>7777777</Contact>
</Student>

<Student>
<Name>Mukesh Ambani</Name>
<Hostel>Rewti</Hostel>
<Contact>6666666</Contact>
</Student>

</Students>

2. StudentInfo.jsp

<html><head><title>Binod Java Solution AJAX </title>
<script type="text/javascript">

function showResult(){

var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false"; xmlDoc.load("abc.xml");
var students=xmlDoc.documentElement;
var student = students.childNodes(0);
var rows = students.childNodes.length; v
ar cols = student.childNodes.length;

var body = document.getElementsByTagName("body")[0];
//var tabl = document.createElement("table");
var tabl = document.getElementById("studentinfo");
var tblBody = document.createElement("tbody");

for (var i = 0; i < rows; i++) {
var row = document.createElement("tr");
student = students.childNodes(i);

for (var j = 0; j < cols; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode(student.childNodes(j).firstChild.text); cell.appendChild(cellText);
row.appendChild(cell);
}

tblBody.appendChild(row);
tabl.appendChild(tblBody);
tabl.setAttribute("border", "2");
}

</script>

</head><body onload="showResult()">
<h2> GET STUDENT INFO </h2><br>

<table id="studentinfo"> <tr bgcolor='red'> <td >Name</td><td>Hostel</td><td>Contact</td> </tr> </table>
</body>
</html>

Now your html table will grow dynamically as per number of records in XML file.

Saturday, May 9, 2009

Get start with Ajax, Ajax simple example with Servlet, Ajax programming with Servlet

I am writing here a very simple ajax program. That will take roll number from jsp page, hit serlvlet, come back with result as XML, parse in javascript and will show on jsp page.

1. ShowStudentInfo.jsp

<html><head>
<title>Binod Java Solution AJAX </title>
<script type="text/javascript">
var request; function getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/blog_demo/StudentInfo?roll="+roll;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send();
}
function showResult(){
if(request.readyState == 4){
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
var student = students[0];
document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].text;
}
}
</script>
</head>
<body><h2> GET STUDENT INFO </h2>
<br> Enter Roll Number <input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();"/>
<br> Name : <span id="NamelH1"></span> <br
> Hostel : <span id="HostelH1"></span> <br
> Contact : <span id="ContactH1"></span> <br>
</body>
</html>

2. Servlet java file StudentInfo.java

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

public class StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public StudentInfo() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("**** STUDENT INFO ****");
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
System.out.println(getResult(roll)); out.println(getResult(roll));
}
public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
} else{ name = "Roll Number not found"; }
String result = "<Students>";
result += "<Student>"; result += "<Name>" + name + "</Name>";
result += "<Hostel>" +hostel + "</Hostel>";
result += "<Contact>" +contact + "</Contact>";
result += "</Student>"; result += "</Students>";
return result;
}
}

Now simple run your JSP page and put the roll number like 110, it will work.
http://localhost:8080/Ajax_Demo/ShowStudentInfo.jsp

If you have any question or suggestion, please put your commnets.

Parse XML response in JavaSript

Some time we get response from server as xml.
This blog will show that how you can handle or parse xml in javascript.
1. Suppose you have xml response like this

<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>
</Students>

2. In JavaScript function


function showResult(){
if(request.readyState == 4){
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
document.getElementById("NamelH1").innerHTML = students[0].getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = students[0].getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = students[0].getElementsByTagName("Contact")[0].text;
}
}

Second situation: Suppose you have abc.xml file and you want to parse in javascript

abc.xml

<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>
</Students>

Then your javascript would be

function getName(){
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
var students=xmlDoc.documentElement;
var student = students.childNodes(0);
document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].text;
}

Your JSP Page:

<h2>GET STUDENT INFO </h2>
<input onclick="getName();" type="button" value="Get Name">
Name : <span id="NamelH1"></span>
Hostel : <span id="HostelH1"></span>
Contact : <span id="ContactH1"></span>