lecturer notes on it 2353 unit iv

47
UNIT IV Representing Web Data: XML-Documents and Vocabularies-Versions and Declaration- Namespaces JavaScript and XML: Ajax-DOM based XML processing Event-oriented Parsing: SAX-Transforming XML Documents-Selecting XML Data:XPATH-Templatebased Transformations: XSLT-Displaying XML Documments in Browsers- Case Study- Related Technologies. Separating Programming and Presentation: JSP Technology Introduction-JSP and Servlets- Running JSP Applications Basic JSP-JavaBeans Classes and JSP- Tag Libraries and Files-Support for the Model-View-Controller Paradigm-Case Study-Related Technologies. XML Introduction XML documents look similar to HTML documents XML is extensible, tags are not predefined and limited as in HTML You can define your own tags in a DTD or XML schema XML is stored in plain text, making it software and hardware independent Legal characters are those of Unicode and ISO/IEC 10646. XML does not DO anything! It structures and describes information for storage or transmission XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags

Upload: shankar

Post on 28-Mar-2015

564 views

Category:

Documents


12 download

TRANSCRIPT

Page 1: Lecturer Notes on IT 2353 UNIT IV

UNIT IV

Representing Web Data: XML-Documents and Vocabularies-Versions and Declaration- Namespaces JavaScript and XML: Ajax-DOM based XML processing Event-oriented Parsing: SAX-Transforming XML Documents-Selecting XML Data:XPATH-Templatebased Transformations: XSLT-Displaying XML Documments in Browsers-Case Study- Related Technologies. Separating Programming and Presentation: JSP Technology Introduction-JSP and Servlets-Running JSP Applications Basic JSP-JavaBeans Classes and JSP-Tag Libraries and Files-Support for the Model-View-Controller Paradigm-Case Study-Related Technologies.

XML

Introduction

• XML documents look similar to HTML documents• XML is extensible, tags are not predefined and limited as in HTML

– You can define your own tags in a DTD or XML schema• XML is stored in plain text, making it software and hardware independent

– Legal characters are those of Unicode and ISO/IEC 10646.• XML does not DO anything!

– It structures and describes information for storage or transmission

XML stands for EXtensible Markup Language

• XML is a markup language much like HTML

• XML was designed to carry data, not to display data

• XML tags are not predefined. You must define your own tags

• XML is designed to be self-descriptive

• XML is a W3C Recommendation

Example XML document:

• An XML document is one that follows certain syntax rules (most of which we followed for XHTML)

Page 2: Lecturer Notes on IT 2353 UNIT IV

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

• An XML document consists of

– Markup

• Tags, which begin with < and end with >

• References, which begin with & and end with ;

Page 3: Lecturer Notes on IT 2353 UNIT IV

– Character, e.g. &#x20;

– Entity, e.g. &lt;

» The entities lt, gt, amp, apos, and quot are recognized in every XML document.

» Other XHTML entities, such as nbsp, are only recognized in other XML documents if they are defined in the DTD

– Character data: everything not markup

• Comments

– Begin with <!--

– End -->

– Must not contain –

• CDATA section

– Special element the entire content of which is interpreted as character data, even if it appears to be markup

– Begins with <![CDATA[

– Ends with ]]> (illegal except when ending CDATA)

• < and & must be represented by references except

– When beginning markup

– Within comments

– Within CDATA sections

• Element tags and elements

– Three types

Page 4: Lecturer Notes on IT 2353 UNIT IV

• Start, e.g. <message>

• End, e.g. </message>

• Empty element, e.g. <br />

– Start and end tags must properly nest

– Corresponding pair of start and end element tags plus everything in between them defines an element

– Character data may only appear within an element

XML Documents

• A well-formed XML document

– follows the XML syntax rules and

– has a single root element

• Well-formed documents have a tree structure

• Many XML parsers (software for reading/writing XML documents) use tree representation internally

• An XML document is written according to an XML vocabulary that defines

– Recognized element and attribute names

– Allowable element content

– Semantics of elements and attributes

• XHTML is one widely-used XML vocabulary

• Another example: RSS (rich site summary)

• Valid names and content for an XML vocabulary can be specified using

– Natural language

– XML DTDs (Chapter 2)

– XML Schema (Chapter 9)

Page 5: Lecturer Notes on IT 2353 UNIT IV

• If DTD is used, then XML document can include a document type declaration:

• XML declaration

– Minimal example:

– If included, < must be very first character of the document

– To override default UTF-8/UTF-16 character encoding, include encoding declaration following version:

XML Namespaces

• XML Namespace: Collection of element and attribute names associated with an XML vocabulary

• Namespace Name: Absolute URI that is the name of the namespace

– Ex: http://www.w3.org/1999/xhtml is the namespace name of XHTML 1.0

Default namespace for elements of a document is specified using a form of the xmlns attribute:

• Another form of xmlns attribute known as a namespace declaration can be used to associate a namespace prefix with a namespace name:

Page 6: Lecturer Notes on IT 2353 UNIT IV

• Example use of namespace prefix:

• In a namespace-aware XML application, all element and attribute names are considered qualified names

– A qualified name has an associated expanded name that consists of a namespace name and a local name

– Ex: item is a qualified name with expanded name <null, item>

– Ex: xhtml:a is a qualified name with expanded name <http://www.w3.org/1999/xhtml, a>

JavaScript and XML

• JavaScript DOM can be used to process XML documents

• JavaScript XML Dom processing is often used with XMLHttpRequest

– Host object that is a constructor for other host objects

– Sends an HTTP request to server, receives back an XML document

• Ajax: Asynchronous JavaScript and XML

• Combination of

– (X)HTML

– XML

– CSS

Page 7: Lecturer Notes on IT 2353 UNIT IV

– JavaScript

– JavaScript DOM (HTML and XML)

– XMLHttpRequest in ansynchronous mode

Asynchronous JavaScript and XML (AJAX) is an umbrella term for a collection of Web development technologies used to create interactive Web applications, mostly W3C standards.

XHTML – a stricter, cleaner rendering of HTML into XML.

CSS for marking up and adding styles.

The Javascript Document Object Model (DOM) which allows the content, structure and style of a document to be dynamically accessed and updated.

The XMLHttpRequest object which exchanges data asynchronously with the Web server reducing the need to continually fetch resources from the server.

Since data can be sent and retrieved without requiring the user to reload an entire Web page, small amounts of data can be transferred as and when required. Moreover, page elements can be dynamically refreshed at any level of granularity to reflect this. An AJAX application performs in a similar way to local applications residing on a user’s machine, resulting in a user experience that may differ from traditional Web browsing.

How AJAX Works

Page 8: Lecturer Notes on IT 2353 UNIT IV

Example for Ajax:

<html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function postRequest(strURL) {

var xmlHttp; if (window.XMLHttpRequest) { // Mozilla, Safari, ...

var xmlHttp = new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} xmlHttp.open('POST', strURL, true); xmlHttp.setRequestHeader('Content-Type',

'application/x-www-form-urlencoded'); xmlHttp.onreadystatechange = function() {

if (xmlHttp.readyState == 4) { updatepage(xmlHttp.responseText); } }

xmlHttp.send(strURL); }

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">&nbsp;

Enter your name: <input type="text" name="username" id="username">

<input value="Say Hello" type="button" onclick='JavaScript:SayHello()' name="showdate"></font></p>

<div id="result" align="center"></div>

</form><div id=result></div>

</body></html>

Page 9: Lecturer Notes on IT 2353 UNIT IV

Java-based DOM

• Java DOM API defined by org.w3c.dom package

• Semantically similar to JavaScript DOM API, but many small syntactic differences

– Nodes of DOM tree belong to classes such as Node, Document, Element, Text

– Non-method properties accessed via methods

• Ex: parentNode accessed by calling getParentNode()

• Methods such as getElementsByTagName() return instance of NodeList

– getLength() method returns # of items

– item() method returns an item

Introduction to parsers

The word parser comes from compilers

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.

It reads a text-formatted XML file or stream and converts it to a document to be manipulated by the application.

Tree-based parsers

Page 10: Lecturer Notes on IT 2353 UNIT IV

These map an XML document into an internal tree structure, and then allow an application to navigate that tree.

Ideal for browsers, editors, XSL processors.

Event-based

An event-based API reports parsing events (such as the start and end of elements) directly to the application through callbacks.

The application implements handlers to deal with the different events

XML Processing: SAX

SAX: Simple API for XML

– http://www.megginson.com/SAX/index.html

– An event-based interface

– Parser reports events whenever it sees a tag/attribute/text node/unresolved external entity/other

– Programmer attaches “event handlers” to handle the event

Advantages

– Simple to use

– Very fast (not doing very much before you get the tags and data)

– Low memory footprint (doesn’t read an XML document entirely into memory)

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

Page 11: Lecturer Notes on IT 2353 UNIT IV

DOM: Document Object Model

– http://www.w3.org/DOM/

– An object-based interface

– Parser generates an in-memory tree corresponding to the document

– DOM interface defines methods for accessing and modifying the tree

Advantages

– Very useful for dynamic modification of, access to the tree

– Useful for querying (I.e. looking for data) that depends on the tree structure [element.childNode("2").getAttributeValue("boobie")]

– Same interface for many programming languages (C++, Java, ...)

Disadvantages

– Can be slow (needs to produce the tree), and may need lots of memory

– DOM programming interface is a bit awkward, not terribly object oriented

DOM Parser Processing Model

Page 12: Lecturer Notes on IT 2353 UNIT IV

SAX

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.

Application then processes those events to act on data.

SAX History

SAX 1.0 was released on May 11, 1998.

SAX is a common, event-based API for parsing XML documents, developed as a collaborative project of the members of the XML-DEV discussion under the leadership of David Megginson.

Advantages

Simple to use

Very fast (not doing very much before you get the tags and data)

Low memory footprint (doesn’t read an XML document entirely into memory)

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!)

Transforming XML Documents

A document can be transformed either manually or by using a program.

A simple transformation can be done by using the find-replace function in text editor. When there are many documents to transform, or when the transformation is more complex, you can use transformation languages and/or programs based on them for the task.

There are two basic techniques used for SGML (Standard Generalized Markup Language) and XML transformations.

Page 13: Lecturer Notes on IT 2353 UNIT IV

event-based mapping and tree-based mapping.

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).

An overview of document transformation techniques.

Event-based mapping technique Tree-based mapping technique

Examples of languages

SAX-Simple API for XML

Omnimark language/program

DOM (document object model) — API

Balise language/program

XSLT language

Pros/cons.

fast, uses computing resources efficiently

does not give very good control over schema (dtd, grammar) of an output document

constructing a parse tree and holding it in memory takes resources

good control over schema of an output documen

best suited when the transformation needs are complex (context transformations)

TABLE : presents an overview of differences between event-based and tree-based transformations

When using the tree-based mapping formalism a parser constructs a parse tree of the source document, and a transformation program can 'navigate' on source

Page 14: Lecturer Notes on IT 2353 UNIT IV

document structure, simultaneously defining transformations or filtering content from the source document to the output document.

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

Transforming XML to XML

Transforming the XML document

<?xml version="1.0"?><persons> <person username="MP123456"> <name>John</name> <family_name>Smith</family_name> </person><person username="PK123456"> <name>Morka</name> <family_name>Ismincius</family_name> </person></persons>

Page 15: Lecturer Notes on IT 2353 UNIT IV

By applying the XSLT transform:

<?xml version="1.0"?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"><xsl:output method="xml" indent="yes"/> <xsl:template match="/"><transform><xsl:apply-templates/></transform></xsl:template><xsl:template match="person"><record><username><xsl:value-of select="@username" /></username><name><xsl:value-of select="name" /></name></record> </xsl:template></xsl:stylesheet>

Results in a new XML document, having another structure: <?xml version="1.0" encoding="UTF-8"?><transform> <record> <username>MP123456</username> <name>John</name> </record> <record> <username>PK123456</username> <name>Morka</name> </record> </transform>

Page 16: Lecturer Notes on IT 2353 UNIT IV

XSL

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.

There are three languages in the family: XSL Transformations (XSLT): an XML language for transforming XML

documents XSL Formatting Objects (XSL-FO): an XML language for specifying the visual

formatting of an XML document

the XML Path Language (XPath): For addressing the parts of an XML document a non-XML language used by XSLT, and also available for use in non-XSLT contexts.

The XSL Templates

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.

Page 17: Lecturer Notes on IT 2353 UNIT IV
Page 18: Lecturer Notes on IT 2353 UNIT IV

• Components of XSL:

– XSL Transformations (XSLT): defines XSL namespace elements and attributes

– XML Path Language (XPath): used in many XSL attribute values (ex: child::message)

– XSL Formatting Objects (XSL-FO): XML vocabulary for defining document style (print-oriented)

XPath

XSLT Example Program:

<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <tr> <td>.</td> <td>.</td> </tr> </table> </body> </html> </xsl:template> </xsl:stylesheet>

Page 19: Lecturer Notes on IT 2353 UNIT IV

XPath operates on a tree representation of an XML document

• Similar to DOM tree in that nodes have different types (element, text, comment, etc.)

• Unlike DOM, attributes are also nodes in the XPath tree

• Root of XPath tree called document root

• One of the children of the document root, called the document element, is the root element of the XML document

Location path: expression representing one or more XPath tree nodes

• / represents document root

• child::message is an example of a location step and has two parts:

Node test:

o Name test: qualified name representing an element (or attribute, for

attribute axis) type

Example: child::message uses a name test

May use * as wildcard name test

Page 20: Lecturer Notes on IT 2353 UNIT IV

o Node-type test:

text(): true if node is a text node

comment(): true if node is a comment node

node(): true of any node

• A location step can have one or more predicates that act as filters:

• A location path is one or more location steps separated by /

o Ex: child::para/child::strong (or just para/strong)

o Ex: para/strong/emph

Page 21: Lecturer Notes on IT 2353 UNIT IV

• 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

o Ex: / represents list consisting only of the 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.

Page 22: Lecturer Notes on IT 2353 UNIT IV

XML in Browsers

Feature Browser

Netscape 6 Preview

Release 1Opera 4 beta 3

Internet Explorer 5.0/Mac

Internet Explorer 5.5/Win

XML display without style sheet

Everything as inline

Everything as inlineStructured presentation

Structured presentation

Uses W3C PI to connect style sheets

yes yes yes yes

display:inline yes yes yes yes

display:block yes yes yes yes

display:none yes yes yes yes

display:list (and list-item)

yesyes (numbering issues)

yes (numbering issues)

no

display:table (and contents)

yesyes (some interactions with embedded HTML)

no no

XLink supportyes (3/3/98 draft)

through CSS extensions

no no

Embedded HTML support

yes (using HTML 4.0 URI as namespace)

yes (using HTML 4.0 URI as namespace, some problems with HTML img elements)

yes (using html prefix, some problems with HTML a elements)

yes (using html prefix)

XSLT supportno (in development)

no (no announcements)

yes, based on old draft (new processor in development)

yes, based on old draft (new processor in development)

Release status Preview Beta Shipping Preview

Page 23: Lecturer Notes on IT 2353 UNIT IV

Release Release

JSP Introduction:

A text-based document capable of returning both static and dynamic content to a clientBrowser

• Static content and dynamic content can be intermixed• Static content

o HTML, XML, Text• Dynamic content

o Java codeo Displaying properties of JavaBeanso Invoking business logic defined in Custom tags

• A technolgy used to create dynamic HTML on the server side• Direct extension of Java Servelets• JSP engine is a servlet with extension *.jsp• Java based technology that simplifies the developing of dynamic web sites• JSPpages are HTML pages with embedded code that allows to access data from

Java code running on the server• JSPprovides separation of HTML presentation logic from the application logic.

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

Page 24: Lecturer Notes on IT 2353 UNIT IV

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:

Page 25: Lecturer Notes on IT 2353 UNIT IV

–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 built on top of SUN Microsystems' servlet technology.

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.

Page 26: Lecturer Notes on IT 2353 UNIT IV

Steps required for a JSP request:

When the user goes to a JSP page web browser makes the request via internet.

JSP request gets sent to the Web server.

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.

The Servlet source code is compiled into a class.

The Servlet is instantiated,calling the init and service methods.

HTML from the Servlet output is sent via the Internet.

HTML results are displayed on the user's web browser

JSP’s life cycle

• JSP page (MyFirstJSP.jsp)

-> Translated to Servlet (MyFirstJSP.servlet)

-> Compiled to class (MyFirstJSP.class)

-> Loaded into memory (Initialization)

-> Execution (repeats)

-> Destruction

Page 27: Lecturer Notes on IT 2353 UNIT IV

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.

2. JSP Page Compilation:

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().

Page 28: Lecturer Notes on IT 2353 UNIT IV

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

Declaration tag ( <%! %> )

It allows the developer to declare variables or methods. Start with <%! and End with %>

Code placed inside this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or scriptlets. For Example,

Expression tag

Expression tag ( <%= %>)

<%! private int counter = 0 ; private String get Account ( int accountNo) ; %>

Page 29: Lecturer Notes on IT 2353 UNIT IV

Expression tag allow the developer to embed any Java expression and is short for out.println().   A semicolon ( ; ) does not appear at the end of the code inside the tag.   e.g.to show the current date and time.

Directive tag

Direcitve tag ( <%@ directive...>)

A JSP directive gives special information about the page to JSP Engine.

Three main types of directives are:1)     page - processing information for this page.2)     Include - files to be included.3)     Tag library - tag library to be used in this page.

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:

Language Which language the file uses. <%@ page language = "java" %>

Extends Superclass used by the JSP engine for the translated Servlet.

<%@ page extends = "com.taglib... %>

import Import all the classes in a java package into the current JSP page. This allows the JSP page to use other java classes.

<%@ page import = "java.util.*" %>

session oes the page make use of sessions. By default all Default is set to true.

Date : <%= new java.util.Date() %>

Page 30: Lecturer Notes on IT 2353 UNIT IV

JSP pages have session data available. There are performance benefits to switching session to false.

buffer Controls the use of buffered output for a JSP page. Default is 8kb

<%@ page buffer = "none" %>

autoFlush Flush output buffer when full. <%@ page autoFlush = "true" %>

isThreadSafe Can the generated Servlet deal with multiple requests? If true a new thread is started so requests are handled simultaneously.

 

info Developer uses info attribute to add information/document for a page. Typically used to add author,version,copyright and date info.   

<%@ page info = "visualbuilder.com testpage,copyright 2001. " %>

errorPage Different page to deal with errors. Must be URL to error page.

<%@ page errorPage = "/error/error.jsp" %>

IsErrorPage This flag is set to true to make a JSP page a special Error Page. This page has access to the implicit object exception (see later).

 

contentType Set the mime type and character set ofthe 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. Two examples of using include files:

This includes the html from privacy.html found in the include directory into the current jsp page.

<%@ include file = "include/privacy.html" %>

Page 31: Lecturer Notes on IT 2353 UNIT IV

or to include a naviagation menu (jsp file) found in the current directory.

3. Tag Lib directive

A tag lib is a collection of custom tag that can be used by the 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

Scriptlet tag ( <% ... %> )

Between <% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable or bean declared.   For example,to print a variable. 

<%        String username = "visualbuilder" ;         out.println ( username ) ;   %>

Action tag

There are three main roles of action tag :1)    It enable the use of server side Javabeans2)    It transfer control between pages3)    Browser independent support for applets.

<%@ include file = "navigation.jsp" %>

Page 32: Lecturer Notes on IT 2353 UNIT IV

Javabeans

A Javabeans is a special type of class that has a number of methods.

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

componento properties of the classo 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

public class Currency {private Locale locale;private double amount;public Currency() {locale = null;amount = 0.0;}public void setLocale(Locale l) {locale = l;}public void setAmount(double a) {amount = a;}public String getFormat() {NumberFormat nf =NumberFormat.getCurrencyInstance(locale);return nf.format(amount);}}

Page 33: Lecturer Notes on IT 2353 UNIT IV

JavaBean in JSP

The following is a list of Javabean scopes:

page - valid until page completes. request - bean instance lasts for the client request session - bean lasts for the client session. application - bean instance created and lasts until application ends

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 database2.Execute a SQL statement3.Process the result set4.Close the connection to the database

<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>

Page 34: Lecturer Notes on IT 2353 UNIT IV

Import java.sql.*;•Step 1 Open a connection to the ODBC DB

Class.forName(“Sun.jdbc.odbc.JdbcOdbcDriver”) ;// load driverConnection con = DriverManager.getConnection(“jdbc:odbc:eshop”);

•Step 2 Execute the SQL statement

Statement statement = con.createStatement();ResultSet rs = statement.executeQuery(“SELECT * FROM Customers”);•Step 3 Process the Results

While ( rs.next() ) {System.out.println(“Name = “+ rs.getString(“CustomerName”) );}•Step 4 Close the connection

rs.close();con.close();

Page 35: Lecturer Notes on IT 2353 UNIT IV

Four JDBC driver types:

1.JDBC-ODBC Bridge, plus ODBC driver–access to database via odbc drivers2.Native-API, partly-Java driver–converts JDBC commands into DBMS-specific native calls3.JDBC-net, pure Java driver–three tier solution driver translates JDBC calls into a database-independent network protocol that is sent to a middlewares server which send to a database4.Native-protocol, pure Java driver. –communicate directly with the vendor database

Model-view-controller

In object-oriented programming development, model-view-controller (MVC) is the name of a methodology or design pattern for successfully and efficiently relating the user interface to underlying data models.

The model-view-controller pattern proposes three main components or objects to be used in software development:

A Model , which represents the underlying, logical structure of data in a software application and the high-level class associated with it. This object model does not contain any information about the user interface.

A View , which is a collection of classes representing the elements in the user interface (all of the things the user can see and respond to on the screen, such as buttons, display boxes, and so forth)

A Controller , which represents the classes connecting the model and the view, and is used to communicate between classes in the model and view.

MVC in Java Server Pages

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.

Page 36: Lecturer Notes on IT 2353 UNIT IV

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.

Page 37: Lecturer Notes on IT 2353 UNIT IV

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

Page 38: Lecturer Notes on IT 2353 UNIT IV

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.