Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Module 4
Agenda
1 Introduction to Ajax
4 XML Schema - I
5 XML Schema - II
• 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)
• Autocompletion
• Load on demand
• 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
Note:
• As both the request and response happen simultaneously,
it appears to the user that the page has not been
refreshed
Synchronous
• After each user activity the request is sent to the server for
processing
Asynchronous
Notes
• The above diagram shows asynchronous request-
response activities in a ajax web application model
• 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
Example:
xmlHttp.onreadystatechange=function(){
//some code for handling server response}
• The onreadystatechange property stores an empty function inside it
Notes
State Description
• 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.
Example:
xmlHttp.open("GET",“server-side-component.jsp",true);
xmlHttp.send(null);
Notes
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
• 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
Create a web application that takes new entry for department and
check if the department is already entered in the database
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";
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
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
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
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
*/
• }
• 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
response.sendRedirect("ShowEmployees.jsp");
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
}
Notes
•Consider a simple DTD called song.dtd and let us write the schema
song.xsd
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>
http://www.w3.org/2001/XMLSchema http://www.music.org/album
(XMLSchema Namespace) (targetNamespace)
<?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
<firstname>Anny</firstname>
<age>19</age>
<birthdate>1990-05-15</birthdate>
<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
• 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
• 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
• Example:
• <xs:attribute name=“title" type="xs:string" use="required“ />
The “use” attribute
• Examples:
<xs:attribute name=“title" type="xs:string" use="required“/>
<xsd:attribute name=“emailid" type="xsd:string" use="optional“ />
The “value” attribute
• Examples:
<xsd:attribute name="year" type="xsd:int" use="fixed"
value="2007“ />
<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>
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
<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.).
– 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
• A W3C Recommendation
•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
•Parts of the source document that are not matched by the template
are copied unchanged
Notes
• 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.
• / 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
• <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
• 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
• For example:
<xsl:for-each select="CATALOG/CD[PRICE>150]">
This will select only those CDs where PRICE is greater than
150
• 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
<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
<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?