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>

Thursday, April 23, 2009

AJAX Using DOJO Tutorial

It is very simple to develope Ajax application with DOJO. There is no any need to use
ActiveXObject or XMLHttpRequest. Here I am going to show a very simple application.

1. Create one dynamic web project using your Eclipse IDE. (Say Project Name : Ajax_Dojo)
2. Write one servlet in that project (Say AdmissionEnquiry.java)
3. Write one jsp page inside WebContent (Say example1.jsp)
4. Copy dojo.js inside WebContent
5. Add any server like Apache or Jboss to your project
6. Run the application http://localhost:8080/Ajax_Dojo/example1.jsp

AdmissionEnquiry.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 AdmissionEnquiry extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public AdmissionEnquiry() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
System.out.println("Entered Roll Number :: "+roll);
PrintWriter out = response.getWriter();
if(roll.equalsIgnoreCase("110")){
out.print("Binod Suman");
}
else if(roll.equalsIgnoreCase("120")){
out.print("Pramod Kumar");
}
else{
out.print("Roll Number not found");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

example1.jsp

<html><body onLoad="onLoad();"
><head>
<title>Ajax Dojo Example</title>
<script language="javascript" src="dojo.js"></script>
<script language="javascript">
dojo.require("dojo.io.*");
dojo.require("dojo.event.*");
function onLoad() {
var buttonObj = document.getElementById("myButton");
dojo.event.connect(buttonObj, "onclick", this, "onclick_myButton");
}
function onclick_myButton() {
var url2 = "http://localhost:8080/Ajax_Dojo/AdmissionEnquiry";
var bindArgs = {
url: url2,
error: function(type, data, evt){
alert(data); },
load: function(type, data, evt){
alert(data); },
mimetype: "text/plain",
formNode: document.getElementById("myForm") };
dojo.io.bind(bindArgs); }
</script>
</head>
<body>

<form id="myForm">
<h1>Find Student Name</h1>
<p> Enter Roll Number <input type="text" name="roll">
<input type="button" id="myButton" value="Submit"/>
</p>
</form>
</body>
</html>

During run the application, you will give roll number as input and you will get student Name.
Very simple ................ :)
Please give your comment to enhance this tutorial. ............ :)

Sunday, April 19, 2009

DOJO Tutorial

Dojo is a toolkit is an open source modular javaScript library. It used to ease the rapid development of Ajax based web application. First you have to download dojo.js from dojotoolkit.org .
1. Create one dynamic web project in Eclipse IDE. (Say Project Name Dojo_Demo)
2. Put the downloaded dojo.js into WebContent folder of project. (Location C:\DOJO_workspace\Dojo_Demo\WebContent\demo.jsp, here C:\DOJO_workspace is project path).
3. Create one demo.jsp in same locatoin i.e. WebContent

demo.jsp

<html>
<head>
<title>Binod Java Solution</title>
<script type="text/javascript">
dojo.require("dojo.event.*");
dojo.require("dojo.widget.*");
dojo.require("dojo.widget.Button");
function buttonCheck() { alert('YOU PRESSED OK BUTTON'); }
function init() {
var helloButton = dojo.widget.byId('button_first');
dojo.event.connect(helloButton, 'onClick')
}
dojo.addOnLoad(init); </script>
</head>
<body bgcolor="#FFFFCC">
<p align="center"><font size="6" color="#800000">Welcome to http://binodsuman.blogspot.com</font></p>
<button dojoType="Button" widgetId="button_first" onClick="buttonCheck();">OK BUTTON</button>
<br>
</body>
</html>

Add any web server (like Tomcat5.5) to your project then add Dojo_Demo project to server and start the server
Run http://localhost:8080/Dojo_Demo/demo.jsp
You will get dojo button, click and get your result. ........ :) So simple
Please give your comment, if you have any idea to enhance this tutorial ........ :)

Sunday, April 12, 2009

XML to PDF tutorial

To transfer xml information to pdf (create pdf file from xml file)
FOP : Formatting Objects Processor is an open source Java API that can convert your XML data into reports in PDF format.
1. Download fop from apache binary version
2. Unzip file and copy any drive say c:\fop-0.95-bin and add this path to your system environment path.
3. student.xml (c:\pdf\student.xml)
4. student.xsl (c:\pdf\student.xsl)
5. use command (c:\pdf> fop -xml student.xml -xsl student.xsl -pdf student.pdf)
You will get one student.pdf file. Very easy

Student.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<StudentRecord>
<Student>
<name>Manish</name>
<roll>130</roll>
<country>India</country>
<company>Infosys</company>
</Student>
<Student>
<name>Pramod Kumar</name>
<roll>120</roll>
<country>India</country>
<company>Patni Computers</company>
</Student>
<Student>
<name>Binod Kumar Suman</name>
<roll>110</roll>
<country>India</country>
<company>Satyam Computers</company>
</Student>
</StudentRecord>

student.xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format%22&gt;
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">

<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format%22&gt;
<fo:simple-page-master master-name="first"
page-height="29.7cm"
page-width="21cm"
margin-top="1cm"
margin-bottom="2cm"
margin-left="2.5cm"
margin-right="2.5cm">

<fo:region-body margin-top="3cm"/>
<fo:region-before extent="3cm"/>
<fo:region-after extent="1.5cm"/>
</fo:simple-page-master>
</fo:layout-master-set>

<fo:page-sequence master-reference="first">
<fo:static-content flow-name="xsl-region-before">
<fo:block line-height="14pt" font-size="10pt"
text-align="end">By Binod</fo:block>
</fo:static-content>
<fo:static-content flow-name="xsl-region-after">
<fo:block line-height="14pt" font-size="10pt"
text-align="end">Page <fo:page-number/>
</fo:block>
</fo:static-content>

<fo:flow flow-name="xsl-region-body">
<fo:block font-size="18pt"
font-family="sans-serif"
line-height="24pt"
space-after.optimum="15pt"
background-color="blue"
color="white"
text-align="center"
padding-top="3pt">
STUDENT EMPLYOEE REPORT
</fo:block>

<fo:block font-size="16pt"
font-family="sans-serif"
space-after.optimum="15pt"
text-align="center">
ADMS JAVA AND CS DEPARTMENT
</fo:block>

<fo:block text-align="start">This is based on the performance. </fo:block>

<fo:table table-layout="fixed" width="100%" border-collapse="separate">
<fo:table-column column-width="50mm"/>
<fo:table-column column-width="50mm"/>
<fo:table-column column-width="50mm"/>
<fo:table-body>
<fo:table-row color="red">
<fo:table-cell><fo:block>NAME</fo:block></fo:table-cell> <fo:table-cell><fo:block>ROLL</fo:block></fo:table-cell> <fo:table-cell><fo:block>COMPANY</fo:block></fo:table-cell> </fo:table-row>
<fo:table-row color="red">
<fo:table-cell><fo:block>------------------</fo:block></fo:table-cell> <fo:table-cell><fo:block>------------------</fo:block></fo:table-cell> <fo:table-cell><fo:block>------------------</fo:block></fo:table-cell> </fo:table-row>

<xsl:for-each select="StudentRecord/Student">
<xsl:sort select="name"/>
<fo:table-row>
<fo:table-cell><fo:block><xsl:value-of select="name"/></fo:block></fo:table-cell>
<fo:table-cell><fo:block><xsl:value-of select="roll" /></fo:block></fo:table-cell>
<fo:table-cell><fo:block><xsl:value-of select="company" />
</fo:block>
</fo:table-cell>
</fo:table-row>
</xsl:for-each>
</fo:table-body>
</fo:table>
</fo:flow>
</fo:page-sequence>
</fo:root>
</xsl:template>
</xsl:stylesheet>

Now you will feel that it is very job to develop PDF from XML. :)

How to backup of your blog

Please visit my other blog
http://binodjava.blogspot.com/2009/05/how-to-backup-of-your-blogger-blog.html

Thanks,

Binod Suman

Monday, April 6, 2009

XSLT tutorial using Java and XML

Extensible Stylesheet Language Transformations (XSLT)
XSLT provides a framework for transforming the structure of anXML document. XSLT combines an input XML document with an XSLstylesheet to produce an output document like HTML, PDF ...........
An XSL stylesheet is a set of transformation instructions for convertinga source XML document to a target output document. It requires an XSLT-compliant processor. The most popular open source XSLTengine for Java is the Apache Software Foundation’s Xalan project.
Here I am going to transform our student record into HTML for rendering purpose.

1. First add jar xml-apis.jar (Google and download)
2. student.xml
3. student.xsl
4. XMLToHTML.java

student.xml
<?xml version="1.0" encoding="ISO-8859-1"?>StudentRecord>
<Student>
<name>Binod Kumar Suman</name>
<roll>110</roll>
<country>India</country>
<company>Satyam Computers</company>
</Student>

<Student>
<name>Pramod Kumar</name>
<roll>120</roll>
<country>India</country>
<company>Patni Computers</company>
</Student>

<Student>
<name>Manish</name>
<roll>130</roll>
<country>India</country>
<company>Infosys</company>
</Student>

</StudentRecord>

student.xsl

<?xml version="1.0" encoding="ISO-8859-1"? >
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform;
<xsl:template match="/">
<html> <body>
<h2>STUDENT RECORDS</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Name</th>
<th align="left">Roll</th>
</tr>

<xsl:for-each select="StudentRecord/Student">
<tr>
<td> <xsl:value-of select="name" /> </td>
<td> <xsl:value-of select="roll" /> </td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

XMLToHTML.java


import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class XMLToHTML {

public static void main(String[] args) throws Exception {
File xmlFile = new File("src\\student.xml");
File xsltFile = new File("src\\student.xsl");
Source xmlSource = new StreamSource(xmlFile);
Source xsltSource = new StreamSource(xsltFile);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
//trans.transform(xmlSource, new StreamResult(System.out));
trans.transform(xmlSource, new StreamResult(new FileOutputStream("test.html")));
System.out.println("** HTML CREATED **");
}
}

After run the application, you will get new test.html file created in root folder of this application.

Interesting Note: Even witthout create html file, you can view xml in html formate in internet explorer. Without change any thing just do double click on student.xml, it will open in internet explorer like xml file.
Now add the XSN file infomation in XML then try to open XML file. You will get html formate.
How to add XSN information in XML file

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<StudentRecord>
<Student>
<name>Manish Kumar</name>
<roll>110</roll>
<country>India</country>
<company>Satyam Computers</company>
</Student>
<Student>
<name>Pramod Kumar</name>
<roll>120</roll>
<country>India</country>
<company>Patni Computers</company>
</Student>
<Student>
<name>Binod Kumar Suman</name>
<roll>130</roll>
<country>India</country>
<company>Satyam Computer Service Ltd</company>
</Student>
</StudentRecord>

Now you try to open this xml, it would be open in html formate as per the xsn.
Both student.xml and student.xsl should be in the same folder.

How to Filter Output in XSLT

You can give condition to the output from XML by adding these conditions :

1. =
2. !=
3. < less than
4. > greater than
5. element

student.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform; <xsl:template match="/"> <html>
<body>
<h2>STUDENT RECORDS</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Name</th>
<th align="left">Roll</th>
<xsl:for-each select="StudentRecord/Student[name='Binod Kumar Suman']">
<tr> <td>
<xsl:value-of select="name" />
</td> <td>
<xsl:value-of select="roll" />
</td> </tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Now you can run java program, you will get html file. In that file you will get only given student name output.
Second filter : Show only student record, whose roll number is greater than 115.

<xsl:for-each select="StudentRecord/Student">
<xsl:if test="roll > 115">
<tr> <td>
<xsl:value-of select="name" />
</td> <td>
<xsl:value-of select="roll" />
</td> </tr>
</xsl:if>
</xsl:for-each>

Now you can also sorting of your output
<xsl:for-each select="StudentRecord/Student">
<xsl:sort select="name"/>
<tr> <td>
<xsl:value-of select="name" />
</td> <td>
<xsl:value-of select="roll" /> </td>
</tr>
</xsl:for-each>

Actually there are many different ways to show xml file in formatted style using xslt
1. Using xsl file reference in xml file and open in internet browser (described above) that file is called XHTML file.
2. Using java Srcipt
How to use Java Script to show xml information in formated way as defined in xsl file
(A.) create xml file (Student.xml) as above
(B.) create xsl file (student.xsl) as above
(C.) create html file (test.htm) as below

test.htm

<html><body>
<script type="text/javascript">
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.load("student.xml")
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.load("student.xsl")
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

Now open test.htm file in internet browser.