Three key points:
1. The document discusses the three-tier and N-tier web architectures, which divide applications into independent presentation, application/business logic, and data tiers for modularity.
2. It then covers XML, explaining that XML is a markup language used to describe data with customizable tags defined by DTDs or schemas, in contrast to predefined HTML tags. XML separates data from presentation and allows data exchange between incompatible systems.
3. Finally, it discusses how J2EE uses a distributed, multitier model to divide application logic into reusable components installed across client, web, business, and EIS tiers.
Three key points:
1. The document discusses the three-tier and N-tier web architectures, which divide applications into independent presentation, application/business logic, and data tiers for modularity.
2. It then covers XML, explaining that XML is a markup language used to describe data with customizable tags defined by DTDs or schemas, in contrast to predefined HTML tags. XML separates data from presentation and allows data exchange between incompatible systems.
3. Finally, it discusses how J2EE uses a distributed, multitier model to divide application logic into reusable components installed across client, web, business, and EIS tiers.
Three key points:
1. The document discusses the three-tier and N-tier web architectures, which divide applications into independent presentation, application/business logic, and data tiers for modularity.
2. It then covers XML, explaining that XML is a markup language used to describe data with customizable tags defined by DTDs or schemas, in contrast to predefined HTML tags. XML separates data from presentation and allows data exchange between incompatible systems.
3. Finally, it discusses how J2EE uses a distributed, multitier model to divide application logic into reusable components installed across client, web, business, and EIS tiers.
Three key points:
1. The document discusses the three-tier and N-tier web architectures, which divide applications into independent presentation, application/business logic, and data tiers for modularity.
2. It then covers XML, explaining that XML is a markup language used to describe data with customizable tags defined by DTDs or schemas, in contrast to predefined HTML tags. XML separates data from presentation and allows data exchange between incompatible systems.
3. Finally, it discusses how J2EE uses a distributed, multitier model to divide application logic into reusable components installed across client, web, business, and EIS tiers.
1.0 Introduction to thre tier and N-Tier Web Architecture:
1.1THREE TIER : Three-tier is a client-server architecture in which the user interface, functional process logic ("business rules"), data storage and data access are developed and maintained as independent modules, most often on separate platforms. The term "three-tier" or "three- layer", as well as the concept of multitier architectures, seems to have originated within Rational Software .
The three-tier model is considered to be a software architecture and a software design pattern. advantages modular software with well defined interfaces the three-tier architecture is intended to allow any of the three tiers to be upgraded or replaced independently as requirements or technology change. For example, a change of operating system from Microsoft Windows to Unix would only affect the user interface code. Typically, the user interface runs on a desktop PC or workstation and uses a standard graphical user interface, functional process logic may consist of one or more separate modules running on a workstation or application server, and an RDBMS on a database server or mainframe contains the data storage logic. The middle tier may be multi-tiered itself (in which case the overall architecture is called an "n-tier architecture").
The 3-Tier architecture has the following 3-tiers. 1. Presentation Tier 2. Application Tier/Logic Tier/Business Logic Tier 3. Data Tier
Comparison with the MVC architecture At first glance three-tiers may seem similar to the Model-view-controller (MVC) concept, however topologically they are different. A fundamental rule in a three tier architecture is the Client tier never communicates directly with the Data tier; in a three-tier model all communication must pass through the Middleware tier. Conceptually the three-tier architecture is linear. However, the MVC architecture is triangular: the View sends updates to the Controller, the Controller updates the Model, and the Model directly updates the View. From a Historical perspective the three-tier architecture concept emerged in the 1990s from observations of distributed systems (for example, web applications) where the Client, Middleware and Data tiers run on physically separate platforms. Whereas MVC comes from the previous decade (by work at Xerox PARC in the late 1970's and early 1980's) and is based on observations of applications that ran on a single graphical workstation; MVC was applied to distributed applications much later in its history
1.2N-tier web architecture: In an e-business application typically there are five tiers: The Client Tier: This tier essentially hosts the minimal processing that occurs at the point of client access. In many cases, this means it is basically rendering the content for presentation. The Presentation Tier: This tier hosts the processing that adapts the display and interaction for the accessing client device, whether it is a desktop computer, network computer, Internet kiosk, cell phone, PDA or any other device. Typical basic services that run on this tier include Web servers, portal servers, WAP servers, and Web proxy servers. The Business Tier: This tier hosts the logic that embodies the rules of the particular enterprise, irrespective of access device or resource implementation. The primary service that runs on this tier is the J2EE technology-based application server. The Integration Tier: This tier hosts the formatting and protocol conversion necessary to communicate with enterprise resources. The services that run on this tier include messaging server (JMS), transaction servers (JTS), CORBA servers (Java IDL), LDAP servers (JNDI), native interfaces (JNI), and others. The Resource Tier: This tier consists of legacy systems or any other back-end or external processing systems. The back-end resources may include database servers and mainframe transactional servers, as well as ERP, SCM, and CRM systems.
Typically there are five tiers in an e-business application
1.3Distributed Multitiered Applications in J2EE Platform:
The J2EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. Figure shows two multitiered J2EE applications divided into the tiers described in the following list. The J2EE application parts shown in Figure are presented in J2EE Components . Client-tier components run on the client machine. Web-tier components run on the J2EE server. Business-tier components run on the J2EE server. Enterprise information system (EIS)-tier software runs on the EIS server. Although a J2EE application can consist of the three or four tiers shown in Figure, J2EE multitiered applications are generally considered to be threetiered applications because they are distributed over three locations: client machines, the J2EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standard twotiered client and server model by placing a multithreaded application server between the client application and back-end storage. DI STRI BUTED MULTI TI ERED APPLI CATI ONS
2.0 XML 2.1 Introduction What is XML? XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to describe data XML tags are not predefined. You must define your own tags XML uses a Document Type Definition (DTD) or an XML Schema to describe the data XML with a DTD or XML Schema is designed to be self-descriptive XML is a W3C Recommendation . XML is Free and Extensible XML tags are not predefined. You must "invent" your own tags. The tags used to mark up HTML documents and the structure of HTML documents are predefined. The author of HTML documents can only use tags that are defined in the HTML standard (like <p>, <h1>, etc.). XML allows the author to define his own tags and his own document structure. The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are "invented" by the author of the XML document.
The Main Difference Between XML and HTML XML was designed to carry data. XML is not a replacement for HTML. XML and HTML were designed with different goals: XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks. HTML is about displaying information, while XML is about describing information.
XML Does not DO Anything XML was not designed to DO anything. Maybe it is a little hard to understand, but XML does not DO anything. XML was created to structure, store and to send information. The following example is a note to Tove from Jani, stored as XML: <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The note has a header and a message body. It also has sender and receiver information. But still, this XML document does not DO anything. It is just pure information wrapped in XML tags. Someone must write a piece of software to send, receive or display it.
XML is a Complement to HTML XML is not a replacement for HTML. It is important to understand that XML is not a replacement for HTML. In future Web development it is most likely that XML will be used to describe the data, while HTML will be used to format and display the same data. My best description of XML is this: XML is a cross-platform, software and hardware independent tool for transmitting information.
XML in Future Web Development XML is going to be everywhere. We have been participating in XML development since its creation. It has been amazing to see how quickly the XML standard has been developed and how quickly a large number of software vendors have adopted the standard. We strongly believe that XML will be as important to the future of the Web as HTML has been to the foundation of the Web and that XML will be the most common tool for all data manipulation and data transmission.
XML can Separate Data from HTML With XML, your data is stored outside your HTML. When HTML is used to display data, the data is stored inside your HTML. With XML, data can be stored in separate XML files. This way you can concentrate on using HTML for data layout and display, and be sure that changes in the underlying data will not require any changes to your HTML. XML data can also be stored inside HTML pages as "Data Islands". You can still concentrate on using HTML only for formatting and displaying the data.
XML is Used to Exchange Data With XML, data can be exchanged between incompatible systems. In the real world, computer systems and databases contain data in incompatible formats. One of the most time-consuming challenges for developers has been to exchange data between such systems over the Internet. Converting the data to XML can greatly reduce this complexity and create data that can be read by many different types of applications.
XML and B2B With XML, financial information can be exchanged over the Internet. Expect to see a lot about XML and B2B (Business To Business) in the near future. XML is going to be the main language for exchanging financial information between businesses over the Internet. A lot of interesting B2B applications are under development.
XML Can be Used to Share Data With XML, plain text files can be used to share data. Since XML data is stored in plain text format, XML provides a software- and hardware- independent way of sharing data. This makes it much easier to create data that different applications can work with. It also makes it easier to expand or upgrade a system to new operating systems, servers, applications, and new browsers.
XML Can be Used to Store Data With XML, plain text files can be used to store data. XML can also be used to store data in files or in databases. Applications can be written to store and retrieve information from the store, and generic applications can be used to display the data.
XML Can Make your Data More Useful With XML, your data is available to more users. Since XML is independent of hardware, software and application, you can make your data available to other than only standard HTML browsers. Other clients and applications can access your XML files as data sources, like they are accessing databases. Your data can be made available to all kinds of "reading machines" (agents), and it is easier to make your data available for blind people, or people with other disabilities.
XML Can be Used to Create New Languages XML is the mother of WAP and WML. The Wireless Markup Language (WML), used to markup Internet applications for handheld devices like mobile phones, is written in XML. You can read more about WML in our WML tutorial.
An Example XML Document XML documents use a self-describing and simple syntax. <?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The first line in the document - the XML declaration - defines the XML version and the character encoding used in the document. In this case the document conforms to the 1.0 specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set. The next line describes the root element of the document (like it was saying: "this document is a note"): <note> The next 4 lines describe 4 child elements of the root (to, from, heading, and body): <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> And finally the last line defines the end of the root element: </note> Can you detect from this example that the XML document contains a Note to Tove from Jani? Don't you agree that XML is pretty self-descriptive?
All XML Elements Must Have a Closing Tag With XML, it is illegal to omit the closing tag. In HTML some elements do not have to have a closing tag. The following code is legal in HTML: <p>This is a paragraph <p>This is another paragraph In XML all elements must have a closing tag, like this: <p>This is a paragraph</p> <p>This is another paragraph</p> Note: You might have noticed from the previous example that the XML declaration did not have a closing tag. This is not an error. The declaration is not a part of the XML document itself. It is not an XML element, and it should not have a closing tag.
XML Tags are Case Sensitive Unlike HTML, XML tags are case sensitive. With XML, the tag <Letter> is different from the tag <letter>. Opening and closing tags must therefore be written with the same case: <Message>This is incorrect</message>
<message>This is correct</message>
XML Elements Must be Properly Nested Improper nesting of tags makes no sense to XML. In HTML some elements can be improperly nested within each other like this: <b><i>This text is bold and italic</b></i> In XML all elements must be properly nested within each other like this: <b><i>This text is bold and italic</i></b>
XML Documents Must Have a Root Element All XML documents must contain a single tag pair to define a root element. All other elements must be within this root element. All elements can have sub elements (child elements). Sub elements must be correctly nested within their parent element: <root> <child> <subchild>.....</subchild> </child> </root>
XML Attribute Values Must be Quoted With XML, it is illegal to omit quotation marks around attribute values. XML elements can have attributes in name/value pairs just like in HTML. In XML the attribute value must always be quoted. Study the two XML documents below. The first one is incorrect, the second is correct: <?xml version="1.0" encoding="ISO-8859-1"?> <note date=12/11/2002> <to>Tove</to> <from>Jani</from> </note>
The error in the first document is that the date attribute in the note element is not quoted. This is correct: date="12/11/2002". This is incorrect: date=12/11/2002.
With XML, White Space is Preserved With XML, the white space in your document is not truncated. This is unlike HTML. With HTML, a sentence like this: Hello my name is Tove, will be displayed like this: Hello my name is Tove, because HTML reduces multiple, consecutive white space characters to a single white space.
With XML, CR / LF is Converted to LF With XML, a new line is always stored as LF. Do you know what a typewriter is? Well, a typewriter is a mechanical device which was used last century to produce printed documents. :-) After you have typed one line of text on a typewriter, you have to manually return the printing carriage to the left margin position and manually feed the paper up one line. In Windows applications, a new line is normally stored as a pair of characters: carriage return (CR) and line feed (LF). The character pair bears some resemblance to the typewriter actions of setting a new line. In Unix applications, a new line is normally stored as a LF character. Macintosh applications use only a CR character to store a new line.
Comments in XML The syntax for writing comments in XML is similar to that of HTML. <!-- This is a comment -->
There is Nothing Special About XML There is nothing special about XML. It is just plain text with the addition of some XML tags enclosed in angle brackets. Software that can handle plain text can also handle XML. In a simple text editor, the XML tags will be visible and will not be handled specially. In an XML-aware application however, the XML tags can be handled specially. The tags may or may not be visible, or have a functional meaning, depending on the nature of the application. XML Elements
XML Elements are extensible and they have relationships. XML Elements have simple naming rules.
XML Elements are Extensible XML documents can be extended to carry more information. Look at the following XML NOTE example: <note> <to>Tove</to> <from>Jani</from> <body>Don't forget me this weekend!</body> </note> Let's imagine that we created an application that extracted the <to>, <from>, and <body> elements from the XML document to produce this output: MESSAGE To: Tove From: Jani Don't forget me this weekend! Imagine that the author of the XML document added some extra information to it: <note> <date>2002-08-01</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Should the application break or crash? No. The application should still be able to find the <to>, <from>, and <body> elements in the XML document and produce the same output. XML documents are Extensible.
XML Elements have Relationships Elements are related as parents and children. To understand XML terminology, you have to know how relationships between XML elements are named, and how element content is described. Imagine that this is a description of a book: My First XML Introduction to XML What is HTML What is XML XML Syntax Elements must have a closing tag Elements must be properly nested Imagine that this XML document describes the book: <book> <title>My First XML</title> <prod id="33-657" media="paper"></prod> <chapter>Introduction to XML <para>What is HTML</para> <para>What is XML</para> </chapter>
<chapter>XML Syntax <para>Elements must have a closing tag</para> <para>Elements must be properly nested</para> </chapter>
</book> Book is the root element. Title, prod, and chapter are child elements of book. Book is the parent element of title, prod, and chapter. Title, prod, and chapter are siblings (or sister elements) because they have the same parent.
Elements have Content Elements can have different content types. An XML element is everything from (including) the element's start tag to (including) the element's end tag. An element can have element content, mixed content, simple content, or empty content. An element can also have attributes. In the example above, book has element content, because it contains other elements. Chapter has mixed content because it contains both text and other elements. Para has simple content (or text content) because it contains only text. Prod has empty content, because it carries no information. In the example above only the prod element has attributes. The attribute named id has the value "33-657". The attribute named media has the value "paper".
Element Naming XML elements must follow these naming rules: Names can contain letters, numbers, and other characters Names must not start with a number or punctuation character Names must not start with the letters xml (or XML, or Xml, etc) Names cannot contain spaces Take care when you "invent" element names and follow these simple rules: Any name can be used, no words are reserved, but the idea is to make names descriptive. Names with an underscore separator are nice. Examples: <first_name>, <last_name>. Avoid "-" and "." in names. For example, if you name something "first-name," it could be a mess if your software tries to subtract name from first. Or if you name something "first.name," your software may think that "name" is a property of the object "first." Element names can be as long as you like, but don't exaggerate. Names should be short and simple, like this: <book_title> not like this: <the_title_of_the_book>. XML documents often have a corresponding database, in which fields exist corresponding to elements in the XML document. A good practice is to use the naming rules of your database for the elements in the XML documents. Non-English letters like are perfectly legal in XML element names, but watch out for problems if your software vendor doesn't support them. The ":" should not be used in element names because it is reserved to be used for something called namespaces (more later). XML Attributes
XML elements can have attributes in the start tag, just like HTML. Attributes are used to provide additional information about elements.
XML Attributes XML elements can have attributes. From HTML you will remember this: <IMG SRC="computer.gif">. The SRC attribute provides additional information about the IMG element. In HTML (and in XML) attributes provide additional information about elements: <img src="computer.gif"> <a href="demo.asp"> Attributes often provide information that is not a part of the data. In the example below, the file type is irrelevant to the data, but important to the software that wants to manipulate the element: <file type="gif">computer.gif</file>
Quote Styles, "female" or 'female'? Attribute values must always be enclosed in quotes, but either single or double quotes can be used. For a person's sex, the person tag can be written like this: <person sex="female"> or like this: <person sex='female'> Note: If the attribute value itself contains double quotes it is necessary to use single quotes, like in this example: <gangster name='George "Shotgun" Ziegler'> Note: If the attribute value itself contains single quotes it is necessary to use double quotes, like in this example: <gangster name="George 'Shotgun' Ziegler">
Use of Elements vs. Attributes Data can be stored in child elements or in attributes. Take a look at these examples: <person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
<person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> In the first example sex is an attribute. In the last, sex is a child element. Both examples provide the same information. There are no rules about when to use attributes, and when to use child elements. My experience is that attributes are handy in HTML, but in XML you should try to avoid them. Use child elements if the information feels like data.
My Favorite Way I like to store data in child elements. The following three XML documents contain exactly the same information: A date attribute is used in the first example: <note date="12/11/2002"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> A date element is used in the second example: <note> <date>12/11/2002</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> An expanded date element is used in the third: (THIS IS MY FAVORITE): <note> <date> <day>12</day> <month>11</month> <year>2002</year> </date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Avoid using attributes? Should you avoid using attributes? Some of the problems with using attributes are: attributes cannot contain multiple values (child elements can) attributes are not easily expandable (for future changes) attributes cannot describe structures (child elements can) attributes are more difficult to manipulate by program code attribute values are not easy to test against a Document Type Definition (DTD) - which is used to define the legal elements of an XML document If you use attributes as containers for data, you end up with documents that are difficult to read and maintain. Try to use elements to describe data. Use attributes only to provide information that is not relevant to the data. Don't end up like this (this is not how XML should be used): <note day="12" month="11" year="2002" to="Tove" from="Jani" heading="Reminder" body="Don't forget me this weekend!"> </note>
An Exception to my Attribute Rule Rules always have exceptions. My rule about attributes has one exception: Sometimes I assign ID references to elements. These ID references can be used to access XML elements in much the same way as the NAME or ID attributes in HTML. This example demonstrates this: <messages> <note id="p501"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
<note id="p502"> <to>Jani</to> <from>Tove</from> <heading>Re: Reminder</heading> <body>I will not!</body> </note> </messages> The ID in these examples is just a counter, or a unique identifier, to identify the different notes in the XML file, and not a part of the note data. What I am trying to say here is that metadata (data about data) should be stored as attributes, and that data itself should be stored as elements. XML Validation
XML with correct syntax is Well Formed XML. XML validated against a DTD is Valid XML.
Well Formed XML Documents A "Well Formed" XML document has correct XML syntax. A "Well Formed" XML document is a document that conforms to the XML syntax rules that were described in the previous chapters: XML documents must have a root element XML elements must have a closing tag XML tags are case sensitive XML elements must be properly nested XML attribute values must always be quoted <?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Valid XML Documents A "Valid" XML document also conforms to a DTD. A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD): <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE note SYSTEM "InternalNote.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
2.2XML with DTD
A DTD defines the legal elements of an XML document. The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. You can read more about DTD, and how to validate your XML documents in our DTD tutorial.
2.3XML Schema XML Schema is an XML based alternative to DTD. W3C supports an alternative to DTD called XML Schema. You can read more about XML Schema in our Schema tutorial.
A General XML Validator To help you check the syntax of your xml files, we have created this link so that you can syntax-check any XML file. XML Validator
XML Errors will Stop you Errors in XML documents will stop your XML program. The W3C XML specification states that a program should not continue to process an XML document if it finds an error. The reason is that XML software should be easy to write, and that all XML documents should be compatible. With HTML it was possible to create documents with lots of errors (like when you forget an end tag). One of the main reasons that HTML browsers are so big and incompatible, is that they have their own ways to figure out what a document should look like when they encounter an HTML error. With XML this should not be possible. 2.4XML validator Syntax-check your XML - IE Only To help you syntax-check your xml, we have used Microsoft's XML parser to create an XML validator. Paste your XML in the text area below, and syntax-check it by pressing the "Validate" button. <?xml version="1.0" ?> <note> <to>Tove</to> <from>Jani</Ffrom> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Syntax-check your XML File - IE Only You can also syntax-check your XML file by typing the URL of your file into the input field below, and then press the "Validate" button Filename: http://www.w3schools.com/xml/note_error.xml
Validate
If you want to syntax-check an error-free XML file, you can paste the following address into the filename field: http://www.w3schools.com/xml/cd_catalog.xml Note: If you get the error "Access denied" when accessing this file, it is because your Internet Explorer security settings do not allow access across domains!
Viewing XML Files Raw XML files can be viewed in Mozilla, Firefox, Opera, Internet Explorer, and Netscape 6+. However, to make XML documents display as nice web pages, you will have to add some display information.
2.5Viewing XML Files In Firefox and Internet Explorer: Open the XML file (typically by clicking on a link) - The XML document will be displayed with color-coded root and child elements. A plus (+) or minus sign (-) to the left of the elements can be clicked to expand or collapse the element structure. To view the raw XML source (without the + and - signs), select "View Page Source" or "View Source" from the browser menu. Viewing an Invalid XML File If an erroneous XML file is opened, the browser will report the error. Why Does XML Display Like This? XML documents do not carry information about how to display the data. Since XML tags are "invented" by the author of the XML document, browsers do not know if a tag like <table> describes an HTML table or a dining table. Without any information about how to display the data, most browsers will just display the XML document as it is. In the next chapters, we will take a look at different solutions to the display problem, using CSS, XSL, JavaScript, and XML Data Islands.
3.0 Client side technologies DHTML 3.1Prerequisites for DHTML Before you continue you should have a basic understanding of the following: HTML CSS JavaScript If you want to study these subjects first, find the tutorials on our Home Page.
DHTML is NOT a W3C Standard DHTML stands for Dynamic HTML. DHTML is not a standard defined by the World Wide Web Consortium (W3C). DHTML is a "marketing term" - used by Netscape and Microsoft to describe the new technologies the 4.x generation browsers would support. DHTML is a combination of technologies used to create dynamic Web sites. To most people DHTML means a combination of HTML 4.0, Style Sheets and JavaScript. W3C once said: "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated."
3.2DHTML Technologies With DHTML a Web developer can control how to display and position HTML elements in a browser window. HTML 4.0 With HTML 4.0 all formatting can be moved out of the HTML document and into a separate style sheet. Because HTML 4.0 separates the presentation of the document from its structure, we have total control of presentation layout without messing up the document content. Cascading Style Sheets (CSS) With CSS we have a style and layout model for HTML documents. CSS was a breakthrough in Web design because it allowed developers to control the style and layout of multiple Web pages all at once. As a Web developer you can define a style for each HTML element and apply it to as many Web pages as you want. To make a global change, simply change the style, and all elements in the Web are updated automatically. The Document Object Model (DOM) DOM stands for the Document Object Model. The HTML DOM is the Document Object Model for HTML. The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML objects. "The W3C Document Object Model (DOM) is a platform and language neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document".
JavaScript Allows you to write code to control all HTML elements.
3.3DHTML Technologies in Netscape 4.x and Internet Explorer 4.x Netscape 4.x Cross-Browser DHTML Internet Explorer 4.x JSS (JavaScript Style Sheets) (allows you to control how different HTML elements will be displayed) Layers (allows you to control element positioning and visibility) CSS1 CSS2 (allows you to control how different HTML elements will be displayed) CSS Positioning (allows you to control element positioning and visibility) JavaScript Visual Filters (allow you to apply visual effects to text and graphics) Dynamic CSS (allows you to control element positioning and visibility) Note: Problems with coding DHTML technologies WILL occur as long as each browser creates its own proprietary features and technology that is not supported by other browsers. A Web page may look great in one browser and horrible in another.
4.0 Java Applets
4.1 Basics
This lesson talks about the basics of applets, advantages of applets over applications, how to load applets in a web page, how to convert applications to applets and how applets work. You should thoroughly understand this lesson before going further in this trail. An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web- page and runs in the context of the browser. An applet must be a subclass of the java.applet.Applet class, which provides the standard interface between the applet and the browser environment. Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs. By calling certain methods, a browser manages an applet life cycle, if an applet is loaded in a web page. 4.2Life Cycle of an Applet: Basically, there are four methods in the Applet class on which any applet is built. init: This method is intended for whatever initialization is needed for your applet. It is called after the param attributes of the applet tag. start: This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages. stop: This method is automatically called whenever the user moves away from the page containing applets. You can use this method to stop an animation. destroy: This method is only called when the browser shuts down normally. Thus, the applet can be initialized once and only once, started and stopped one or more times in its life, and destroyed once and only once. . 4.3When to write Applets vs. Applications In the early days of Java, one of the critical advantages that Java applets had over Java applications was that applets could be easily deployed over the web while Java applications required a more cumbersome installation process. Additionally, since applets are downloaded from the internet, by default they have to run in a restricted security environment, called the "sandbox", to ensure they don't perform any destructive operations on the user's computer, such as reading/writing to the filesystem. However, the introduction of Java Web Starthas made it possible for Java applications to also be easily deployed over the web, as well as run in a secure environment. This means that the predominant difference between a Java applet and a Java application is that an applet runs in the context of a web browser, being typically embedded within an html page, while a Java application runs standalone, outside the browser. Thus, applets are particularly well suited for providing functions in a web page which require more interactivity or animation than HTML can provide, such as a graphical game, complex editing, or interactive data visualization. The end user is able to access the functionality without leaving the browser.
4.4Loading Applets in a Web Page In order to load an applet in a web page, you must specify the applet class with appropriate applet tags. A simple example is below: <applet code=AppletWorld.class width="200" height="200"> </applet> For development and testing purposes, you can run your applet using the lightweight appletviewer application that comes with the JDK. For example, if AppletWorld.html is the html file name, then you run the command as appletviewer AppletWorld.html Once you know your applet runs within the appletviewer, it is important to test your applet running in a web browser by loading the applet's web page into the browser window. The browser can retrieve the class files either from the internet or from the local working directory used during development. If you make changes to your applet's code while it is loaded in the browser, then you must recompile the applet and press the "Shift + Reload" button in the browser to load the new version. Getting Started with Applets Below is the HelloWorld applet, which is a simple Java class that prints the string "Hello World" in small rectangle.
We strongly recommend that you install the latest version; release 1.4 or later is required for all our applets. You can find more information in Troubleshooting Applet Problems Following is the source code for the HelloWorld applet: import javax.swing.JApplet; import java.awt.Graphics;
public class HelloWorld extends JApplet { public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString("Hello world!", 5, 15); } } An applet such as this is typically managed and run by Java Plug-in. Java Plug-in, which is automatically included when you download the Java(TM) SE Runtime Environment (JRE), extends the functionality of a web browser, allowing applets to be run under Sun's Java(TM) SE Runtime Environment (JRE) rather than the Java Runtime Environment that comes with the web browser. It works with the Mozilla family of browsers and with Internet Explorer. 4.5Converting Applications to Applets An application is a standalone program consisting of at least one class with a main method. Applets differ significantly from applications. First, applets do not have a main method that is automatically called to begin the program. Instead, several methods are called at different points in the execution of an applet. The difference between Java applets and applications lies in how they are run. Applications are usually run by loading the application's main class file with a Java interpreter, such as the java tool in the JDK(TM) 6. Basic steps to follow to convert an application program into an applet program: You need to create a subclass of java.applet.Applet in which you override the init method to initialize your applet's resources the same way the main method initializes the application's resources. init might be called more than once and should be designed accordingly. Moreover, the top-level Panel needs to be added to the applet in init; usually it was added to a Frame in main. That's it! You may understand clearly as to how you can convert an application program into an applet, by going through a sample application program SwingUI.java here and its corresponding applet program ApptoAppl.java When you compare these two programs, you may come up with the following major differences between the two: The applet class is declared public so appletviewer can access it. The applet class descends from Applet/JApplet and the application class descends from Frame/JFrame. The applet version has no main method. The application constructor is replaced in the applet by start and init methods. GUI components are added directly to the Applet; whereas, in the case of an application, GUI components are added to the content pane of its JFrame object.
4.6Defining an Applet Subclass The first bold line of the following listing begins a block that defines the HelloWorld class. import javax.swing.JApplet; import java.awt.Graphics;
public class HelloWorld extends JApplet { public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString("Hello world!", 5, 15); } } Applets inherit a great deal of functionality from the Applet or JApplet class, including abilities to communicate with the browser and present a graphical user interface (GUI) to the user. An applet which will be using GUI components from Swing (Java's GUI toolkit) should extend the javax.swing.JApplet base class, which provides the best integration with Swing's GUI facilities. JApplet provides the same "RootPane" top-level component structure as Swing's JFrame and JDialog components, whereas Applet provides just a simple panel. See How to Use Root Panesfor more details on how to utilize this feature. An applet may extend java.applet.Applet when it makes no use of Swing's GUI components. This may be the case if the applet does all its own rendering using the Java graphics libraries (such as with graphing or gaming) and/or uses only AWT components. The following is the source code for the Simple. The Simple applet displays a descriptive string whenever it encounters a major milestone in its life, such as when the user first visits the page the applet's on. The pages that follow use the Simple applet and build upon it to illustrate concepts that are common to many applets. If you find yourself baffled by the Java source code, you might want to go to Learning the Java Language to learn about the language. /* * Java(TM) SE 6 Version */
public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } }
Note: In this example, we extend the Applet class, not the Swing JApplet class, as we do not need to add Swing components to this applet.
Loading the Applet You should see "initializing... starting..." above, as the result of the applet being loaded. When an applet is loaded, here's what happens: An instance of the applet's controlling class (an Applet subclass)is created. The applet initializes itself. The applet starts running. Leaving and Returning to the Applet's Page When the user leaves the page for example, to go to another page the browser stops the applet. When the user returns to the page, the browser starts the applet.
Browser note: Some browsers reload the applet when you return to its page. In at least one browser, a bug exists where an applet can initialize itself more than once without being reloaded.
Reloading the Applet Some browsers let the user reload applets, which consists of unloading the applet and then loading it again. Before an applet is unloaded, it's given the chance to stop itself and then to perform a final cleanup, so that the applet can release any resources it holds. After that, the applet is unloaded and then loaded again, as described in Loading the Applet, above.
Try this: If your browser or other applet viewer lets you easily reload applets, reload the applet. Look at the standard output to see what happens when you reload the applet. (See Displaying Short Status Strings for information about the standard output.) You should see "stopping..." and "preparing for unloading..." when the applet is unloaded. You can't see this in the applet GUI because the applet is unloaded before the text can be displayed. When the applet is reloaded, you should see "initializing..." and "starting...", just like when you loaded the applet for the first time.
Quitting the Browser When the user quits the browser (or whatever application is displaying the applet), the applet has the chance to stop itself and do final cleanup before the browser exits. : It can initialize itself. It can start running. It can stop running. It can perform a final cleanup, in preparation for being unloaded. Following is the interface for these methods: public class Simple extends JApplet { . . . public void init() { . . . } public void start() { . . . } public void stop() { . . . } public void destroy() { . . . } . . . } The init, start, stop, and destroy methods are discussed and used throughout this tutorial. For more information, you can also refer to the JApplet API Specification. 4.7Overriding These Methods Not every applet needs to override every one of these methods. Some very simple applets override none of them. For example, the HelloWorld applet at the beginning of this section doesn't override any of these methods, since it doesn't do anything except draw itself. The "Hello World" applet just displays a string once, using its paint method. (The paint method is described on the following page.) Most applets, however, do more. The init Method The init method is useful for one-time initialization that doesn't take very long. In general, the init method should contain the code that you would normally put into a constructor. The reason applets shouldn't usually have constructors is that an applet isn't guaranteed to have a full environment until its init method is called. For example, the Applet image loading methods simply don't work inside of an applet constructor. The init method, on the other hand, is a great place to call the image loading methods, since the methods return quickly.
The start Method Every applet that does something after initialization (except in direct response to user actions) must override the start method. The start method either performs the applet's work or (more likely) starts up one or more threads to perform the work. You'll learn more about threads later in this trail, in the Threads in Applets section. You'll learn more about handling the events that represent user actions on the next page. The stop Method Most applets that override start should also override the stop method. The stop method should suspend the applet's execution, so that it doesn't take up system resources when the user isn't viewing the applet's page. For example, an applet that displays animation should stop trying to draw the animation when the user isn't looking at it. The destroy Method Many applets don't need to override the destroy method, since their stop method (which is called before destroy) does everything necessary to shut down the applet's execution. However, destroy is available for applets that need to release additional resources.
Note: You should keep implementations of the destroy method as short as possible, because there is no guarantee that this method will be completely executed. The Java Virtual Machine might exit before a long destroy method has completed.
Methods for Drawing and Event Handling 4.8Using the Paint Method To draw the applet's representation within a browser page, you use the paint method. For example, the Simple applet defines its onscreen appearance by overriding the paint method: public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } Applets inherit the paint method from the Abstract Window Toolkit (AWT) Container class. 4.9Handling Events Applets inherit a group of event-handling methods from the Container class. The Container class defines several methods, such as processKeyEvent and processMouseEvent, for handling particular types of events, and then one catch-all method called processEvent. To react to an event, an applet must override the appropriate event-specific method. For example, the following program, SimpleClick, implements a MouseListener and overrides the mouseClicked method. /* * Java(TM) SE 6 version. */
public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); }
//The following empty methods could be removed //by implementing a MouseAdapter (usually done //using an inner class). public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { }
public void mouseClicked(MouseEvent event) { addItem("click!... "); } } Below is the resulting applet. When you click within its rectangle, it displays the word "click!...".
5.0ActiveX control
ActiveX control is a Microsoft term that is used to denote reusable software components that are based on Microsoft Component Object Model (COM). ActiveX controls provide encapsulated reusable functionality to programs and they are typically but not always visual in nature. For example, an ActiveX control might implement spreadsheet functionality similar to Microsoft Excel, which would be visual in nature, but it also might implement functionality to upload or download files from an FTP site, which is not visual in nature unless it incorporates some sort of download progress display or similar. ActiveX controls debuted in v4.0 of the desktop development tool for Microsoft Windows called Visual Basic, but Microsoft later modified the Internet Explorer web browser to use them to incorporate applet-like functionality into web pages. Because of that later use, ActiveX Controls have since been much derided in the mainstream and technical press for their ability to be used by unethical developers to create computer viruses, trojans and spyware infections. 5.1Safety & security ActiveX controls are not inherently unsafe, especially when used within a development package like Visual Basic. In that context, assuming the author is trusted, they are no less safe than the other programming code the developer who uses the controls may write. ActiveX controls are instead unsafe for users of Internet Explorer who turn on the browser's ability to download and activate ActiveX controls within a web page. The problems occur when a user surfs to a non-trusted web page and that web page contains a malicious ActiveX control. This is a very common means of distributing malware such as adware and spyware to unwitting users of Internet Explorer; the easiest way to avoid it is to use an alternative web browser that does not use the Trident rendering engine. Internet Explorer users should configure their browsers to not install ActiveX controls from untrusted sites. Examples of ActiveX controls are: Adobe Reader, Apple QuickTime Player, Macromedia Flash Player, Microsoft Windows Media Player, Real Networks RealPlayer, Sun Java Virtual Machine. 5.2Writing ActiveX controls ActiveX controls are simply glorified COM objects, so they can be written using: Microsoft Foundation Classes (MFC) - Not recommended, due to the size of the MFC DLLs required Active Template Library (ATL) - The easiest way Plain C/C++ - Most difficult since lots of support code must be written In languages that support COM, e.g. Visual Basic
And now for another belly-chuckler - what's the difference between an ActiveX component and an ActiveX control? OK, not quite a dinner party puzzler but still an important point. Let's take a look at what exactly an ActiveX component is... and is not. An ActiveX component is just a general term, encompassing: An ActiveX EXE An ActiveX DLL An ActiveX Control An ActiveX component is not: Active, in any way, shape or form A source of fibre that can help you lose weight as part of a calorie controlled diet So what exactly are ActiveX EXEs and DLLs? Basically, they're chunks of code you use in your Visual Basic projects just by setting a reference to them a little like how you set a reference to DAO or ADO when you need access to a database. But that's another department completely... more to the point, just what are ActiveX controls? Well, you might not know this, but you already have experience of ActiveX controls. You've used them, tweaked them and tossed them to one side all in the course of a days work. Ohhhh yes. Indeed, every time you set the Text property of a Text Box, you're utilising an ActiveX control. Every time you respond to the Click event of a Command Button, you're utilising an ActiveX control. Every time you run the MoveNext method of the Data control, you're utilising an ActiveX control. I think you get the picture. In essence, an ActiveX control is anything you might see in the Toolbox. Top Tip: Don't forget that you can also add more controls to the Toolbox by selecting Projects, Components But how can all this background information help in everyday programming life? Well, with the advent of Visual Basic 5 and, more recently Visual Basic 6, supercool geeky-types have been able to create their very own ActiveX controls. So perhaps you could create your own groovy text box control that only allows the user to input numbers. Or perhaps just text. Or perhaps text and numbers, but no spaces. Maybe you'd like to create a company-wide Exit button that flashes every time you hover your mouse over it. Sure, it might be about as useful as a pencil sharpener in the bullring, but it'd look good. Other slightly more practical uses include creating a standardised Save dialog box. Or a lighter-weight version of the MSChart control. Or a plain but simple replacement for the InputBox() function. Or perhaps an intelligent scrollable window that displays a picture you pass it. Or a new and improved combo box. Or maybe just something else. Then, when you need to use that groovy flashing Exit button, you simply draw it onto your form, just as you would any standard control. You could then set its MyControl.Forecolor property, and perhaps respond to its MyControl_Click event by adding a bit of code. You could even execute one of its' methods every now and then, such as MyControl.FlashAnimation. The difference here is that you, as a productive, presentable, professional, pragmatic programmer, created the control. And as such, you dictate when the MyControl_Click event fires. Or how the MyControl.FlashAnimation method works. Or in which way the MyControl.ForeColor property is implemented is the user presented with a text list of just four colours or the standard colour selection panel? We'll be covering all this and more in this series. But for now, let's jump in at the deep end and knock out our very first ActiveX control!
JavaServer Faces (JSF) is a Java-based Web application framework that simplifies the development of user interfaces for Java EE applications. Out of the box, JSF uses JavaServer Pages for its display technology, but JSF can also accommodate other display technologies (such as XUL). JSF includes:
* A set of APIs for representing user interface (UI) components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility * A default set of UI components * Two JavaServer Pages (JSP) custom tag libraries for expressing a JavaServer Faces interface within a JSP page. * A server-side event model * State management * Managed Beans (JavaBeans created with dependency injection) * Unified Expression Language for both JSP 2.0 and JSF 1.2
6.0 Server Side Technologies
6.1JSF The JSF specification was developed under the Java Community Process as JSR 127, which defined JSF 1.0 and 1.1, and JSR 252 which defined JSF 1.2. Contents
JSF versions
* JSF 1.0 (2004-03-11) - the initial release of JSF specification. * JSF 1.1 (2004-05-27) - bug fix release. There were no spec or HTML renderkit changes. * JSF 1.2 (2006-05-11) - latest release. o enhancements to provide an interim solution to the content-interweaving problem described at http://www.onjava.com/pub/a/onjava/2004/06/09/jsf.html o provide XML Schema for the config files, instead of using DTD o enhancements to allow faces applications to handle multi-frame, or multi- window UI designs o enhancements to the f: tag library for improved TCK coverage, f:view lifetime events, and other small features o enhancements to the decorator support for API objects o security enhancements for client side state saving o solve the "duplicate button press" problem o re-organize the spec into normative, and non-normative sections, to make implementation easier o portlet related bug-fixes o bug fixes that require minimal specification changes
Comparison to other Web-GUI Frameworks
Microsoft ASP.NET
Main article: ASP.net
ASP.NET from Microsoft features a component based approach to WebApplication development similar to JSF. In ASP.Net v1, component rendering code was bundled with the UI component, unlike JSF, where rendering and component interfaces can be separated, thus allowing for customization of the renderer. ASP.Net v2 introduced the control adapter framework allowing the default rendering to be overridden by 3rd party code. ASP.NET is also more tightly integrated into the Microsoft development tools, thereby enabling Drag & Drop UI generation in Visual Studio.
Business code is connected to the UI components by subscribing to events generated by the components and stored in a separate file ("code behind"). Thus a typical ASP.NET page consists of a (HTML) file describing the visual page layout (design), and a file with the page logic (code). Both files are treated as one single entity by the Microsoft development tools.
As a consequence, presentation layer and business logic is normally tightly coupled in ASP.NET applications (in Java technology often referred to as Model 1). This is a major difference to JSF or Struts, where business logic is by design much more segregated from the presentation layer via a strict MVC paradigm and a separate definition of page flow (Model 2). Implementation of the latter is also possible by use of certain frameworks.
[edit] WebObjects / Wotonomy
Main article: WebObjects Main article: Wotonomy
WebObjects is the earliest known web-application framework and was originally developed by NeXT Software, Inc. then acquired by Apple Computer when it acquired NeXT. It contains an MVC architecture with a similar component and event model, and lifecycle to JSF. It is deployable without J2EE (its original configuration), or can be deployed in a servlet container, its dispatcher object acting as the entry-point of a J2EE webapp. Unlike JSF's default case, components are not defined in JSP files, but are in .woc directories containing (any or all of) an html/xml/wml template file, a file to map fields and actions to java code, and a .java class. The template file provides the rendering/layout and may include other WebObjects components, rather than the delegated RenderKit approach used by default in JSF. It is a halfway-point between the delegated and directly-rendered approaches used in JSF.
WebObjects also includes a layered architecture with one of the earliest Object- Relational Mapping frameworks, Enterprise Objects Framework.
Wotonomy is a clean-room, open-source re-implementation of the WebObjects frameworks licensed under LGPL. It attempts to implement all parts of WebObjects, and has implemented the whole MVC web-GUI stack. As a clone of WebObjects, it differs from JSF in identical ways, except where it is incomplete.
[edit] Apache Tapestry
Main article: Tapestry (programming)
Tapestry is an open-source framework for creating dynamic, robust, scalable web applications in Java. Tapestry builds upon the standard Java Servlet API, and so it works in any servlet container or application server. Unlike JSF, Tapestry does not use JSP as the view technology - instead preferring an alternate templating engine that allows for easy html preview and editing.
Main article: Apache Struts
Struts is a popular Model 2 MVC framework from the Apache Software Foundation. It provides page-at-a-time MVC and does not have a component-model in the style of JSF. Pages are mapped to models with a dispatch servlet (controller) piping input to actions. In Struts, unlike the component-oriented approaches above where components consume their own form data, a struts action is responsible for knowing and digesting the parameters of the request. Struts applications use JSPs to render views and are amenable to mix-and-match jsp taglib use. (See also Apache Beehive)
6.2JAVA SERVLETS
The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as CGI and ASP. NET. Servlets can maintain state across many server transactions by using HTTP cookies, session variables or URL rewriting. The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A Servlet is an object that receives a request (ServletRequest) and generates a response (ServletResponse) based on the request. The API package javax.servlet.http defines HTTP subclasses of the generic servlet (HttpServlet) request (HttpServletRequest) and response (HttpServletResponse) as well as a session (HttpSession) that tracks multiple requests and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web application. However, servlets can be generated automatically by JavaServer Pages (JSP), or alternately by template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view- controller pattern 6.3 JSP
JavaServer Pages (JSP) is a Java technology that allows software developers to dynamically generate HTML, XML or other types of documents in response to a Web client request. The technology allows Java code and certain pre-defined actions to be embedded into static content. The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way of extending the capabilities of a Web server. JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate a servlet in Java code that is then compiled by the Java compiler, or it may generate byte code for the servlet directly. JSP Syntax A JavaServer Page may be broken down into the following pieces: static data such as HTML, JSP directives such as the include directive, JSP scripting elements and variables, JSP actions, custom tags <html> <head></head> <body> <jsp:include page="mycommon.jsp" > <jsp:param name="extraparam" value="myvalue" /> </jsp:include> name:<%=request.getParameter("extraparam")%> </body></html> JSP directives JSP directives control how the JSP compiler generates the servlet. The following directives are available: include The include directive informs the JSP compiler to include a complete file into the current file. It is as if the contents of the included file were pasted directly into the original file. This functionality is similar to the one provided by the C preprocessor. Included files generally have the extension "jspf" (for JSP Fragment): <%@ include file="somefile.jspf" %> page There are several options to the page directive.
import results in a Java import statement being inserted into the resulting file contentType specifies the content that is generated. This should be used if HTML is not used or if the character set is not the default character set. errorPage indicates the page that will be shown if an exception occurs while processing the HTTP request. isErrorPage if set to true, it indicates that this is the error page. isThreadSafe indicates if the resulting servlet is thread safe. <%@ page import="java.util.*" %> //example import <%@ page contentType="text/html" %> //example contentType <%@ page isErrorPage=false %> //example for non error page <%@ page isThreadSafe=true %> //example for a thread safe JSP Note: Only the "import" page directive can be used multiple times in the same JSP. taglib The taglib directive indicates that a JSP tag library is to be used. The directive requires that a prefix be specified (much like a namespace in C++) and the URI for the tag library description. <%@ taglib prefix="myprefix" uri="taglib/mytag.tld" %> JSP scripting elements and objects J SP I mplicit Objects The following JSP implicit objects are exposed by the JSP container and can be referenced by the programmer: out The JSPWriter used to write the data to the response stream. page The servlet itself. pageContext A PageContext instance that contains data associated with the whole page. A given HTML page may be passed among multiple JSPs. request The HttpServletRequest object that provides HTTP request information. response The HTTP response object. session The HTTP session object that can be used to track information about a user from one request to another. config Provides servlet configuration data. application Data shared by all JSPs and servlets in the application. exception Exceptions not caught by application code. Scripting elements There are three basic kinds of scripting elements that allow java code to be inserted directly into the servlet. A declaration tag places a variable definition inside the body of the java servlet class. Static data members may be defined as well. <%! int serverInstanceVariable = 1; %> A scriptlet tag places the contained statements inside the _jspService() method of the java servlet class. <% int localStackBasedVariable = 1; out.println(localStackBasedVariable); %> An expression tag places an expression to be evaluated inside the java servlet class. Expressions should not be terminated with a semi-colon . <%= "expanded inline data " + 1 %> JSP actions JSP actions are XML tags that invoke built-in web server functionality. The following actions are provided:
jsp:include Similar to a subroutine, the Java servlet temporarily hands the request and response off to the specified JavaServer Page. Control will then return to the current JSP, once the other JSP has finished. Using this, JSP code will be shared between multiple other JSPs, rather than duplicated. jsp:param Can be used inside a jsp:include, jsp:forward or jsp:params block. Specifies a parameter that will be added to the request's current parameters. jsp:forward Used to hand off the request and response to another JSP or servlet. Control will never return to the current JSP. jsp:plugin Older versions of Netscape Navigator and Internet Explorer used different tags to embed an applet. This action generates the browser specific tag needed to include an applet. jsp:fallback The content to show if the browser does not support applets. jsp:getProperty Gets a property from the specified JavaBean. jsp:setProperty Sets a property in the specified JavaBean. jsp:useBean Creates or re-uses a JavaBean available to the JSP page. Examples of tags jsp:include <html> <head></head> <body> <jsp:include page="mycommon.jsp" > <jsp:param name="extraparam" value="myvalue" /> </jsp:include> name:<%=request.getParameter("extraparam")%> </body></html> jsp:forward <jsp:forward page="subpage.jsp" > <jsp:param name="forwardedFrom" value="this.jsp" /> </jsp:forward> In this forwarding example, the request is forwarded to "subpage.jsp". The request handling does not return to this page. jsp:plugin <jsp:plugin type=applet height="100%" width="100%" archive="myjarfile.jar,myotherjar.jar" codebase="/applets" code="com.foo.MyApplet" > <jsp:params> <jsp:param name="enableDebug" value="true" /> </jsp:params> <jsp:fallback> Your browser does not support applets. </jsp:fallback> </jsp:plugin> The plugin example illustrates a <html> uniform way of embedding applets in a web page. Before the advent of the <OBJECT> tag, there was no common way of embedding applets. This tag is poorly designed and hopefully future specs will allow for dynamic attributes (height="${param.height}", code="${chart}", etc) and dynamic parameters. Currently, the jsp:plugin tag does not allow for dynamically called applets. For example, if you have a charting applet that requires the data points to be passed in as parameters, you can't use jsp:params unless the number of data points are constant. You can't, for example, loop through a ResultSet to create the jsp:param tags. You have to hand code each jsp:param tag. Each of those jsp:param tags however can have a dynamic name and a dynamic value. jsp:useBean <jsp:useBean id="myBean" class="com.foo.MyBean" scope="request" /> <jsp:getProperty name="myBean" property="lastChanged" /> <jsp:setProperty name="myBean" property="lastChanged" value="<%= new Date()%>" /> The scope attribute can be request, page, session or application. It has the following meanings: request the attribute is available for the lifetime of the request. Once the request has been processed by all of the JSPs, the attribute will be de-referenced. page the attribute is available for the current page only. session the attribute is available for the lifetime of the user's session. application the attribute is available to every instance and is never de- referenced. Same as a global variable. The example above will use a Bean Manager to create an instance of the class com.foo.MyBean and store the instance in the attribute named "myBean". The attribute will be available for the life-time of the request. It can be shared among all of the JSPs that were included or forwarded-to from the main JSP that first received the request. JSP Standard Tag libraries (JSTL) In addition to the pre-defined JSP actions, developers may add their own custom actions using the JSP Tag Extension API. Developers write a Java class that implements one of the Tag interfaces and provide a tag library XML description file that specifies the tags and the java classes that implement the tags. Consider the following JSP. <%@ taglib uri="mytaglib.tld" prefix="myprefix" %> ... <myprefix:myaction> <%-- the start tag %> ... </myprefix:myaction> <%-- the end tag %> ... The JSP compiler will load the mytaglib.tld XML file and see that the tag 'myaction' is implemented by the java class 'MyActionTag'. The first time the tag is used in the file, it will create an instance of 'MyActionTag'. Then (and each additional time that the tag is used), it will invoke the method doStartTag() when it encounters the starting tag. It looks at the result of the start tag, and determines how to process the body of the tag. The body is the text between the start tag and the end tag. The doStartTag() method may return one of the following: SKIP_BODY - the body between the tag is not processed EVAL_BODY_INCLUDE - evaluate the body of the tag EVAL_BODY_TAG - evaluate the body of the tag and push the result onto stream (stored in the body content property of the tag). NOTE: If tag extends the BodyTagSupport class, the method doAfterBody() will be called when the body has been processed just prior to calling the doEndTag(). This method is used to implement looping constructs. When it encounters the end tag, it invokes the doEndTag() method. The method may return one of two values: EVAL_PAGE - this indicates that the rest of the JSP file should be processed. SKIP_PAGE - this indicates that no further processing should be done. Control leaves the JSP page. This is what is used for the forwarding action. The myaction tag above would have an implementation class that looked like something below: public class MyActionTag extends TagSupport { //Releases all instance variables. public void release() {...}
public MyActionTag() { ... }
//called for the start tag public int doStartTag() { ... }
//called at the end tag public int doEndTag(){ ... } } Add Body Tag description.