Sei sulla pagina 1di 176

J2EE

AJAX & XML-II

Module 4
Agenda

1 Introduction to Ajax

2 Simple Ajax Application

3 Ajax Database Application

4 XML Schema - I

5 XML Schema - II

6 eXtensible Stylesheet Language (XSL)


Objectives
At the end of this module, you will be able to:

•Know what is AJAX ?


•Understand web Standards used in AJAX
•Understand AJAX Advantages
•Get to know how Ajax works
•Implement different Properties
•Send request to the server
•Learn to develop a simple Suggest Application using AJAX
•Learn how to communicate with database using AJAX and
DAO
•Learn how to return a JSP page as AJAX response
Objectives (Contd.).
• Describe the use of XML Schema and limitations of
DTDs
• Describe structure of XML Schema
• Create Schema Definition Files
• Define attributes in XSD
• Apply restrictions on values and set of values
• Describe the use of XSL
• Transform an XML document by using XSLT
• Work with XPATH expressions
• Create XSL Style sheets
• Use XSLT elements
• Sort and filter XML documents
Introduction to Ajax
What is AJAX ?
•AJAX stands for Asynchronous JavaScript And XML
•AJAX is a new way to use existing technologies to generate
dynamic web applications
•AJAX is based on JavaScript and HTTP Requests
•With AJAX, your JavaScript can communicate directly with the
server, using the JavaScript XMLHttpRequest object. With this
object, your JavaScript can trade data with a web server without
reloading the page.
•With AJAX you can create better, faster and more user friendly
web applications.
•Through AJAX both request and response are carried out
simultaneously.
•AJAX is a client side technology.
Notes
• Some additional features

1.AJAX is a type of programming made very popular by


Google with its Google Suggest in the year 2005. Ajax in
not a new programming language, but a technique for
creating better, faster and more interactive web
applications.
2.AJAX uses asynchronous data transfer (HTTP requests)
between the browser and the web server, allowing web
pages to request small bits of information from the server
instead of the entire pages.
3.AJAX is a browser based technology, independent of the
web server software.
Why AJAX ?
• Ajax is not a new technology, it’s an amalgamation of several
existing Technologies coming together in powerful new ways.

• Ajax Incorporates :
• Standards based presentation using XHTML and CSS
• Dynamic display and interaction using DOM.
• Data Interchange and manipulation using XML and
XSLT
• Asynchronous data retrieval using XMLHttpRequest
• JavaScript binding everything together
Notes
• While developing web based applications, on one side you
have tools like JSP, ASP, PHP, Perl, etc., and on the other,
there are JavaScript, DHTML, etc. One striking difference
between both the groups is that while JSP, ASP, PHP & Perl
are server side scripts, JavaScript is a client side script.
• Now taking an example, interactive web applications are
driven by user input data and the most routine operation on the
user-input data is validation. Though server side scripts are
extremely effective in weeding out malicious data, they are
usually time consuming and add additional bandwidth to the
web server. On the flip side, while the client side scripts are
instantaneous and all load is bore by the client system, they
can be very easily fooled. Having client-side validation as well
as server-side validation is an over-kill. So an interface that can
validate both sides at the same time suits the situation. Hence,
AJAX.
Web Standards used in AJAX
AJAX is based on the following Web Standards:
•JavaScript (For event action)
•XML (for information exchange)
•HTML (for formatted display)
•CSS (for formatting template)

This is also compatible with server-side Technologies like-


•JSP/Servlet
•ASP/ASP.NET
•PHP etc
Notes

• Web standards used in AJAX are well defined,


and supported by all major browsers.
• AJAX applications are browser and platform
independent.
AJAX- for better Internet Applications
•Web applications cater to larger audience over extensive
geographical regions
•Sometimes synchronous request processing may lead to
performance issues
•Refreshing a page will entail in loss of information fed by the
user
•AJAX makes internet applications much more user friendly
•Internet applications efficient and faster – data can be validated
before the form is submitted
•Gives rich UI contols
•Frameworks can work seamlessly if AJAX is incorporated
•AJAX does not require API overhead like other Technologies
•Nowadays, AJAX is supported by almost all browsers
AJAX - Advantages
• Real-time form data validation

• Autocompletion

• Load on demand

• Sophisticated user interface controls and effects

• Refreshing data and server push

• Partial submit

• Mashups
Notes
• Real-time form data validation: In interactive forms several form
fields like User IDs, Serial numbers, postal codes etc may require
server-side validation. This can be validated in a form using AJAX
before the user submits a form.
• Autocompletion: Certain form fields require to be filled up by
values fetched from the server at runtime. For instance if basic is
inserted then its associated salary components will be filled up by
values calculated from the server. This can be achieved using
AJAX
• Load on demand: Certain information enclosed within pages can
be returned to the master page as and when required. Like, when
a user chooses employee id the corresponding employee records
shall be fetched from the server.
• Sophisticated user interface controls and effects: Controls
such as trees, menus, data tables, rich text editors, calendars, and
progress bars allow for better user interaction can be developed
with AJAX technique embedded in them
Notes
• Refreshing data and server push: HTML pages may poll data
from a server for up-to-date data such as scores, stock quotes,
weather, or application-specific data. A client may use Ajax
techniques to get a set of current data without reloading a full
page. Polling is not the most effecient means of ensuring that
data on a page is the most current. Emerging techniques such
as Comet are being developed to provide true server-side push
over HTTP by keeping a persistent connection between the
client and server.
• Partial submit: An HTML page can submit form data as needed
without requiring a full page refresh.
• Mashups: An HTML page can obtain data using a server-side
proxy or by including an external script to mix external data with
your application's or your service's data. For example, you can
mix content or data from a third-party application such as
Google Maps with your own application.
AJAX – How it works
Client Side Web / XML Server

Browser
HTTP
JavaScript Request
Source
Call AJAX
Engine
Target
HTML+CSS
XML Data

Web Page

Fetch from
Store cache Datastores,
in Backend Process,
Cache Legacy Stores

Browser Cache Web Page


Notes
• AJAX works in the following manner:
1.The source (which can be a textbox/combobox etc) generates a
javascript call
2.The call is intercepted by the AJAX Engine
3.Ajax Engine creates XMLHttpRequest object
4.Using this object it sends Http request in either Get or Post method, to
the server resource (which can be datastore, any backend process,
legacy store etc)
5.A web page gets downloaded from the server to the local system. It is
stored in the browser cache, from where it is displayed on the browser.
The page area which does not require data from the server side is
temporarily stored in the browser cache
6.The response generated from the server is received as XML response
by the AJAX Engine
7.Ajax Engine translates the response into HTML/DHTML (HTML+CSS)
and displays in the target (which can be a textbox/div area etc)
8.The page is getting fetched from the browser cache and it amalgamates
the response from Ajax Engine
Notes

Note:
• As both the request and response happen simultaneously,
it appears to the user that the page has not been
refreshed

• The data which do not require server side processing


remains unchanged and thus AJAX does not hamper user
interaction with the page
Classic Web Application Model

Synchronous

Source: James Garrett / adaptivepath.com


Notes

• The above diagram shows synchronous request-response


activities in a classic web application model

• After each user activity the request is sent to the server for
processing

• The user has to wait unless the response is returned from


the server

• In a given time frame the process is quite time exhaustive


AJAX Web Application Model

Asynchronous
Notes
• The above diagram shows asynchronous request-
response activities in a ajax web application model

• The client side processing carries alongside server side


processing

• The user continues working with the UI while the response


is getting fetched from server

• In a given time frame the process is faster


AJAX and HTTP requests

Contrary to the traditional JavaScript working,


•With AJAX, your JavaScript communicates directly with the
server, through the JavaScript XMLHttpRequest object.
•With an HTTP request, a web page can make a request to, and
get a response from a web server - without reloading the page.
•The user will stay on the same page, and he or she will not
notice that scripts request pages, or send data to a server in the
background.
Notes
• In traditional JavaScript coding, if you want to get some
information from a file or database on the server or you
want to send user information to the server, you will have to
create a HTML form and use the GET/POST method. The
user will have to enter the data and then click on the
“submit” button to send the information and then wait for the
server to respond then a new page will be loaded with the
results.

• Because the server returns a new page each time the user
submits the input, traditional web applications can run
slowly and tend to be less user-friendly.
The XMLHttpRequest Object

• The main element of AJAX is the XMLHttpRequest Object.


• By using the XMLHttpRequest object, a web developer can update a page
with data from the server after the page has loaded.
• The XMLHttpRequest Object is supported in various browsers like Internet
Explorer 5.0+ , Safari 1.2 , Mozilla 1.0/Firefox, Opera 8+ and Netscape 7.
• Different browsers use different methods to create the XMLHttpRequest
Object
(Internet Explorer uses an ActiveXObject, while other browsers uses the
built-in JavaScript object called XMLHttpRequest.
Example:
var xmlHttp;
xmlHttp=new XMLHttpRequest(); //firefox, safari , opera 8.0+
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); //IE 6.0+
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE 5.5+
Notes

• Note: Internet Explorerer 7.0 supports XMLHttpRequest.


The onreadystatechange Property
• Once a request is made to the server, the function receives the data
returned by the server

• The onreadystatechange property stores the function that will


process the response from a server

• The function that is stored in the onreadystatechange property is a


function that is stored in the property to be called automatically

Example:
xmlHttp.onreadystatechange=function(){
//some code for handling server response}
• The onreadystatechange property stores an empty function inside it
Notes

• In the code above, the “xmlHttp” is a variable that holds


the XMLHttpRequest object.
The readyState Property
•The readyState property holds the status of the server’s response.
•The onreadystatechange function will be executed, when each time
the readyState changes
•The possible values for the readyState property:

State Description

0 Request not initialized

1 Request has been set up / Connection Established

2 Request sent / request received by server

3 Request under process / response is in process

4 Request completed / Server ready to generate response


The responseText Property

• The data sent back from the server can be retrieved with the
responseText property.

Example:

xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState==4)
{

document.myFormname.myTextboxname.value=xmlHt
tp.responseText;
}
}
Notes
• In the partial code above, the “xmlHttp” is a variable that
holds the XMLHttpRequest object.

• In the example above, it checks if the readyState property


of the XMLHttpRequest object is ‘4’ (The Request is
Complete) , if yes it sets the responseText (data sent by
the server)
• as the textbox’s value. Here,
• document  Is the html document
• myFormname  Is the name of the Form within the html
page
• MyTextboxname  Is the name of the text box in the form
Sending a request to the server
• To send a request to the server, we use the open() and the send()
methods

• The open() method:


The open() method takes three arguments.
1. The first argument defines which method to use when sending the
request (GET or POST)
2. The second argument specifies the URL of the server-side script
3. The third argument takes a boolean which specifies that the request
should be handled asynchronously

• The send() method - sends the request off to the server.

Example:
xmlHttp.open("GET",“server-side-component.jsp",true);
xmlHttp.send(null);
Notes

• Browsers don’t cache POST requests (unlike GET


requests)
Simple Ajax Application
Prerequisites for running Ajax Application
• AJAX does not have huge api requirements compared to other
technologies

• For an AJAX Application to execute, the browser must support AJAX

• For Microsoft Internet Explorer, IE 6.0 or above is recommended, as


the earlier versions does not support AJAX

• As we are going to fetch response from the server, a web server at


least is required

• Since the request and response are carried out simultaneously, it is


preferable that the RAM is at least 512MB or more
Suggest Application
Case Study :
Create an application that takes city names as input from the user.

• While taking the input, for each key press it is going to


provide a list of city names starting with the entered
keywords, as suggestion

• Use AJAX to generate the suggestion from a servlet having


an array of city names
Notes

This application is also popularly known as "Google


Suggestion" Application and Google has implemented this
as a toolbar.
Steps to follow

• For creating the application we have to follow the


following steps:

1. Create a HTML file with a text box and suggestion div

2. Create a Javascript file with AJAX code

3. Create a Servlet for processing the application request


and generating the response
Step 1- CitySuggest.html
<html>
<head>
<title>City Suggest</title>
<script src="CityApps.js">
</script>
</head>
<body>
<!-- Text box to type city names -->
Enter City <input type="text" name="city_name"
onkeyup="sendRequest(this.value)"/>
<p><strong>Suggestions:</strong></p>
<!-- Div where the application response shall be
displayed -->
<div id="city_suggest"></div>
</body>
</html>
Step 2- CityApps.js (Javascript)
var req;//global variable
//function to get the keyword and generate request object
function sendRequest(cname)
{
//for firefox/safari/opera/google chrome
if (window.XMLHttpRequest) {
req = new XMLHttpRequest( );
}
else if (window.ActiveXObject)//for IE
{req = new ActiveXObject("Microsoft.XMLHTTP");}
//concatenate the city name as parameter value to url
var url = "NameSuggest?city_n="+cname;
//check server request state
req.onreadystatechange = getResponse;
req.open("GET", url, true);//send request to server
req.send(null);
}
Notes

• The javascript could have been written in the previous


HTML page within <script> as an alternative
Step 2- CityApps.js (Javascript) (Contd.).
//function to get the response and display in the specific
area
function getResponse()
{
if (req.readyState==4) //if request is complete
{
if (req.status == 200) //if target page is found
{
//write the response text in the div area
document.getElementById("city_suggest").innerHTML =
req.responseText;;
}
}
}
Step 3- NameSuggest.java (Servlet)
/*
* Servlet Class to process a keyword
* and return matching city names as suggestion
* from a list of city names
*/
package com.Talearnt;

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;
Step 3- NameSuggest.java (Servlet) (Contd.).
public class NameSuggest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest
request,HttpServletResponse response) throws
ServletException, IOException {
try {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String suggestion="";
//Array containing city names
String cities[]={***the declaration is in notes page***}
//fetch the city name from application request
String city_name=request.getParameter("city_n");
if(city_name.length()>0)
{
for(int i=0;i<cities.length;i++)
{
Notes

• ***declaration of String cities[]***

• String cities[]=
• {"Aligarh","Ahmedabad","Allahabad","Ajmer","Aurangabad","
Aizwal","Agartala","Agra","Amritsar","Bengaluru","Baroda","B
ikaner","Belgaun",
• "Bareily","Bhubaneshwar","Bhatinda","Bhopal","Cochin","Ch
andigarh","Chennai”,"Coimbatore","Cuttack","Calicut","Dehr
adun","Durgapur","Ernakulam",
"Faridabad","Gangtok","Ghaziabad","Gulbarga","Gandhinag
ar","Gwahati","Gwalior","Goa","Gaya”,"Gurgaon","Hyderaba
d","Indore","Imphal","Jaipur","Jammu",
Notes

• "Jamshedpur","Jaisalmer","Jodhpur","Jallandhar","Jabalpur
","Kakinada","Kannur","Kanpur","Kolkata","Kohima","Karnal
","Kollam","Lucknow","Leh","Ludhiana",
"Mangalore","Madurai","Mumbai","Moradabad","Mysore","
Mughalsarai","Nagpur","Nashik","New Delhi",
"Nainital","Nellore","Noida","Pallakad","Panvei","Pune",
"Pondicherry","Patna","Port
Blair","Puri","Raipur","Rourkela","Rajkot","Rajamundry","Ra
nchi","Shillong","Srinagar","Silchar","Siliguri","Salem","Sura
t",
"Sambalpur","Shimla","Trivandrum","Trichur","Tirupathi","U
daipur","Ujjain","Udupi","Vijaynagar","Vijaywada","Vizag","V
ellore","Varanasi"};
Step 3- NameSuggest.java (Servlet) (Contd.).
//convert the array index value and the request parameter
value
//to uupercase and then check if the array index
value(city name)
//is prefixed with the supplied string
if(cities[i].toUpperCase().startsWith
(city_name.toUpperCase()))
{ suggestion=suggestion+cities[i]
+"<br>";
}}}
out.println(suggestion);}
catch(Exception e)
{e.printStackTrace();}}
}
Suggest Application Output

User types a character

The application return


all the city names
beginning with those
character/s
Ajax Database Application
AJAX Database Application
Case Study :

Create a web application that takes new entry for department and
check if the department is already entered in the database

• The entry form should be designed in a JSP page

• Department no should be autogenerated

• While taking the input in department name check using ajax if


the name is already present in the database using DAO

• Notify the message in a span placed adjascent to the


department name textbox
Step 1- DeptEntry.jsp
<%@page import="com.Talearnt.dao.DeptDAO"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Department Entry</title>
</head>
<body>
<script src="DeptApps.js"></script>
<h1>Enter Department Details</h1>
<%
DeptDAO dao=new DeptDAO();
%>
Notes

• The JSP uses the DAO to autogenerate the deptno.


The same could have been done without using
scriptlet, by using <jsp:useBean>.
Step 1- DeptEntry.jsp (Contd.).
<form method="post" action="AddDepartmentServlet">
<table>
<tr>
<td>Deptno</td>
<td><input type="text" name="dno"
value="<%=dao.generateDeptno()%>" readonly/></td>
</tr>
<tr>
<td>Enter Deptname</td>
<td><input type="text" name="dname"
onblur="sendRequest(this.value)"/></td>
<td><span id="dname_status"></span></td>
</tr>
<tr><td>Enter Location</td>
<td><input type="text" name="loc"/></td>
</tr>
Step 1- DeptEntry.jsp (Contd.).
<tr>
<td><input type="submit" name="b1" value="Add"/></td>
<td><input type="reset" name="b2" value="Clear"/></td>
</tr>
</table>
</form>
</body>
</html>
Step 2- DeptApps.js (javascript)
var req;//global variable
//function to get the department name as parameter
//and passing it to server for checking its existence
function sendRequest(dnm)
{
//for firefox/safari/opera/google chrome
if (window.XMLHttpRequest) {
req = new XMLHttpRequest( );
}
else if (window.ActiveXObject) //for IE
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
//concatenate the dname as parameter value to url
var url = "DnameChecker?dname="+dnm;
Step 2- DeptApps.js (javascript) (Contd.).
req.onreadystatechange = getResponse;//check server
request state
req.open("POST", url, true);//send request to server
req.send(null);
}
//function to get the response and display in the specific
area
function getResponse()
{
if (req.readyState==4) //request is complete
{
if (req.status == 200) //target page is found
{
//write the response text in the span area
document.getElementById("dname_status").innerHTML =
req.responseText;;
}}}
Notes

• Here, we are using POST method to send the


request to the server
Step 3- DeptDAO.java (DAO)
package com.Talearnt.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* Dept DAO class
*/
public class DeptDAO
{
//Database connection url
String url="jdbc:oracle:thin:@localhost:1521:orcl";
Step 3- DeptDAO.java (DAO) (Contd.).
//Database connection username
String username="scott";
//Database connection password
String password="tiger";

//method to establish database connection


public Connection connect() throws SQLException,
ClassNotFoundException
{
//Using type 4 driver
Class.forName("oracle.jdbc.OracleDriver");
//return connection url
return
DriverManager.getConnection(url,username,password);
}
Notes

• The connect() configures the connection parameters for


the entire DAO and this can be reused by different
methods.

• The generateDeptno() and getDname() are caling it to


establish connection to the database.
Step 3- DeptDAO.java (DAO) (Contd.).
//method to autogenerate deptno by finding the maximum
deptno
//currently present and generating the new deptno by
10
public int generateDeptno()
{
int deptno=0;
try
{
//establish conection
Connection conn=connect();
//query to fetch the max deptno value
String query="select max(deptno) from dept";
//Using PreparedStatement the query plan is created
PreparedStatement ps=conn.prepareStatement(query);
//fetch value into resultset
ResultSet rs=ps.executeQuery();
Notes
• The generateDeptno() auto generates the deptno which
is displayed in the DeptEntry.jsp. Each consecutive
deptno is having value +10 from its previous one. So, if
40 is the last maximum deptno, then next will be 50.

• The autogeneration can be also done using database


sequence or any other technique.
Step 3- DeptDAO.java (DAO) (Contd.).
if(rs.next())
{
//fetch max(deptno) value into deptno
deptno=rs.getInt(1);
}
//increment deptno by 10
//if no value is returned from the query ie
//when table is empty then deptno will start with
10
deptno=deptno+10;
}
catch(Exception ex)
{
ex.printStackTrace();
}
return deptno;
}
Step 3- DeptDAO.java (DAO) (Contd.).
//method to check if dname passed as parameter is already
present
public boolean getDname(String dname)
{
try
{
//establish conection
Connection conn=connect();
//query to fetch the max deptno value
String query="select * from dept where dname=?";
//Using PreparedStatement the query plan is created
PreparedStatement ps=conn.prepareStatement(query);
//send dname as parameter to preparedstatement
ps.setString(1, dname);
Notes

• The getDname() carries the dname set from the


servlet. It checks with the database for the existence of
the supplied dname.
Step 3- DeptDAO.java (DAO) (Contd.).
//fetch value into resultset
ResultSet rs=ps.executeQuery();
//check if resultset contains at least one row
if(rs.next())
{//dname is present
return true;}
else
{//dname is not present
return false;}
}
catch(Exception ex)
{//for exception also return false
return false;}
}
}
Step 4- DeptChecker.java (Servlet)
package com.Talearnt.servlet;

import com.Talearnt.dao.DeptDAO;
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;

/**
* Servlet class which receives the
* application request
*/
Step 4- DeptChecker.java (Servlet) (Contd.).
public class DnameChecker extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-
8");
PrintWriter out = response.getWriter();
try {
//extract department name from the parameter
String deptname=request.getParameter("dname");
if(deptname.length()>0)//if not blank
{
DeptDAO dao=new DeptDAO();
//check from DAO if department exists
if(dao.getDname(deptname)==true)//when found
{out.println("<font color=red>Deptname Already
Present</font>");
}
Notes

• The servlet here acts like a controller and interacts with


the DAO (model) to communicate with the database.

• The response is sent back to the view (JSP).


Step 4- DeptChecker.java (Servlet) (Contd.).
else
{//when not found
out.println("<font
color=green>Deptname not Present</font>");
}
}
else
{//for blank
out.println("<font color=red>Deptname
cannot be blank</font>");
}
} finally {
out.close();
}
}
}
Expected Output (One) – preexisting deptname

Message given as
response from
server using AJAX
Expected Output (Two) – new deptname

Message given as
response from
server using AJAX
AJAX Database Application returning JSP
Case Study :

Create a web application that provides the user a list of jobs, selecting
which the employees having that job profile is displayed

• When a particular job is chosen, use ajax to fetch the list of


employees having that job profile and display them in a div
area
• Fetch the employees from the database using DAO and
store them as a Vector of EmployeeBean objects
• Store the Vector in a session
• The final response is generated from a JSP which retieves
the employee records from the session and dispay them in a
tabular manner
Step 1- EmployeesJob.html (HTML)
<html>
<head>
<title>View Employees</title>
</head>
<script src="EmpApps.js">
</script>
<body>
Choose Employee job type
<select name="job_list"
onchange="sendRequest(this.value)">
<option value="nojob">---Choose Job---
</option>
<option value="ANALYST">Analyst</option>
<option value="CLERK">Clerk</option>
<option value="SALESMAN">Salesman</option>
<option value="MANAGER">Manager</option>
</select>
<hr/><div id="emp_details"></div>
</body></html>
Step 2- EmpApps.js (Javascript)
var req;//global variable
//function to get the job as parameter and
//passing to server to find related employee records
function sendRequest(j)
{
//for firefox/safari/opera/google chrome
if (window.XMLHttpRequest) {
req = new XMLHttpRequest( );
}
else if (window.ActiveXObject) //for IE
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
//concatenate the job as parameter value to url
var url = "FindEmp?job_list="+j;
Step 2- EmpApps.js (Javascript) (Contd.).
req.onreadystatechange = getResponse;//check server
request state
req.open("POST", url, true);//send request to server
req.send(null);
}
//function to get the response from jsp
//and display in the specific area
function getResponse()
{
if (req.readyState==4) //request is complete
{
if (req.status == 200) //target page is found
{
//write the response text in the div area
document.getElementById("emp_details").innerHTML =
req.responseText;;
}}}
Step 3- EmployeeBean.java (Bean)
package com.Talearnt.bean;

import java.io.Serializable;
/**
* Employee Bean class
* containing accessor and mutator
* methods of Employee attributes in the table
*/
public class EmployeeBean implements Serializable
{
private int empno;
private String ename;
private String job;
private double salary;
public EmployeeBean()
{
}
Step 3- EmployeeBean.java (Bean) (Contd.).
public int getEmpno() {
return empno; }
public void setEmpno(int empno) {
this.empno = empno; }
public String getEname() {
return ename; }
public void setEname(String ename) {
this.ename = ename; }
public String getJob() {
return job; }
public void setJob(String job) {
this.job = job; }
public double getSalary() {
return salary; }
public void setSalary(double salary) {
this.salary = salary; }
}
Notes

• get() are accessor methods


• set() are mutator methods
Step 4- EmployeeDAO.java (DAO)
package com.Talearnt.dao;

import com.Talearnt.bean.EmployeeBean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

/**
* DAO class to fetch Employee records
* on the basis of selected job profile
*/

public class EmployeeDAO


{
Step 4- EmployeeDAO.java (DAO) (Contd.).
//Method to fetch employee records who are having the job
//matching the job supplied from the view as parameter

public Vector<EmployeeBean> fetchEmployees(EmployeeBean


empbean)
{
//Database connection url
String
url="jdbc:oracle:thin:@localhost:1521:orcl";
//Database connection username
String username="scott";
//Database connection password
String password="tiger";
//Vector to store a collection of employee objects
//fetched from database
Vector<EmployeeBean> V=new Vector<EmployeeBean>();
Notes

• Here Vector can be used in non-generic format also.


Step 4- EmployeeDAO.java (DAO) (Contd.).
try
{
//Using type 4 driver
Class.forName("oracle.jdbc.OracleDriver");
//Establish the connection
Connection
conn=DriverManager.getConnection(url,username,password);
//Query to fetch empno,ename and sal based on job
and //sort result on the basis of empno in ascending
order
String query="select empno,ename,sal from emp where
job=? order by empno";
//Using PreparedStatement the query plan is created
PreparedStatement ps=conn.prepareStatement(query);
//set the job as parameter to PreparedStatement
ps.setString(1, empbean.getJob());
Step 4- EmployeeDAO.java (DAO) (Contd.).
//Execute the query and store result in ResultSet
ResultSet rs=ps.executeQuery();//executeQuery() for
select
//fetch each row from resultset until no rows are
available
while(rs.next())
{
//An employee record object created to map and store
//each attribute of employee record from the resultset
EmployeeBean emprecord=new EmployeeBean();
emprecord.setEmpno(rs.getInt(1));//fetch empno
emprecord.setEname(rs.getString(2));//fetch ename
emprecord.setSalary(rs.getDouble(3));//fetch sal
V.addElement(emprecord);//store entire employee object in
vector
}

See Notes for remaining code


Notes

• }
• catch(Exception ex)
• {
• ex.printStackTrace();
• }
• return V;
• }
• }
Step 5- FindEmp.java (servlet)
package com.Talearnt.servlet;

import com.Talearnt.bean.EmployeeBean;
import com.Talearnt.dao.EmployeeDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Servlet class to process application request
*/
public class FindEmp extends HttpServlet {
Step 5- FindEmp.java (servlet) (Contd.).
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-
8");
PrintWriter out = response.getWriter();
try {//extract job from the parameter
String job_selected=request.getParameter("job_list");
//check if 'nojob' is selected
if(!job_selected.equalsIgnoreCase("nojob"))
{
EmployeeBean empbean=new EmployeeBean();
empbean.setJob(job_selected);//set the job
EmployeeDAO empdao=new EmployeeDAO();
//call the fetchEmployees() of EmployeeDAO
Vector<EmployeeBean>
employeeV=empdao.fetchEmployees(empbean);
Notes

The servlet gets the job as request parameter and sets it in


the setter() of the bean
Step 5- FindEmp.java (servlet) (Contd.).
HttpSession hs=request.getSession();
//set the entire vector object containing employee
records in the session
hs.setAttribute("emp", employeeV);
//redirect to ShowEmployees.jsp

response.sendRedirect("ShowEmployees.jsp");
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
}
Notes

• The Vector returned from the DAO is set in the session


and the response is redirected to the
ShowEmployees.jsp

• The JSP gives the final response


Step 6- ShowEmployees.jsp (jsp)
<%@page import="com.Talearnt.bean.EmployeeBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Employees</title>
</head>
<body>
<%
//Get the Vector object containing employee
records from session
Vector<EmployeeBean>
empV=(Vector<EmployeeBean>)session.getAttribute("emp");
%>
Step 6- ShowEmployees.jsp (jsp) (Contd.).
<table>
<th>Emp No</th><th>Emp Name</th><th>Salary</th>
<%
//Fetch each employee bean object from vector
for(int i=0;i<empV.size();i++){
EmployeeBean beanobject=empV.elementAt(i);
//create rows and feed data from employee bean object
%>
<tr>
<td><%=beanobject.getEmpno()%></td>
<td><%=beanobject.getEname()%></td>
<td><%=beanobject.getSalary()%></td>
</tr>
<%
}
%>
</table></body></html>
Expected Output

Choose Job Combobox

Data fetched from database using AJAX


and returned as JSP response in the div
area
XML Schema - I
XML Schema

•An XML-based language alternative to DTDs

•Describes the structure of an XML document

•The W3C XML Schema language is also referred to as XML Schema


Definition or XSD

•XML documents that comply to an XML schema are known as


instances of that schema
Notes

• A well-formed XML document follows all the syntax rules


of XML, but it may not necessarily adhere to any particular
schema. So, an XML document can be well formed
without being valid, but it cannot be valid unless it is well
formed.
Limitations of DTDs

• DTDs are a weak specification language


• You cannot put any restrictions on element contents
• You have little control over ordering of elements
• For example: Difficult to specify that all child
elements must occur, but may be in any order
• There are only ten data types for attribute type values

• DTDs are not written in XML


• For validation, you need separate parsers for XML
and DTD
Features of XML Schema

• XML Schema presents enhancements over DTDs:


• Support for data types
• 37+ built-in data types
• Allows to create your own data types
• It is written in XML
• Can define the child elements to occur in any order
• Gives you much more control over structure and
content
Notes

– Though XML Schemas are more powerful than DTDs, DTDs


have been around longer than XSD. Therefore DTDs are
more widely used and also, more tools support them
Defining XML Schema

The purpose of XML Schema is to define the structure of an


XML document just like a DTD

• An XML Schema defines:


• elements that can appear in a document
• attributes that can appear within elements
• which elements are child elements
• the sequence in which the child elements can appear
• the number of child elements
• whether an element is empty or can include text
• default values for attributes
Example – a DTD to an XSD

•Consider a simple DTD called song.dtd and let us write the schema
song.xsd

<!ELEMENT song (title, category, artist)>


<!ELEMENT title (#PCDATA)>
<!ELEMENT category (#PCDATA)>
<!ELEMENT artist (#PCDATA)>

•The file extension of XSD document is .xsd


XSD - Example
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema" song.xsd
targetNamespace="http://www.music.org/album"
elementFormDefault="qualified">
<xsd:element name=“song">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name=“category” type="xsd:string"/>
<xsd:element name=“artist" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Notes

• (song.xsd) XML Schema: Specifies the Properties for a


Class of Resources. For the class of song resource, there
are 3 properties – title, category, artist.

• (song.xml) XML Instance Document: Specifies Values for


the Properties. For a specific instance of a song resource,
the values for the properties – New Divide, Pop, Linkin
Park. Use schemaLocation to identify the companion
document (i.e., the schema) which defines the song class
of resources.
Understanding XSD Example

•Every XSD document has a root element called <schema>


•Schema heavily uses namespaces, hence namespace declaration is
done at root level itself

song.xsd
<xsd:schema
1 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
2 targetNamespace="http://www.music.org/album"
3 elementFormDefault="qualified">
……
</xsd:schema>

1 Namespace of XML Schema Language


2 Namespace of the vocabulary defined in this schema
3 All XML elements must be qualified (use a namespace)
Notes
• The <schema> element may have attributes
(namespaces)
• XML Schema elements are referred with the xsd prefix
xmlns:xsd="http://www.w3.org/2001/XMLSchema“ - This is
necessary to specify since our XSD tags are defined here
• The elements and data types such as schema, element,
complexType, sequence, string, etc that are used to
construct schemas come from the
http://www.w3.org/2001/XMLSchema namespace
• targetNamespace=http://www.music.org/album
indicates that the elements defined by this schema such
as: song, title, category, and artist are to go in the
namespace specified by targetNamespace
Mapping of vocabulary and schema

http://www.w3.org/2001/XMLSchema http://www.music.org/album
(XMLSchema Namespace) (targetNamespace)

element complexType song title


string schema category artist
sequence

This is the vocabulary (XSD


tags) that the XML Schema
provides to define our own
schema
Notes

• The vocabulary that DTDs provide: ELEMENT, ATTLIST,


#PCDATA, CDATA, NMTOKEN, ENTITY

• to define our new vocabulary are: song, title, category,


artist

• Similarly XML Schema has a vocabulary that is already


available to define our new vocabulary in schema
documents.
XML Document mapped to Schema

<?xml version="1.0" encoding="UTF-8"?>


<song
xmlns="http://www.music.org/album"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.music.org/album song.xsd">
<title>New Divide</title>
<category>Pop</category>
The namespace to use
<artist>Linkin Park</artist>
</song>

Informs parser about location of the


schema when it defines a The location of XML schema
namespace to use for that namespace
Notes
• The schemaLocation attribute has two values. The first
value is the namespace to use. The second value is the
location of the XML schema to use for that namespace
• The targetNamespace declaration in the XSD targets all the
elements defined in the schema to the URI pointed out in
the targetNamespace.
• And if any XML instance document want to use the
elements present in the namespace, it must specify the URI
of where the namespace is located and then it also needs
to specify where exactly (which file) the definitions of the
elements being used are present.
• Clearly, the schemaLocation syntax in the XML Instance
document indicates the URI and the file location.
Referencing a schema in an XML instance document
• To refer to a DTD in an XML document, the reference goes before the
root element:
<?xml version="1.0"?>
<!DOCTYPE rootElement SYSTEM "url">
<rootElement> ... </rootElement>

• To refer to an XSD in an XML document, the reference goes in the root


element:

<?xml version="1.0"?>
<rootElement
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance“
(The XML Schema Instance reference is required)
xsi:SchemaLocation="url file">
(This is where your XML Schema definition can be found)
...
</rootElement>
Notes

• Source:
http://www.disi.unige.it/person/CerioliM/TAPS2002-2003/Sli
des/schemas.ppt
Multiple Levels of Checking

song.xml song.xsd XMLSchema.xsd


(schema-for-schemas)

Validate that xml document Validate that song.xsd is a valid


conforms to rules described schema document, i.e., it
in song.xsd conforms
to rules described in schema-for-
schemas
Notes

• XML Schema: Specifies the Properties for a Class of


Resources
Components of a Schema

• All schema definitions contain two types of elements: simple and


complex

• A “simple” element is one that contains only text


• Text can be simple data such as numbers, strings, or dates
• Various restrictions may be applied to simple data
• Cannot contain any child elements
• Cannot have attributes

• A “complex” element is one that contains child elements


• May contain attributes
• May be empty, or it may contain text
Notes

• Complex types can have internal structure, such as child


elements and attributes, but simple types cannot. For
example, attributes are always simple types because
attribute values cannot have any internal structure (such
as child elements).

• The distinction between simple and complex types is an


important one because simple and complex types are
declared differently. Complex types are declared by the
author, and the XML schema specification comes with
many simple types already declared. Simple types can
also be declared by the author.
Defining a simple element

• A simple element is defined as


<xsd:element name=“aaa" type=“bbb" />
where:
• aaa is the name of the element
• bbb is the data type of the element

xsd:boolean xsd:integer Common built-in


xsd:date xsd:string types in XML
xsd:decimal xsd:time schema

• Elements may have a default value or a fixed value specified whose


values are assigned automatically
• default="default value" if no other value is specified
• fixed="value" i.e., no other value may be specified
Notes
• To declare elements, you use the <xsd:element> element
in XML schemas. When you declare an element, you can
specify its type.

• The <xsd:element> element has two attributes, fixed and


default, that let you specify an element's default values.
Defining simple element - Examples

• XML code for simple elements

<firstname>Anny</firstname>
<age>19</age>
<birthdate>1990-05-15</birthdate>

• XSD code for simple element definitions

<xsd:element name=“firstname" type="xsd:string"/>


<xsd:element name="age" type="xsd:integer"/>
<xsd:element name=“birthdate" type="xsd:date"/>

• Example: the default value is “ABC Inc":

<xsd:element name="company" type="xsd:string" default=“ABC Inc"/>


Defining a complex element

• Use the element complexType when declaring elements with child


elements

A complex element is defined as:

<xs:element name="name">
<xs:complexType>
….
.... information of complex type element
</xs:complexType>
</xs:element>
Defining a complex element - Example

Example:

<xsd:element name="song">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="category" type="xsd:string"/>
<xsd:element name="artist" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:sequence> means elements must occur in this order
Notes

• Occurrence indicators are used to define how often an


element can occur.

• The <maxOccurs> indicator specifies the maximum


number of times an element can occur.

• The <minOccurs> indicator specifies the minimum number


of times an element can occur.
XML Schema - II
Defining Attributes

• Attributes are always declared as simple types

• An attribute is defined as
<xsd:attribute name=“aaa" type=“bbb" />
where:
• aaa is the name of the attribute
• bbb is the data type of the attribute
xsd:boolean xsd:integer
xsd:date xsd:string

Common built-in types in


xsd:decimalxsd:time XML schema

• Example:
• An XML element with an attribute:
<book price=“500">Mastering XML</book>
• The corresponding attribute definition:
<xsd:attribute name=“price" type="xsd:integer"/>
Notes

• The <xsd:attribute> also has a type attribute, and its


attributes must always be of a simple type.

• Attributes may also have a default value or a fixed value


specified.
Default and Fixed values for Attributes

Attributes may have a default value or a fixed value specified

• default=“default value” means no other value is specified


• Example:
<xs:attribute name=“publisher" type="xs:string" default=“ABC“/>

• fixed=“value” means no other value may be specified


• Example:
<xs:attribute name=“publisher" type="xs:string" fixed=“ABC“/>
Optional and Required Attributes

• Attributes are optional by default

• To specify that the attribute is required, use the "use" attribute

• Example:
• <xs:attribute name=“title" type="xs:string" use="required“ />
The “use” attribute

• The use attribute specifies whether the attribute is required or


optional

• If an attribute is optional, it specifies whether its value is fixed or has


a default

• Examples:
<xs:attribute name=“title" type="xs:string" use="required“/>
<xsd:attribute name=“emailid" type="xsd:string" use="optional“ />
The “value” attribute

• The value attribute contains a value if you need to specify one

• Examples:
<xsd:attribute name="year" type="xsd:int" use="fixed"
value="2007“ />

<xsd:attribute name="year" type="xsd:int" use="default"


value="2007“ />
Restrictions or Facets

• You can put restrictions to define acceptable values for


XML elements or attributes

• Restrictions on Values - Example


<xsd:element name=“marks">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="0">
<xsd:maxInclusive value="100">
</xsd:restriction>
</xsd:element>
• Here, an element called “marks" is defined with a
restriction
• The value of marks cannot be < 0 or > 100
Notes

• The general form for putting a restriction on a text value is:


– <xsd:element name="name"> (or xsd:attribute)
<xsd:restriction base="type">
... the restrictions ...
</xsd:restriction>
</xsd:element>
Restrictions on a set of values
• You can use enumeration to restrict the value to be one of a fixed set
of acceptable values

• For example: An element “sport” is defined with a restriction. The only


acceptable values are: Tennis, Golf, Badminton
<xs:element name=“sport">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=“Tennis"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value=“Badminton"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Elements containing only other elements
• Example of XML element "employee“ which contains only other
elements
<employee>
<name>Anny</name>
<address>Park Street, Bangalore</address>
</employee>

• Create a named complexType “person” and use that type

<xs:complexType name="persontype">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name=“address" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="employee" type="persontype“ />
Notes
• A complex element in an XML Schema can be defined in two
different ways:
• 1. The "employee" element can be declared directly by naming
the element, like this:
• <xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name=“address" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
• In this method, only the "employee" element can use the
specified complex type.
• 2. In the 2nd method (shown in slide) The "employee" element
can have a type attribute that refers to the name of the complex
type to use.
Elements containing only other elements (Contd.).

In this method, several elements can refer to the same complex type

For Example:

<xs:complexType name="persontype">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name=“address" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:element name="employee" type="persontype"/>


<xs:element name=“customer" type="persontype"/>
<xs:element name=“faculty" type="persontype"/>
Using “ref” attribute

You can design your schema by defining all elements and attributes
first
You can then refer to them using ref attribute
Example:
<xsd:element name="name" type="xsd:string"/> Definition of
<xsd:element name="address" type="xsd:string"/> simple
<xsd:element name="employee"> elements
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="name"/>
<xsd:element ref="address"/>
</xsd:sequence> Definition of
</xsd:complexType> complex
</xsd:element> element
Elements with mixed content

• Mixed complex type elements can contain attributes, elements, and


text

• Add mixed="true" to the xs:complexType element

• An XML element, “message", that contains both text and other


elements:

<message>
Dear<name>Anny</name>,
Please attend a training on<training>XML</training>
scheduled on <tdate>2009-08-17</tdate>.
</message>
Elements with mixed content (Contd.).

• The following schema declares the “message" element


<xs:element name="message">
<xs:complexType mixed="true“>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="training" type="xs:string"/>
<xs:element name="tdate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
eXtensible Stylesheet Language (XSL)
Introduction to XSL

• XSL stands for Extensible Stylesheet Language

• It is an XML-based style sheet language for XML documents

• XSL describes how the XML document should be displayed

• The XSL consists of three languages


• XSL Transformations (XSLT): an XML language for transforming
XML documents into other types of documents (for eg. HTML)
• XML Path Language (XPath): a non-XML language used by
XSLT, and also for selecting parts of an XML document
• XSL Formatting Objects (XSL-FO): an XML language for
specifying visual formatting of an XML document
Notes
• CSS – HTML Stylesheets
• XSL-XML Stylesheets
• XSLT - a language for transforming XML documents
• XPath - a language for navigating in XML documents
• XSL-FO - a language for formatting XML documents
• HTML pages use predefined tags, and these tags are
understood by the browsers. For example, <p> means a
paragraph and <b> means bold and so on.
• With XML, the tags are user-defined and the browsers
may not understand the meaning of these tags. For
example, a <table> tag could mean an HTML table or
maybe a piece of furniture. Because of the nature of XML,
there is no standard way to display an XML document.
Notes

– In order to display XML documents, it is necessary to have a


mechanism to describe how the document should be displayed.
One of these mechanisms is Cascading Style Sheets (CSS) and
the other one is XSL (eXtensible Stylesheet Language), which is
the preferred style sheet language of XML.

– CSS was primarily designed for styling HTML pages. It can also
be used to style XML pages where as XSL was designed
specifically to style XML pages and is much more sophisticated
than CSS
XSLT

• An important part of XSL

• A W3C Recommendation

• Uses XPath to navigate in XML documents

• Transforms XML documents into any text-based format


• HTML, plain text, rich text format (RTF), and Microsoft Word
• The most common transformation is from XML documents to
HTML documents

• Uses two documents for transformation


• an XML document containing actual data
• an XSL document (a style sheet with a .xsl extension)
Notes
• XSLT has become the most popular part of XSL because
it's relatively easy to use and it lets you transform XML
documents into other formats, such as HTML or plain text.

• XSLT is popular partly because by using it, you can


manipulate the data in XML documents without having to
write any software.

• Note that XSLT style sheets are also XML documents.


• XSL is a more general language that lets you format XML
in great detail.
Transforming XML by using XSLT

XSLT transformations can happen at three different


places:

•In the server - A server program, such as a .NET or JSP


can use XSLT to transform XML document and send it to
client

•In the client - A client program, such as browser can


perform XSLT transformations

•With a separate program - A number of standalone


programs are available to perform XSLT transformations
Notes

• Modern web browsers include an XSLT processor. So if a


browser is passed an XML document with an appropriate
XSL style sheet then it can transform the document to
HTML and display it appropriately.
• Internet Explorer fully supports XSLT 1.0 support
• Internet Explorer lets you perform client-side XSLT
transformations. This is done by connecting the XSLT style
sheet to the XML document by using an <?xml-stylesheet?
> processing instruction, like this:
• <?xml-stylesheet type="text/xsl" href=“movies.xsl"?>
• Using IE is probably the most accessible way to perform
XSLT transformations for most people
How does transformation happen?

•The XML source document is parsed into an XML source tree

•XPath is used to define templates that match parts of the source tree

•XSLT is used to transform the matched part and put the transformed
information into a result tree

•The result tree is output as a result document

•Parts of the source document that are not matched by the template
are copied unchanged
Notes

• The XML text document is read in and stored as a tree of nodes.

• The <xsl:template match="/"> template is used to select the


entire tree.

• The rules within the template are applied to the matching nodes,
thereby changing the structure of the XML tree. If there are
other templates, they must be called explicitly from the main
template.

• Unmatched parts of the XML tree are not changed.


• After the template is applied, the tree is written out again as a
text document.
Notes
How XSLT views XML Documents

• XSLT views an XML document as a tree of nodes. The tree


starts with the root node, and it branches out from that point.
The root node corresponds to the very beginning of the
document; it is not the same as the document element.
• Each distinct item in an XML document is considered a node
—comments, processing instructions, elements, even the text
inside elements. From XSLT's point of view, there are seven
types of nodes, Attribute, Comment, Element, Namespace,
Processing instruction (The text of the processing instruction
(excluding <? and ?>)), Root node (The very start of the
document, before even the document element), Text.
• To handle and search the various nodes in XML documents,
the XSLT specification defines a number of elements. It also
uses XPath to let you specify exactly what nodes you are
looking for
Understanding XPath

• Consider the XML document: XPath expressions are similar


to
movies.xml paths in a computer file system
<movieLibrary>
<movie>
/ represents the document
<title>Mad Max</title>
<director>George Miller</director>
</movie> /movieLibrary selects root
<movie> element
<title>Padosan</title>
<director>Jyoti Swaroop</director> /movieLibrary/movie selects
</movie> every movie element
</movieLibrary>
//director selects every actor
element, wherever it occurs
Notes

• XSLT uses XPath to find information in an XML document.


XPath is used to navigate through elements and attributes
in XML documents.

• / is the root node of the XML tree that represents the start
of the document . That is it does not refer to any specific
element.
Understanding XSLT

• <xsl:for-each select="//movie">
• loops through every movie element, everywhere in the document

• <xsl:value-of select="title"/>
• selects content of title element at current location

• <xsl:for-each select="//movie">
<xsl:value-of select="title"/>
</xsl:for-each>
• selects content of title element for each movie in the XML
document
Notes
• The XSLT <xsl:value-of select="XPath expression"/>
selects the contents of an element and adds it to the output
stream
• <xsl:value-of select=“title"/> selects the title child.
Alternative Xpath expression that would also work: ./title

• The XSLT <xsl:for-each select=“XPath expression”>


element allows you to do looping in XSLT. It can be used to
select every XML element of a specified node-set:

• Note: The value of the select attribute is an XPath


expression. An XPath expression works like navigating a
file system; where a forward slash (/) selects
subdirectories.
Steps for creating documents

1. Create an XML document movies.xml

2. Create an XSL style sheet file movies.xsl that describes how to


select elements from movies.xml and embed them into an HTML
page
a. This is done by intermixing HTML and XSL in movies.xsl file

3. Add the following line to movies.xml file to tell it to connect to the


style sheet movies.xsl for formatting information
<?xml-stylesheet type="text/xsl" href="movies.xsl"?>
Notes
• If we create an HTML fie, it should like:

• <html>
<head>
<title>Movie Titles and Directors</title>
</head>
<body>
<h2>Movie titles:</h2>
<ul>
<li>MAD MAX</li>
<li>Padosan</li>
</ul>
<h2>Movie directors:</h2>
<ul>
<li>George Miller</li>
<li>Jyoti Swaroop</li>
</ul>
</body>
</html>
Outline of the required XSL file

• An XSLT document has the .xsl extension


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html> ... </html>
</xsl:template>
</xsl:stylesheet>
• Begins with xml declaration followed by <xsl:stylesheet> element
• Contains one or more templates, such as:
<xsl:template match="/"> ... </xsl:template>
• And ends with </xsl:stylesheet>
Notes

• Since an XSL style sheet is an XML document itself, it


always begins with the XML declaration: <?xml
version="1.0" encoding=“UTF-8"?>.

• The root element that declares the document to be an


XSL style sheet is <xsl:stylesheet>

• In the <xsl:stylesheet> element, you associate the xsl


namespace with the URI "

• http://www.w3.org/1999/XSL/Transform ", which is the


official namespace for XSLT.
XSL Style Sheet - Example
movies.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<h2>Movie Collection</h2> Output
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Director</th></tr>
<xsl:for-each select="movieLibrary/movie">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="director"/></td></tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet> Observe here that XSL can rearrange the
data; the HTML result can present
information in a different order than the XML
Notes
• The XML document can be displayed by using an option
available in Netbeans
– Right click on the xml document.
– One of the options displayed is : XSL Transformation.
– Select the option.
– Specify XSL file name.
– Specify a name for the html file that will be generated.
– The result is displayed on the browser. The generated
HTML file will be stored at the destination you have
specified.
– You can also right click the XML document and open it
with the Internet Explorer. You can see the XML
document displayed as per your requirement.
XSLT <xsl:template> Element

• An XSL style sheet consists of one or more set of rules called


templates
• A template lets you match a node/nodes in the XML document
• It allows to specify what you want to do with the contained data
• The <xsl:template> element is used to build templates
• The match attribute associates a template with an XML element
• It also defines a template for the entire XML document
• Value of match attribute is an XPath expression
• Examples:
<xsl:template match="/"> …. </xsl:template>
<xsl:template match=“movieLibrary">
Notes

• The <xsl:template match="/"> chooses the root node, that


is the whole document.

• When the XSLT processor opens the document, it starts at


the root node and searches for templates that match the
children of the root node, which means that <xsl:template
match=“movieLibrary"> will match because
<movieLibrary> is a child of the root node.
A sample XML document
catalog.xml
<?xml version="1.0" encoding="ISO8859- <CD>
1" ?> <TITLE>Slumdog
<CATALOG> Millionaire</TITLE>
<CD> <ARTIST>Dev Patel</ARTIST>
<TITLE>Titanic</TITLE> <PRICE>Rs.100</PRICE>
<ARTIST>Leonardo di <YEAR>2009</YEAR>
Caprio</ARTIST> </CD>
<PRICE>Rs.300</PRICE> <CD>
<YEAR>1997</YEAR> <TITLE>Mungaru Male</TITLE>
</CD> <ARTIST>Ganesh</ARTIST>
<CD> <PRICE>Rs.175</PRICE>
<TITLE>Rab Ne Bana di Jodi</TITLE> <YEAR>2006</YEAR>
<ARTIST>Shahrukh Khan</ARTIST> </CD>
<PRICE>Rs.75</PRICE> <CD>
<YEAR>2008</YEAR> <TITLE>Jab We Met</TITLE>
</CD> <ARTIST>Shahid
<CD> Kapoor</ARTIST>
<TITLE>Ghajini</TITLE> <PRICE>Rs.50</PRICE>
<ARTIST>Amir Khan</ARTIST> <YEAR>2007</YEAR>
<PRICE>Rs.200</PRICE> </CD>
<YEAR>2008</YEAR> </CATALOG>
</CD>
Sorting with XSL

• Use xsl:sort and order attribute for sorting XML data

• For example:
<xsl:for-each select="CATALOG/CD" >
<xsl:sort select="ARTIST" order="descending"/>
sorts elements in descending order of ARTIST values
Notes
• <?xml version='1.0'?>
• <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
• <xsl:template match="/">
• <html>
• <body>
• <table border="2" bgcolor="yellow">
• <tr>
• <th>Title</th>
• <th>Artist</th>
• </tr>
• <xsl:for-each select="CATALOG/CD" >
• <xsl:sort select="ARTIST" order="descending"/>
• <tr>
• <td><xsl:value-of select="TITLE"/></td>
• <td><xsl:value-of select="ARTIST"/></td>
• </tr>
• </xsl:for-each>
• </table>
• </body>
• </html>
• </xsl:template>
• </xsl:stylesheet>
Filtering Output

• You can filter output by introducing filtering parameter to the select


value

• For example:
<xsl:for-each select="CATALOG/CD[PRICE>150]">
This will select only those CDs where PRICE is greater than
150

• Compound filtering parameters is also possible

• For example:
<xsl:for-each select="CATALOG/CD[YEAR>2005 and
PRICE>150]">
Notes
• <?xml version='1.0'?>
• <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
• <xsl:template match="/">
• <html>
• <body>
• <table border="2" bgcolor="yellow">
• <tr>
• <th>Title</th>
• <th>Artist</th>
• </tr>
• <xsl:for-each select="CATALOG/CD[YEAR>2005 and PRICE>150]">
• <tr>
• <td><xsl:value-of select="TITLE"/></td>
• <td><xsl:value-of select="ARTIST"/></td>
• </tr>
• </xsl:for-each>
• </table>
• </body>
• </html>
• </xsl:template>
• </xsl:stylesheet>
if condition

• Use if condition for matching an element’s value and obtain selective


display based on the result of if condition

<xsl:for-each select="CATALOG/CD">
<xsl:if test="PRICE > 160'">
<tr>
<td><xsl:value-of select="TITLE"/></td>
<td><xsl:value-of select="ARTIST"/></td>
</tr>
</xsl:if>
</xsl:for-each>

• Here, the values of TITLE and ARTIST are displayed based on result
of xsl:if match
Notes
• <?xml version='1.0'?>
• <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
• <xsl:template match="/">
• <html>
• <body>
• <table border="2" bgcolor="yellow">
• <tr>
• <th>Title</th>
• <th>Artist</th>
• </tr>
• <xsl:for-each select="CATALOG/CD">
• <xsl:if match=“PRICE > 160">
• <tr>
• <td><xsl:value-of select="TITLE"/></td>
• <td><xsl:value-of select="ARTIST"/></td>
• </tr>
• </xsl:if>
• </xsl:for-each>
• </table>
• </body>
• </html>
• </xsl:template>
• </xsl:stylesheet>
Choose, When and Otherwise

• The xsl:choose ... xsl:when ... xsl:otherwise construct is XML’s equivalent of


Java’s switch ... case ... default statement

<xsl:choose>
<xsl:when test="PRICE >100">
<td bgcolor="#ff0000"><xsl:value-of select="ARTIST"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="ARTIST"/></td>
</xsl:otherwise>
</xsl:choose>

• This code checks whether PRICE is greater than 150 and if true displays
ARTIST with a red background. Otherwise, background color remains
unchanged
Notes
• <?xml version='1.0'?>
• <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
• <xsl:template match="/">
• <html>
• <body>
• <table border="2" bgcolor="yellow">
• <tr>
• <th>Title</th>
• <th>Artist</th>
• </tr>
• <xsl:for-each select="CATALOG/CD">
• <tr>
Notes (Contd.).
• <td><xsl:value-of select="TITLE"/></td>
• <xsl:choose>
• <xsl:when match=".[PRICE > 150]">
• <td bgcolor="#ff0000"><xsl:value-of select="ARTIST"/></td>
• </xsl:when>
• <xsl:otherwise>
• <td><xsl:value-of select="ARTIST"/></td>
• </xsl:otherwise>
• </xsl:choose>
• </tr>
• </xsl:for-each>
• </table>
• </body>
• </html>
• </xsl:template>
• </xsl:stylesheet>
What is Xquery?

•XQuery is a language which is used to query XML data


•We have XQuery for XML in the same way that we have
SQL for databases
•It is built on XPath expressions
•XQuery is a World Wide Web Consortium (W3C)
recommendation
Summary
In this module, you were able to:
•Know what is AJAX ?
•Understand web Standards used in AJAX
•Understand AJAX Advantages
•Get to know how Ajax works
•Implement different Properties
•Send request to the server
•Develop simple suggest application using AJAX
•Develop application to communicate with database using AJAX and
DAO
•Develop application through which a JSP page could be returned as
AJAX response
Summary (Contd.).

•Describe the use of XML Schema and limitations of DTDs


•Describe structure of XML Schema
•Create Schema Definition Files
•Define attributes in XSD
•Apply restrictions on values and set of values
•Describe the use of XSL
•Transform an XML document by using XSLT
•Work with XPATH expressions
•Create XSL Style sheets
•Use XSLT elements
•Sort and filter XML documents
References
1. w3schools.com (2012). AJAX Introduction. Retrieved April 30, 2012,
from, http://www.w3schools.com/ajax/default.asp

2. Greg Murray (2005). Asynchronous JavaScript Technology and


XML(Ajax) With the Java Platform. Retrieved April 30, 2012, from,
http://www.oracle.com/technetwork/articles/javaee/ajax-135201.html

3. Adaptive path (2012). Ajax: A New Approach to Web Applications.


Retrieved May 2, 2012, from, http
://www.adaptivepath.com/ideas/ajax-new-approach-web-applications
References (Contd.).

4. Karl Aberer, EPFL-SSC, Laboratoire de systèmes


d'informations rèpartis(2004). Conception of Information
Systems Part 1: Data Representation - XML. Retrieved
May 11, 2012 from
http://lsirwww.epfl.ch/courses/cis/2004ss/part1-XML.pdf

5. Liam Quin, W3C XSL Working Group(2011). The


Extensible Stylesheet Language Family (XSL). Retrieved
May 11, 2012 from http://www.w3.org/Style/XSL/
Thank You

Potrebbero piacerti anche