Professional Documents
Culture Documents
XML
Introduction
• An XML document is one that follows certain syntax rules (most of which we
followed for XHTML)
The Difference Between XML and HTML
XML is not a replacement for HTML. XML and HTML were designed with different
goals:
XML was designed to transport and store data, with focus on what data is. HTML was
designed to display data, with focus on how data looks.
HTML is about displaying information, while XML is about carrying information.
XML Syntax
– Markup
» The entities lt, gt, amp, apos, and quot are recognized
in every XML document.
• Comments
– End -->
• CDATA section
– Within comments
– Three types
• Start, e.g. <message>
XML Documents
• Many XML parsers (software for reading/writing XML documents) use tree
representation internally
• Valid names and content for an XML vocabulary can be specified using
– Natural language
• XML declaration
– Minimal example:
XML Namespaces
Default namespace for elements of a document is specified using a form of the xmlns
attribute:
• Combination of
– (X)HTML
– XML
– CSS
– JavaScript
function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}
function SayHello(){
var usr=window.document.f1.username.value;
var rnd = Math.random();
var url="sayhello.php?id="+rnd +"&usr="+usr;
postRequest(url);
}
</script>
</head>
<body>
<h1 align="center"><font color="#000080">Simple Ajax
Example</font></h1>
<p align="center"><font color="#000080">Enter your name and
then press
"Say Hello Button"</font></p>
<form name="f1">
<p align="center"><font color="#000080">
Enter your name: <input type="text" name="username"
id="username">
<input value="Say Hello" type="button"
onclick='JavaScript:SayHello()' name="showdate"></font></p>
</form>
<div id=result></div>
</body>
</html>
Java-based DOM
Introduction to parsers
In a compiler, a parser is the module that reads and interprets the programming
language.
In XML, a parser is a software component that sits between the application and the
XML files.
Tree-based parsers
These map an XML document into an internal tree structure, and then allow an
application to navigate that tree.
Event-based
An event-based API reports parsing events (such as the start and end of elements)
directly to the application through callbacks.
– http://www.megginson.com/SAX/index.html
– An event-based interface
• Advantages
– Simple to use
– Very fast (not doing very much before you get the tags and data)
• Disadvantages
– Not doing very much for you -- you have to do everything yourself
– Not useful if you have to dynamically modify the document once it’s in
memory (since you’ll have to do all the work to put it in memory yourself!)
XML Processing: DOM
– http://www.w3.org/DOM/
– An object-based interface
– DOM interface defines methods for accessing and modifying the tree
• Advantages
– Useful for querying (I.e. looking for data) that depends on the tree structure
[element.childNode("2").getAttributeValue("boobie")]
• Disadvantages
– Can be slow (needs to produce the tree), and may need lots of memory
SAX (the Simple API for XML) is an event-based parser for xml documents.
The parser tells the application what is in the document by notifying the
application of a stream of parsing events.
SAX History
Advantages
Simple to use
Very fast (not doing very much before you get the tags and data)
Disadvantages
Not doing very much for you -- you have to do everything yourself
Not useful if you have to dynamically modify the document once it’s in
memory (since you’ll have to do all the work to put it in memory yourself!)
In event-based transformation a parser does not construct a parse tree, but reads
the source document in serial order and outputs information of any elements
found, or responds via API (Application Programming Interface) to the requests
related to the events the parser encounters (of which one is an element
occurrence).
A parse tree offers us the means to perform more complex transformations and
filtering because with it we have a better control over the output of a
transformation
A family of languages called eXtensible Stylesheet Language (XSL) which allows one to
describe how files encoded in the XML standard are to be formatted or transformed.
XSL processors do parses the XML source and tries to find out the matching template
rule. If it do find it, then the instructions inside the matching template is evaluated.
• Components of XSL:
– XML Path Language (XPath): used in many XSL attribute values (ex:
child::message)
• Similar to DOM tree in that nodes have different types (element, text,
comment, etc.)
• One of the children of the document root, called the document element, is
the root element of the XML document
Node test:
• A location step can have one or more predicates that act as filters:
o Ex: para/strong/emph
• An absolute location path begins with / and uses the document root as the
context node
o Ex: /body/para represents all para nodes that are children of body
which is child of document root
• A relative location path does not begin with / and uses an element
determined by the application (e.g., XSLT) as the context node
o Ex: body/para
XSLT Browsers
Nearly all major browsers have support for XML and XSLT.
Mozilla Firefox
As of version 1.0.2, Firefox has support for XML and XSLT (and CSS).
Mozilla includes Expat for XML parsing and has support to display XML + CSS. Mozilla
also has some support for Namespaces.
Mozilla is available with an XSLT implementation.
Netscape
As of version 8, Netscape uses the Mozilla engine, and therefore it has the same XML /
XSLT support as Mozilla.
Opera
As of version 9, Opera has support for XML and XSLT (and CSS). Version 8 supports
only XML + CSS.
Internet Explorer
As of version 6, Internet Explorer supports XML, Namespaces, CSS, XSLT, and XPath.
Version 5 is NOT compatible with the official W3C XSL Recommendation.
XML in Browsers
Feature Browser
Netscape 6 Internet Internet
Preview Opera 4 beta 3 Explorer Explorer
Release 1 5.0/Mac 5.5/Win
XML display
Everything as Structured Structured
without style Everything as inline
inline presentation presentation
sheet
Uses W3C PI
to connect yes yes yes yes
style sheets
display:inline yes yes yes yes
display:block yes yes yes yes
display:none yes yes yes yes
display:list yes (numbering yes (numbering
yes no
(and list-item) issues) issues)
yes (some
display:table
yes interactions with no no
(and contents)
embedded HTML)
yes (3/3/98 through CSS
XLink support no no
draft) extensions
yes (using HTML
yes (using html
yes (using 4.0 URI as
Embedded prefix, some
HTML 4.0 namespace, some yes (using html
HTML problems with
URI as problems with prefix)
support HTML a
namespace) HTML img
elements)
elements)
yes, based on yes, based on
no (in no (no old draft (new old draft (new
XSLT support
development) announcements) processor in processor in
development) development)
Release status Preview Beta Shipping Preview Release
Release
JSP Introduction:
A text-based document capable of returning both static and dynamic content to a client
Browser
JavaServer Pages (JSP) is a technology based on the Java language and enables the
development of dynamic web sites. JSP was developed by Sun Microsystems to allow
server side development.
JSP files are HTML files with special Tags containing Java source code that provide the
dynamic content.
The following shows the Typical Web server, different clients connecting via the Internet
to a Web server.
In this example, the Web server is running on Unix and is the very popular Apache Web
server
The following diagram shows a web server that supports JSP files. Notice that the web
server also is connected to a database.
JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet
engine dynamically generates the HTML and sends the HTML output to the client?s web
browser.
• JSP technology provides a way to combine the worlds of HTML and Java servlet
programming.
• JSP specs are built on the Java Servlet API.
• JSP supports two different styles for adding dynamic content to web pages:
–JSP pages can embed actual programming code (typically Java)
–JSP supports a set of HTML-like tags that interact with Java objects on the server
(without the need for raw Java code to appear in the page).
JSP architecture
JSPs are essential an HTML page with special JSP tags embedded.
These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or
.html. The JSP engine parses the .jsp and creates a Java servlet source file.
It then compiles the source file into a class file,this is done the first time and this why the
JSP is probably slower the first time it is accessed.
Any time after this the special compiled servlet is executed and is therefore returns faster.
Steps required for a JSP request:
• When the user goes to a JSP page web browser makes the request via internet.
• Web server recognises the .jsp file and passes the JSP file to the JSP Servlet
Engine.
• If the JSP file has been called the first time,the JSP file is parsed,otherwise Servlet
is instantiated.
• The next step is to generate a special Servlet from the JSP file. All the HTML
required is converted to println statements.
-> Destruction
1. JSP Page Translation:
A java servlet file is generated from the JSP source file. This is the first step in its tedious
multiple phase life cycle. In the translation phase, the container validates the syntactic
correctness of the JSP pages and tag files. The container interprets the standard directives
and actions, and the custom actions referencing tag libraries used in the page.
The generated java servlet file is compiled into a java servlet class.
Note: The translation of a JSP source page into its implementation class can happen at
any time between initial deployment of the JSP page into the JSP container and the
receipt and processing of a client request for the target JSP page.
3. Class Loading:
The java servlet class that was compiled from the JSP source is loaded into the container.
4. Execution phase:
In the execution phase the container manages one or more instances of this class in
response to requests and other events. The interface JspPage contains jspInit() and
jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP
pages serving HTTP requests and this interface contains _jspService().
5. Initialization:
jspInit() method is called immediately after the instance was created. It is called only
once during JSP life cycle.
6. _jspService() execution:
This method is called for every request of this JSP during its life cycle. This is where it
serves the purpose of creation. Oops! it has to pass through all the above steps to reach
this phase. It passes the request and the response objects. _jspService() cannot be
overridden.
7. jspDestroy() execution:
This method is called when this JSP is destroyed. With this call the servlet serves its
purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.
JSP Tags
• Declaration tag
• Expression tag
• Directive tag
• Scriptlet tag
• Action tag
Declaration tag
A semicolon ( ; ) does not appear at the end of the code inside the tag.
Directive tag
Direcitve tag ( <%@ directive...>)
A JSP directive gives special information about the page to JSP Engine.
Directives do not produce any visible output when the page is requested but change the
way the JSP Engine processes the page.
e.g.,you can make session data unavailable to a page by setting a page directive (session)
to false.
1. Page Directive
This directive has 11 optional attributes that provide the JSP Engine with special
processing information. The 11 different attributes with a brief description is decribe in
table given below:
<%@ page language =
Language Which language the file uses.
"java" %>
Superclass used by the JSP engine for the <%@ page extends =
Extends
translated Servlet. "com.taglib... %>
Import all the classes in a java package into the
<%@ page import =
import current JSP page. This allows the JSP page to use
"java.util.*" %>
other java classes.
session oes the page make use of sessions. By default all Default is set to true.
JSP pages have session data available. There are
performance benefits to switching session to false.
Controls the use of buffered output for a JSP page. <%@ page buffer =
buffer
Default is 8kb "none" %>
<%@ page autoFlush =
autoFlush Flush output buffer when full.
"true" %>
Can the generated Servlet deal with multiple
isThreadSafe requests? If true a new thread is started so requests
are handled simultaneously.
<%@ page info =
Developer uses info attribute to add
"visualbuilder.com test
info information/document for a page. Typically used
page,copyright 2001. "
to add author,version,copyright and date info.
%>
Different page to deal with errors. Must be URL to <%@ page errorPage =
errorPage
error page. "/error/error.jsp" %>
This flag is set to true to make a JSP page a special
IsErrorPage Error Page. This page has access to the implicit
object exception (see later).
Set the mime type and character set of
contentType
the JSP.
2. Include directive
It allows a JSP developer to include contents of a file inside another. Typically include
files are used for navigation,headers,tables and footers that are common to multiple
pages.
This includes the html from privacy.html found in the include directory into the current
jsp page.
<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>
Custom tag were introduced in JSP 1.1 and allow JSP developer to hide complex server
side code from web designers
Scriptlet tag
<%
String username = "visualbuilder" ;
out.println ( username ) ;
%>
Action tag
There are three main roles of action tag :
1) It enable the use of server side Javabeans
2) It transfer control between pages
3) Browser independent support for
applets.
Javabeans
The JSP page can call these method so can leave most of the code in these Javabeans. For
example,if you wanted to make a feedback form that automatically sent out an email.
By having a JSP page with a form,when the visitor presses the submit button this send
the details to a Javabean that sends out the email.
This way there would be no code in the JSP page dealing with sending emails (JavaMail
API) and your Javabeans could be used in another page (promoting reuse).
• Java classes that can be easily reused and composed together into an application
• Any Java class that follows certain design conventions can be a JavaBeans
component
o properties of the class
o public methods to get and set properties
• Within a JSP page, you can create and initialize beans and get and set the values of
their properties
• JavaBeans can contain business logic or data base access logic
Example: JavaBeans
<html>
<body>
<!–Instantiate the Counter bean -->
<jsp:useBean id=“counter”scope=“session”class=“Counter”/>
<!–Set the bean’s count property -->
<jsp:setProperty name=“counter”property=“count”param=“count”/>
<!--Display output to html -->
Count from scriptlet code: <%= counter.getCount() %>
<br>
<!–Get the bean’s count property -->
Count from getProperty: <jsp:getProperty
name=“counter”property=“count />
<br>
</body>
</html>
JDBC and JSP Concepts
JDBC Java Database Connectivity interface is a pure Java API used to execute SQL
statements.
Four Basic JDBC interactions:
1.Open a connection to the database
2.Execute a SQL statement
3.Process the result set
4.Close the connection to the database
Import java.sql.*;
•Step 1 Open a connection to the ODBC DB
While ( rs.next() ) {
System.out.println(“Name = “+ rs.getString(“CustomerName”) );
}
•Step 4 Close the connection
rs.close();
con.close();
Four JDBC driver types:
Model-view-controller
The controller object is master Servlet. Every request goes through the controller who
retrieves the necessary model object. The model may interact with other business
entities such as databases or Enterprise Java Beans (EJB). The model object sends
the output results back to the controller. The controller takes the results and places it
inside the web browser session and forwards a redirect request to a particular Java
Server Page. The JSP, in the case, is the view.
The controller has to bind a model and a view, but it could be any model and associated
any view. Therein lies the flexibility and perhaps an insight to developing a very
advanced dynamic controller that associates models to a view.
The prior sections have concentrated on their being one controller, one model, and one
view. In practice, multiple controllers may exist - but only one controls a section of the
application at a time. For example, the administrator's functions may be controlled by one
controller and the main logic controlled by another. Since only one controller can be in
control at a given time, they must communicate. There may also be multiple models - but
the controller takes the simplified view representation and maps it to the models
appropriately and also translates that response back to the view. The view never needs to
know how the logic is implemented.
Model-View Controller Architecture:
The following steps are executed when the user submits the request.
1. The Controller Servlet handles the user’s request. (This means the hyperlink in the
JSP should point to the controller servlet).
2. The Controller Servlet then instantiates appropriate JavaBeans based on the
request parameters (and optionally also based on session attributes).
3. The Controller Servlet then by itself or through a controller helper communicates
with the middle tier or directly to the database to fetch the required data.
4. The Controller sets the resultant JavaBeans (either same or a new one) in one of
the following contexts – request, session or application.
5. The controller then dispatches the request to the next view based on the request
URL.
6. The View uses the resultant JavaBeans from Step 4 to display data. Note that there
is no presentation logic in the JSP. The sole function of the JSP in Model 2
architecture is to display the data from the JavaBeans set in the request, session or
application scopes.
Advantage of MVC
Using MVC you can have as many controller servlets in your web application. In fact
you can have one Controller Servlet per module.
However there are several advantages of having a single controller servlet for the entire
web application. In a typical web application, there are several tasks that you want to do
for every incoming request. For instance, you have to check if the user requesting an
operation is authorized to do so.
You also want to log the user’s entry and exit from the web application for every request.
You might like to centralize the logic for dispatching requests to other views.
The list goes on. If you have several controller servlets, chances are that you have to
duplicate the logic for all the above tasks in all those places.
A single controller servlet for the web application lets you centralize all the tasks in a
single place.