Professional Documents
Culture Documents
Rajiv Jain, Vei Publishing - Zero To Mastery In Web Development- No.1 Web Development Book To Become Zero To Hero In Web Development, This Amazing Web Development Book Covers A-Z Web ... (Zero To Mast.pdf
Rajiv Jain, Vei Publishing - Zero To Mastery In Web Development- No.1 Web Development Book To Become Zero To Hero In Web Development, This Amazing Web Development Book Covers A-Z Web ... (Zero To Mast.pdf
Rajiv Jain, Vei Publishing - Zero To Mastery In Web Development- No.1 Web Development Book To Become Zero To Hero In Web Development, This Amazing Web Development Book Covers A-Z Web ... (Zero To Mast.pdf
Web
DEVELOPMENT
Zero to Mastery in
Web
DEVELOPMENT
All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form or by any means, electronic, mechanical,
photocopying, recording or otherwise, without the prior permission of the copyright
owners.
DISCLAIMER
Errors, if any, are purely unintentional and readers are requested to communicate
such errors to the publisher to avoid discrepancies in future.
Published by:
AN ISO 9001:2008 CERTIFIED COMPANY
Index 239-244
CHAPTER 1
INFORMATION
ARCHITECTURE
Marketing
The marketing team basically focuses on the intended purposes and audiences for
the web site. They must understand what will bring the right people to the web site
and what will bring them back again.
Information Architecture
The information architects focus on the design of organization, indexing, labelling,
and navigation systems to support browsing and searching throughout the web
site.
Graphic Design
The designers are responsible for the graphic design and page layout to represent
the graphic look of the web site. They create and implement a design philosophy
that balances form and function.
6 ZERO TO MASTERY IN WEB DEVELOPMENT
Editorial
Editors focus on the use of language throughout the web site. Their tasks may
involve reading and editing copy, massaging content to ensure a common voice for
the site, and creating new copy.
Technical
The technical designers and programmers are responsible for server administration
and the development of site production tools and web site applications. They also
aware the other teams regarding technology-related opportunities and limitations.
Project Management
The project manager is responsible for managing the project on schedule and within
budget. He or she is also responsible for enabling communication between the
other teams and the clients or internal stakeholders.
Advantages:
• This organization schemes are easy to design and maintain due to little
intellectual work involved in assigning items to categories.
• It’s Easy to Use.
Disadvantages:
• Exact organization schemes require the user to know the specific name
of the resource they are going to search.
Three frequently used exact organization schemes are as follows:
• Alphabetical organization scheme: In this scheme all the information
atoms are arranged alphabetically and grouped accordingly. The
implementation of this scheme can be seen in encyclopaedias,
Dictionaries, phone books, bookstores etc. On the web you can observe
this scheme in the Address book of your mailbox.
• Chronological Organization Schemes: In this scheme, the information
is represented in chronological way. E.g. an archive of press releases
might be organized by the date of release. Moreover, history books,
magazine archive, diaries and television guides are organized
chronologically. As long as there is agreement on when a particular
event occurred, chronological schemes are easy to design and use.
• Geographical Organization Schemes: Location is very important
characteristics of information. It is because political, social and economic
issues are mainly location dependent. Example, in a website of MNC
the list of products available is different in different countries according
to economy, population of that particular country. So such a website
maintains such location dependent information using Geographical
Organization Schemes.
2. Ambiguous Organization Schemes: Ambiguous Organization Schemes
divides the information into categories that defy exact definition. They
are mired in the ambiguity of language and organization. Ambiguous
organization supports the serendipitous mode of information seeking by
grouping items in intellectually meaningful manner. In the alphabetical
scheme, closely grouped items may don’t have anything in common beyond
the fact that their names begin with the same letter. In this scheme, someone
other than the user has made an intellectual decision to group items together.
10 ZERO TO MASTERY IN WEB DEVELOPMENT
Advantages
Ambiguous Organization Schemes are more useful than exact organization schemes
because the information atoms are grouped on the basis of their meaning not just
because they start from a particulars alphabet.
Disadvantages
Ambiguous Organization Schemes are difficult to
• Design
• Maintain
• Use
Most common and valuable ambiguous organization schemes are:
• Topical Organization scheme: The most challenging approach to organize
the information is by topic or subject. In this scheme all the information
atoms related to one topic is grouped into a single category E.g. Phone
book yellow pages are organized topically. Research oriented websites
are highly dependent and based on topical organization schemes. To design
a topical Organization Scheme, it is important to define the breadth of
coverage content. Some schemes such as encyclopaedia cover the entire
breadth of human knowledge. On the other hand, corporate websites are
limited to cover only those topics which are directly related to the
company’s products and services. E.g.Yahoo.com categorizes the various
information as Ads & Entertainment, Hobbies and Games, Industry and
Business etc. whereas Microsoft.com categorizes it as about, Product
Support, Careers, and Contacts etc.
• Task-oriented Organization Scheme: Task oriented schemes organizes
the content and application into a collection of processes, functions or
tasks. These schemes are useful when it is possible to deal with a limited
INFORMATION ARCHITECTURE
11
number of high priority tasks that users will want to perform frequently.
E.g. Ms Word uses this scheme as collections of individual actions are
organized under various task oriented menus such as Edit, Insert and
Format.
• Audience-specific Organization Scheme: This scheme is appropriate
where there are two or more clearly definable audiences for a website
organization intranet. This scheme works efficiently, when the site is
frequently used by repeated visitors who can bookmark their particular
section of the site. It also works well if there is value in customizing the
content for each audience. E.g. xyzcollege.com contains different links
for students, faculty and management. This type of schemes can be open
or closed. In an open scheme, members of one audience can access the
content intended for other audiences. A closed scheme prevents members
from moving between audience specific sections.
• Hybrid Organization Scheme: The power of a pure organization scheme
is having the ability to provide a simple mental model that users can quickly
understand. However when you start combining the elements of multiple
schemes, confusion is created and solutions are hard to find. The hybrid
scheme can include elements of audience specific, topical task oriented
and alphabetical organization.
Examples
• Family trees are basically hierarchical.
• Organization charts are usually hierarchical.
• We divide the books into chapters into sections into paragraphs into
sentences into words into letters.
12 ZERO TO MASTERY IN WEB DEVELOPMENT
Advantages
A. The mutually exclusive subdivisions and parent child relationships of
hierarchies are simple and familiar.
B. Because of this pervasiveness of hierarchy, it is easy for the user to quickly
understand web sites that use hierarchical organization models. They can
develop a mental model of the site’s structure and their location within
that structure. This helps the users to feel comfortable.
C. This approach allows you to quickly get a handle on the scope of the
website without going through an extensive content inventory process.
You can identify the major content areas and exploring possible
organization schemes that will provide access to that content. Because
hierarchies provide a simple and familiar way to organize information
they are a good place to start the information architecture process.
While designing the hierarchical model consider the following points
• Balance between exclusivity and inclusivity: The hierarchical categories
should be mutually exclusive. Within a single organization scheme there
is a need to balance between exclusivity the and inclusivity. Hierarchical
model that allows listing is known as poly hierarchical model. But if too
many items are cross listed then hierarchy loses its value.
• Balance between breadth and depth: It is necessary to consider the
balance between the breadth and depth of the hierarchy. Breadth refers to
the number of options at each level in the hierarchy and depth refers to the
number of levels in the hierarchy. If a hierarchy is too narrow and deep
then users have to click through an inordinate number of levels to find
what they are searching for. In the broad and shallow hierarchy users must
choose from large number categories and may get unpleasantly surprised
by the lack of content once they select an option.
Hypertext Model
Hypertext is a new and highly nonlinear way of structuring information. A hypertext
system involves two types of components: the items or chunks of information which
are to be linked, and the links between those chunks. These components can form
hypermedia systems that connect text, data, image, video, and audio chunks.
Hypertext chunks can be connected hierarchically, non-hierarchically, or both
(shown in figure 1.1).
Advantages
1. This model provides great flexibility
2. This model allows for useful and creative relationships between various
items and areas in the hierarchy. It usually makes sense to first design the
information hierarchy and then identify ways in which hypertext can
complement the hierarchy.
Disadvantages
1. It presents substantial potential for complexity and user confusion.
2. As users navigate through highly hyper textual websites it is easy for them
to get lost.
3. Hyper textual links are often personal in nature. The relationships that
one person sees between content items may not be apparent to others.
Contextual Navigation system: Some relationships are not well suited into
the structured categories of global and local navigation. So there is a need for the
creation of contextual navigation links specific to a particular page, document or
object. E.g. Words or phrases within sentences are represented as embedded or
inline hypertext links. On an e-commerce site, these “See Also” links can point
users to related products and services. In this way contextual navigation supports
associative learning and users learn by exploring the relationship you define
between items. They might learn about useful products they didn’t know about.
Uses of Guides
• Guides are often a useful tool for introducing new users to the content and
functionality of a website.
• Guides are valuable marketing tools for restricted access websites, enabling
you to show potential customers what they will get for their money.
• Guides are valuable internally, providing an opportunity to showcase key
features of a redesigned site to colleagues, managers and venture capitalists.
Linking between Navigation and searching: Searching is loosely linked with
integrated Navigation Systems and tightly linked with Remote Navigation systems.
between a table of contents, an index, and a sitemap. For strong hierarchy, a table
of content is needed. For appropriate hierarchy, an index is considered. Moreover,
for good visualization of hierarchy, a sitemap may be appropriate. At last, to help
new or prospective users to understand what they can do with site, a guided tour
can be added in the system.
For large and complex site, elements such as table of contents and an index
can be added serve different users with varying needs. Sometimes, a user gets
confused due to multiple options while navigating these elements. So it is important
to consider the potential user confusion and additional overhead required to design
and maintain these navigation elements.
Fielded Searching
Users are easily reachable to author, keyword, Title, Subject and ten other fields.
For example, A researcher could find a dissertation related to his or her area of
interest by searching the subject field. By reading the abstract of that dissertation
he will learn who was advisor of that doctoral student. To find other related
dissertations, the researcher could then search the advisor field to learn about other
doctoral students who shared the same advisor.
Longer Queries
More complex queries often require more space than the single line entry box
found in the simple search interface. The more complex interface supports a much
longer query.
22 ZERO TO MASTERY IN WEB DEVELOPMENT
architects are ignoring two important things: that the information that is there
in the site isn’t all the same. And that it makes good sense to respect the lines that
has already been drawn between different types of content. For example, it’s clear
that English and French content are vastly different and that there audience’s
overlaps very little, so why not create separately searchable indices along those
divisions?
that is not found in other media. The technology disappears and inhibitions fall
away.
In early research-oriented meetings, white boards support the collaboration
around the definition and refinement of the mission, vision, and goals of the project.
When working with several people from the organization, each with a different set
of experiences, perspectives, and goals, you can use the white board to help identify
issues, resolve the differences, and achieve consensus.
White boards are also useful for considering all possible information
architectures. Presenting ideas on the whiteboard triggers new understanding and
further brainstorming. The white board, the architect, and colleagues become
connected in a feedback cycle that moves towards the articulation of the information
architecture.
Current Research
MARC Online
Digital Dissertations
Legend
Page Link
Search Browse
Search
_________________________
_________________________
sample search would go here
Search tips
Browse
by Title
by Subjects/Discipline
by Primary Audience
by Primary Purposes
by Primary Format
For these reasons Architectural page mockup are very useful tools during
conceptual design for complimenting the blueprint view of the site. Mockups are
quick and dirty textual documents that show the content and links of major pages
on the website. They enable you to clearly communicate whatever the implications
are, of the architecture at the page level. They are also very useful when used in
conjunction with scenarios. They help the people to see the site in action before
any code is written. Finally, they can be employed in some basic usability tests to
see if users actually follow the scenarios as expected by you. Keep in mind that
you only need to mockupthe major pages of the web site. These mockups and the
designs that derive from them can serve as templates for the design of subsidiary
pages.
The mockups are easier to read as comparative to blueprints. By integrating
various aspects of the organizational labelling, and navigation systems in to one
view, they will help to understand the architecture. In laying out the content on a
page mockup, you should try to show the logical visual grouping of the content
items. Placing a content group at the top of the page or using a larger font size
indicates the relative importance of that particular content.While the graphic
designer will make the final and more detailed layout decisions you can make a
good start with such mockups.
CHAPTER 2
DYNAMIC HTML AND
WEB DESIGNING
DOM
The DOM is what allows you to access any part of your Web page to change it
with HTML. Every part of a Web page is specified by the DOM and using
its consistent naming conventions you can access them and change their
properties.The HTML DOM is the W3C standard Document Object Model for
HTML. It defines a standard set of objects for HTML, and a standard way to access
and manipulate them.DHTML is about using the DOM to access and manipulate
HTML elements.
DYNAMIC HTML AND WEB DESIGNING
35
Scripts
Scripts written in either JavaScript or ActiveX are the two most common scripting
languages used to activate DHTML. You use a scripting language to control the
objects specified in the DOM. JavaScript is the scripting standard for HTML.
DHTML is about using JavaScript to control access and manipulate HTML elements.
XHTML
XHTML or HTML is used to create the page itself and build the elements for the
CSS and the DOM to work on.
According to the World Wide Web Consortium (W3C):
“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."
Real-time positioning
When most people think of DHTML, Real time positioning is expected. Objects,
images, and text moving around the Web page. This can allow you to play interactive
games with your readers or animate portions of your screen.
Dynamic Fonts
This is a Netscape only feature. Netscape developed this to get around the problem
that designers had with not knowing what fonts would be on a reader’s system.
36 ZERO TO MASTERY IN WEB DEVELOPMENT
With dynamic fonts, the fonts are encoded and downloaded with the page, so that
the page always looks how the designer intended it to.
Data binding
This is an IE only feature. Microsoft developed this to allow easier access to databases
from Web sites. It is very similar to using a CGI to access a database, but uses an
ActiveX control to function. This feature is very advanced and difficult to use for
the beginning DHTML writer.
• Target Audience: Is there a specific group of people that will help you
reach your goals? It is helpful to identify the “ideal" person you want to
visit your web site. This will later help to determine the best design
style for your site.
• Content: What kind of information will the audience be looking for on
your web site? Are they looking for specific information, a particular
product or service, online ordering…?
Planning
Using the information that is collected from phase one, it is time to put together a
plan for your web site. At this point a site map is developed.The site map contains
a list of all main topic areas of the site, as well as sub-topics, if there are any. This
serves as a guide as to what content will be on the site, and is essential to developing
a consistent, easy to understand navigational system. The end-user of the web site
must be kept in mind when designing your site. A good user interface creates an
easy way to navigate web site. During this phase, web designer will also help you
decide what technologies should be implemented.
Designing
Drawing from the information gathered up to this point, it’s time to determine the
look and style of your site.Target audience is one of the key factors taken into
consideration. A site aimed at teenagers, for example, will look much different
than one meant for a financial institution.Your web designer will create one or
more prototype designs for your web site. This is typically a .jpg image of what the
final design will look like. Either way, your designer should allow you to view
your project throughout the design and development stages. The most important
reason for this is that it gives you the opportunity to express your likes and dislikes
on the site design.In this phase, communication between both you and your designer
is crucial to ensure that the final web site will match your needs and taste.
Development
In developmental stage the web site itself is created. At this time, your web designer
will take all of the individual graphic elements from the prototype and use them to
create the actual, functional site.This is basically done by first developing the home
page, followed by a “shell" for the interior pages. The shell serves as a template for
the content pages of your site, as it contains the main navigational structure for the
web site. Once the shell has been created, your designer will take your content and
distribute it throughout the site, in the appropriate areas.This entire time, your
designer should continue to make your in-progress web site available to you for
viewing, so that you can suggest any additional changes or corrections you would
like to have done.
DYNAMIC HTML AND WEB DESIGNING
43
Testing
At this point, web designer will test the web site. They will test things such as the
complete functionality of forms or other scripts, as well last testing for last minute
compatibility issues (viewing differences between different web browsers), ensuring
that your web site is optimized to be viewed properly in the most recent browser
versions.
A good web designer is one who is well versed in current standards for web
site design and development. As part of testing, your designer should check to be
sure that all of the code written for your web site validates. Valid code means that
your site meets the current web development standards.
Once you give your web designer final approval, it is time to deliver the site.
An FTP (File Transfer Protocol) program is used to upload the web site files to
your server. Most web designers offer domain name registration and web hosting
services as well. Once these accounts have been setup, and your web site uploaded
to the server, the site should be put through one last run-through. This is just
precautionary, to confirm that all files have been uploaded correctly, and that the
site continues to be fully functional.
Maintenance
The development of your web site is not necessarily over, though. One way to
bring repeat visitors to your site is to offer new content or products on a regular
basis. Most web designers will be more than happy to continue working together
with you, to update the information on your web site. Many designers offer
maintenance packages at reduced rates, based on how often you anticipate making
changes or additions to your web site.
3. A footer that lables a page by identifying its author, data of creation, and
version number.
<head>
<title> Title of the <title> tag contains the web
web page</title> page title.
</head>
<head> tag contains
information about the web.
The id Attribute:
This attribute can be used to uniquely identify any element within a page. There
are few reasons that you might want to use an id attribute on an element:
• If an element carries an id attribute as a unique identifier it is possible to
identify just that element and its content.
• If you have two elements of the same name within a Web page, you can
use the id attribute to distinguish between elements that have the same
name.
the range A-Z or a-z and may be followed by letters (A-Za-z), digits (0-9), hyphens
(“-"), underscores (“_"), colons (“:"), and periods (“."). The value is case-
sensitive.The following example uses the ID attribute to identify each of the first
two paragraphs of a document:<P ID=firstpr>My 1 st paragraph.</P><P
ID=secondpr>My 2ndparagaph.</P>The paragraphs in the example could have
style rules associated with them through their ID attributes. The following
Cascading Style Sheet defines unique colors for the two paragraphs:
P#firstpr
{
color: pink;
background: none
}
P#secondpr
{
color: purple;
background: none
}
Example
<html>
<head>
<title>ID rule Example </title>
<style type="text/css">
<!—
#ideg {background-color:green;}
—>
</style>
</head>
<body>
<p> hello </p>
<p id="ideg"> welcome </p>
<h1 id="ideg">to HTML </h1>
<p> its interesting </p>
</body>
</html>
Output
DYNAMIC HTML AND WEB DESIGNING
49
• onselect: The onselect event is triggered when a user selects some text in
the text field.
• onchange: The onchange event is fired when a control losses the input
focus and its value has been modified since gaining focus.
Example:
<html>
<head>
</head>
<body onload=’alert(“Event demo loaded");’>
<form onreset=’alert(“Form reset");’ onsubmit=’alert(“Form submit");’>
<ul>
<li>onblur: <input type="text" value="Click into field and then leave" size="40"
onblur=’alert(“Lost focus");’ />
<br /><br /></li>
<li>onclick: <input type="button" value="Click Me" onclick=’alert(“Button
click");’ /><br /><br /></li>
<li>onchange: <input type="text" value="Change this text then leave" size="40"
onchange=’alert(“Changed");’ />
<br /><br /></li>
<li>ondblclick: <input type="button" value="Double-click Me"
ondblclick=’alert(“Button double-clicked");’ />
<br /><br /></li>
<li>onfocus: <input type="text" value="Click into field" onfocus=’alert(“Gained
focus");’ /><br /><br /></li>
<li>onkeydown: <input type="text" value="Press key and release slowly here"
size="40" onkeydown=’alert(“Key down");’ /><br /><br /></li>
<br /><br /></li>
<li>onkeyup: <input type="text" value="Type and release" size="40"
onkeyup=’alert(“Key up");’ /><br /><br /></li>
<li>onload: Alert presented on initial document load.<br /><br /></li>
<li>onmousedown: <input type="button" value="Click and hold"
onmousedown=’alert(“Mouse down");’ />
<br /><br /></li>
<li>onmousemove: Move mouse over this
<a href="" onmousemove=’alert(“Mouse moved");’>link</a><br /><br /></li>
<li>onmouseout: Position
mouse <a href="" onmouseout=’alert(“Mouse out");’>here</a>
DYNAMIC HTML AND WEB DESIGNING
55
and now leave.<br /><br /></li>
<li>onmouseover: Position mouse over this
<a href=""onmouseover=’alert(“Mouse over");’>link</a><br /><br /></li>
<li>onmouseup: <input type="button" value="Click and release"
onmouseup=’alert(“Mouse up");’ /><br /><br /></li>
<li>onreset: <input type="reset" value="Reset Demo" /><br /><br /></li>
<li>onselect: <input type="text" value="" size="40" onselect=’alert(“Selected");’
/><br /><br /></li>
<li>onsubmit: <input type="submit" value="Test Submit" /><br /><br /></li>
<li>onunload: Try to leave document by following this
<a href="http://www.yahoo.com">link</a>.<br /><br /></li>
</ul>
</form>
</body>
</html>
56 ZERO TO MASTERY IN WEB DEVELOPMENT
Text-Level Elements
These don’t cause paragraph breaks. Text level elements that define character styles
can generally be nested. They can contain other text level elements but not block
level elements.These elements are used to mark up text inside block level elements.
DYNAMIC HTML AND WEB DESIGNING
59
Some block level elements exclude certain text level elements, and some text level
elements may only appear inside specific block level elements.
Text-level elements in HTML can be categorized as: physical and logical.
Physical elements, such as <b> for bold and <i> for italic, are used to specify how
the text should be rendered. Logical elements, such as <strong>and <em>, indicate
what the text is, but not necessarily how it should look. Although common
renderings exist for logical text elements, the ambiguity of these elements and the
limited knowledge of this type of document structuring have reduced their use.
This is <tt>Monospaced</tt><br/>
This is <u> Underlined </u><br/>
This is <strike> Strike-through</strike><br/>
This is also<s> Strike-through</s><br/>
This is <big>Big</big><br/>
This is even<big><big>Bigger</big></big><br/>
This is <small> Small </small><br/>
This is even<small><small> Smaller</small></small><br/>
This is <sup> Superscript</sup><br/>
This is<sub> Subscript</sub><br/>
This is <b><i>.<u> Bold, Italic, Underline</b></i></u>
</p>
</body>
</html>
Figure Screen Shot shows the rendering of the physical text elements:
DYNAMIC HTML AND WEB DESIGNING
61
Logical Elements
Logical elements indicate the type of content that they enclose. The browser is
relatively free to determine the presentation of that content, although there are
expected renderings for these elements that are followed by nearly all browsers.
Plain and simple, will a designer think <strong> or <b>? As mentioned previously,
HTML purists push for <strong> because a browser for the blind could read strong
text properly. For the majority of people coding Web pages, however, HTML is
used as a visual language, despite its design intentions. Even when logical elements
are used, many developers assume their default rendering in browsers to be static.
<h1> tags always make something large in their minds.
Experts know the beauty and intentions behind logical elements, and with
style sheets logical elements will continue to catch on and eventually become the
dominant form of page design. Even at the time of this writing, a quick survey of
large sites shows that logical text elements are relatively rare. However, to embrace
the future and style sheets, HTML authors should strongly reexamine their use of
these elements.
Logical markup
• EM - Emphasized text
• STRONG - Strongly emphasized
• DFN - Definition of a term
• CODE - Code fragment
• SAMP - Sample text
• KBD - Keyboard input
• VAR - Variable
• CITE - Short citation
The following example uses all of the logical elements in a test document:
<html>
<head>
<title> Logical Text Elements</title>
</head>
<body>
<h1 align="center" >Logical Text Elements</h1>
<hr/>
<p>
<acronym>www<acronym> is an acronym
<abbr>www</abbr> is an abbreviation
This is <em>Emphasis</em><br/>
62 ZERO TO MASTERY IN WEB DEVELOPMENT
Figure Screen Shot shows the rendering of the logical elements under Opera:
Hyperlinks
In web terms, a hyperlink is a reference or you can say an address to a resource on
the web. Hyperlinks can point to any resource on the web: an HTML page, an
image, a sound file, a movie, etc. A hyperlink (or link) is a word, group of words, or
image that you can click on to jump to another document.The most important attribute
of the <a> element is the href attribute, which indicates the link’s destination.
DYNAMIC HTML AND WEB DESIGNING
65
By default, links will appear as follows in all browsers:
• An unvisited link is underlined and blue
• A visited link is underlined and purple
• An active link is underlined and red
Syntax
<a href="url">Link text</a>
The href attribute specifies the destination of a link.
Example
<a href="http://www.google.com/">Visit google</a>
This will display like this: Visit google
Clicking on this hyperlink will send the user to Google’s homepage.
Here is the meaning of each part of this example:
<a starts the anchor
Href stands for “hypertext reference"
http://www.google.com/ the URL of the external document
> marks the end of the reference portion of the tag
Visit google the text that will appear and be clickable
</a> ends the anchor
Links and anchors enable you to connect documents to one another. There are
three kinds of connections:
• Connecting two documents in the same directory.
• Connecting two documents in different directories.
• Connecting one part of a document to a particular location within a document.
In the above screenshot u can see the image, when you click on this image the
url mentioned in href attribute will get open in a new tab because the value of
attribute target is specified as “_blank".
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<hr />
<p><a name="bottom" href="#top">return to top</a>
<a href="#middle">go to middle</a></p>
</body>
</html>
DYNAMIC HTML AND WEB DESIGNING
69
• Title Attribute
The title attribute specifies extra information about an element.The information is
most often shown as a tooltip text when the mouse moves over the element.
<body>
...some text...
<P>You’ll find a lot more in <A href="chapter2.html" title="Go to chapter
two">chapter two</A>.
<A href="./chapter2.html" title="Get chapter two.">chapter two</A>.
</body>
• Accesskey Attribute
The accesskey attribute specifies a shortcut key to activate or focus an element.
Value provided for access key should be a single letter.
Example:
<a href="http://www.google.com/html" accesskey="g">visit google</a>
<a href="http://www.yahoo.com/css" accesskey="y">visit yahoo</a>
To visit Google use “ALT+g" & for Yahoo “ALT+y"
• Target Attribute
This attribute specifies where to open the linked document.
Syntax
<a target="_blank|_self|_parent|_top|framename">
70 ZERO TO MASTERY IN WEB DEVELOPMENT
Attribute Values
Value Description
blank It will open the linked document in a new window or tab
self It will open the linked document in the same frame as it was
clicked (this is default)
parent It will open the linked document in the parent frame
top It will open the linked document in the full body of the window
framename It will open the linked document in a named frame
• Tabindex Attribute
This attribute specifies the tab order of an element when the “tab" button is used
for navigating between the various links.
Example
<html>
<body>
<a href="http://www.yahoomail.com/" tabindex="2">Yahoo Mail!!</a><br>
<a href="http://www.google.com/" tabindex="1">Google</a><br>
<a href="http://www.microsoft.com/" tabindex="3">Microsoft</a>
</body>
</html>
For a server side image map, put an image inside a link, and set the ISMAP
attribute on the IMG (just the name, it does not need a value). When the link is
clicked, the browser will request the given link, and add ?x,y on the end of it, as
the click offset from the left,top corner of the image (such as a.html?47,8). If the
user is not using a mouse, then the coordinates will be 0,0.
<a href="a.html"><imgsrc="b.gif" alt="" ismap></a>
Example
<html>
<body>
<img src="abc.jpg" width="145" height="126" usemap="#xyz">
<map name="xyz">
<area shape="rect" coords="0,0,82,126" href="a.htm">
<area shape="circle" coords="90,58,3" href="b.htm">
<area shape="circle" coords="124,58,8" href="c.htm">
</map>
</body>
</html>
In above example, we use the <area> tag in conjunction with the shape and
coord attributes. These accept the following attributes:
Shape Defines a shape for the clickable area. Possible values:
• Default: This covers the entire image, and does not need
the coords attribute.
• Rect: This expects four coordinates. The horizontal position
of the top-left corner, the vertical position (from the top of
the image) of the top-left corner, the horizontal position of
the bottom-right corner and the vertical position of the
bottom-right corner. An example would be:
shape="rect" coords="10,20,75,40"·
• Circle: This expects three coordinates. The horizontal
position of the centre, the vertical position of the centre and
the radius of the circle (percentage radii are taken as a
percentage of the shorter side of the image). An example
would be:
shape="circle" coords="50,80,20"
• Poly: This expects as many pairs of coordinates as you need
to make your polygon. These can make any polygon shapes
you need, and can have sloping lines. All coordinates are
DYNAMIC HTML AND WEB DESIGNING
73
specified as horizontal position then vertical position, with
all of them in a long comma separated list. The last pair of
coordinates can optionally match the first. An example would
be:
shape="poly" cords=" 228, 316, 243, 316, 325, 229, 322, 217,
228, 316"
Coords Specifies the coordinates of the clickable area. Coordinates
are specified as follows:
• rect: left, top, right, bottom
• circle: center-x, center-y, radius
• poly: x1, y1, x2, y2, ...
Image maps can be placed anywhere in the document (inside elements where
inline content is allowed), and can be before or after the image that use them.The
AREA element should be treated as a block level element, and must be placed.
Directly inside the MAP element, not inside any of the other block level content
inside it.
key
Documents Semantic Network
terms
2.16.1 How would you define the main goals of the Semantic Web?
The Semantic Web is a Web of data. There is a lot of data we all use every day, and
it’s not part of the Web. For example, I can see my bank statements on the web, and
my photographs, and I can see my appointments in a calendar. But can I see my
photos in a calendar to see what I was doing when I took them? Can I see bank
statement lines in a calendar? Why not? Because we don’t have a web of data.
Because data is controlled by applications, and each application keeps it to itself.
The vision of the Semantic Web is to extend principles of the Web from
documents to data. Data should be accessed using the general Web architecture
using, e.g., URI-s; data should be related to one another just as documents (or
portions of documents) are already. This also means creation of a common
framework that allows data to be shared and reused across application, enterprise,
and community boundaries, to be processed automatically by tools as well as
manually, including revealing possible new relationships among pieces of data.
Semantic Web technologies can be used in a variety of application areas; for
example: in data integration, whereby data in various locations and various formats
can be integrated in one, seamless application; in resource discovery and
classification to provide better, domain specific search engine capabilities; in
cataloging for describing the content and content relationships available at a
particular Web site, page, or digital library; by intelligent software agents to facilitate
knowledge sharing and exchange; in content rating; in describing collections of
pages that represent a single logical “document"; for describing intellectual property
rights of Web pages, and in many others.
DYNAMIC HTML AND WEB DESIGNING
75
2.16.2 What are the major building blocks of the Semantic Web?
In order to achieve the goals, the most important is to be able to define and
describe the relations among data (i.e., resources) on the Web. This is not like the
usage of hyperlinks on the current Web that connect the current page with
another one: the hyperlinks defines a relationship between the current page and
the target. One major difference is that, on the Semantic Web, such relationships
can be established between any two resources, there is no notion of “current"
page. Another major difference is that the relationship (i.e, the link) itself is
named, whereas the link used by a human on the (traditional) Web is not and
their role is deduced by the human reader. The definition of those relations
allow for a better and automatic interchange of data. RDF, which is one of the
fundamental building blocks of the Semantic Web, gives a formal definition for
that interchange.
“The Semantic Web is a vision: the idea of having data on the Web defined
and linked in a way that it can be used by machines not just for display purposes,
but for automation, integration and reuse of data across various applications"
The Semantic Web is an evolving development of the World Wide Web in
which the meaning (semantics) of information and services on the web is defined,
making it possible for the web to understand and satisfy the requests of people and
machines to use the web content.
At its core, the semantic web comprises a set of design principles, collaborative
working groups, and a variety of enabling technologies. Some elements of
the semantic web are expressed as prospective future possibilities that are yet
to be implemented or realized. Other elements of the semantic web are expressed
in formal specifications. Some of these include Resource Description
Framework (RDF), a variety of data interchange formats (e.g. RDF/XML, N3,
Turtle, N-Triples), and notations such as RDF Schema (RDFS) and the
Web Ontology Language (OWL), all of which are intended to provide a
formal description of concepts, terms, and relationships within a given knowledge
domain.
GIF Images
GIF is the most widely supported image format on the Web. Originally introduced
by CompuServe, there are actually two types of GIF: GIF 87 and GIF 89a. Both of
them support 8-bit color (256 colors), use the LZW (Lempel-Ziv-Welch) lossless
compression scheme, and generally have the .gif file extension. Transparency and
Animation is supported by GIF 89a. GIF images use a basic form of compression
called run-length encoding. This lossless compression works well with large areas
of continuous color.
JPEG
The other common Web image format is JPEG, indicated by a filename ending
with .jpg or .jpeg. JPEG, which stands for the Joint Photographic Experts Group
(the name of the committee that wrote the standard) is a lossy image format designed
for compressing photographic images that may contain thousands, or even millions,
of colors or shades of gray. As JPEG is a lossy image format, there is some trade-
off between image quality and file size. However, the JPEG format stores high-
quality 24-bit color images in a smaller amount of space than GIF, thus saving disk
space or download time on the Web.
PNG
The Portable Network Graphics (PNG) format is an emerging format that has all of
the features of GIF in addition to several other features. The compression algorithm
for PNG is not proprietary compared to GIFs, which use LZW (owned by Unisys).
PNG’s compression algorithm is slightly better than GIF’s, as shown in Figure 2.3
but this alone is probably not much of a reason to give up GIF images given the
browser compatibility problems that still plague the PNG format. PNG also supports
slightly improved interlacing.
DYNAMIC HTML AND WEB DESIGNING
77
Gif PNG
Image Use
The first thing to consider is that the quality of the image being used will affect the
outcome of the page layout. Even when armed with a scanner, digital camera, or
software such as Adobe Photoshop, Adobe Illustrator or Macromedia Fireworks,
you might be a long way from being able to produce aesthetically pleasing Web
pages. Don’t fret, you would never expect that just owning a copy of a word
processor would destine you to produce a huge number of books; it takes skill,
patience, and years of practice.
78 ZERO TO MASTERY IN WEB DEVELOPMENT
Straight lines, basic colors, and modest use of imagery should produce a clean
and uncluttered design. Furthermore, the simple design will load very fast! When
you decide to use image on your site, whether for just decoration or for the
information, don’t skimp on quality. If you use the clip art from some free Web
site, your site will reflect this. Fortunately, there are many sites that sell the
professional quality clip-illustrations and photographs relatively at a cheaper price.
While this might save money, don’t just right click your way to a nice new image
free of charge. Web users are sophisticated enough to know when they’re having a
cheap site foisted on them.
Example
<html>
<body>
<form action="abc.asp">
First name: <input type="text" name="fname"><br>
<input type="image" src="submit.gif" alt="Submit" width="48" height="48">
</form>
<p>Click on the image, and the input that you entered will be sent to a page on the
server called “abc.asp".</p>
<p>The image input type sends the X and Y coordinates of the click that activated
the image button as default.</p>
</body>
</html>
Output:
Click on the image, and the input that you entered will be sent to a
page on the server called "abc.asp".
The image input type sends the X and Y coordinates of the click
that activated the image button as default.
After entering the name as ‘pridhi’ you will get the following output:
Output
<body>
<table border="2">
<caption>
Student Table
</caption>
<tr>
<th>Roll No.
<th colspan="2">NAME
<th colspan="2">Phone NO
<th colspan="2">Address
<tr>
<th> 
<th>FName
<th>LName
<th>Landline
<th>Mobile
<th>House no & city
<th>State
<tr>
<td>09/IT/39
<td>Pridhi
<td>Arora
<td>45432
<td>987654321
<td>xyz faridabad
<td>Haryana
<tr>
<td>09/IT/38
<td>Pawan
<td>Bhadana
<td>23454
<td>123456789
<td>abc faridabad
<td>Haryana
DYNAMIC HTML AND WEB DESIGNING
83
</body>
</html>
Output
Student Table
Roll No. NAME Phone No. Address
F Name L Name Landline Mobile House no & city State
09/IT/39 Pridhi Arora 45432 987654321 xyz faridabad Haryana
09/IT/38 Pawan Bhadana 23454 123456789 abc faridabad Haryana
<title>Frames example</title>
</head>
<frameset rows="10%,70%,10%,10%">
<frame src="top_frame.htm" />
<frame src="main_frame.htm" />
<frame src="middle_frame.htm" />
<frame src="bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames!!
</body>
</noframes>
</frameset>
</html>
Now create four HTML files called top_frame.htm, main_frame.htm,
middle_frame.htm and bottom_frame.htm to be loaded into the frames with some
content.
Output:
top frame.htm
main_frame.htm
middle_frame.htm
bottom_frame.htm
Example 2
<html>
<head>
<title>My first Frames Page</title>
</head>
<frameset cols="120,*">
<frame src="a.htm" name="menu">
<frameset rows="*,50">
DYNAMIC HTML AND WEB DESIGNING
85
<frame src="b.htm" name="main">
<frame src="c.htm" name="bottom">
</frameset>
</frameset>
</html>
Output:
a.htm b.htm
c.htm
The <frameset> Element Attributes
1. cols: specifies how many columns are contained and the size of each
column in the frameset. You can specify the width of each column in one
of four ways:
• Absolute values in pixels. For example to create four vertical frames,
use cols= "50, 500, 50, 100".
• A percentage of the browser window. For example to create four vertical
frames, use cols= "10%, 70%, 10%, 10%".
• Using a wildcard symbol. For example to create three vertical frames,
use cols= "10%, *, 10%". In this case wildcard takes remainder of the
window.
• As relative widths of the browser window. For example to create three
vertical frames, use cols="3*,2*,1*". This is an alternative to
percentages. You can use the relative widths of the browser window.
Here the window is divided into sixths: the first column takes up half of
the window, the second takes one third, and the third takes one sixth.
2. rows: This works just like the cols attribute and can take the same values,
but it is used to specify the rows in the frameset. For example to create
three horizontal frames, use rows="10%, 10%, 80%". You can specify the
height of each row in the same way as explained above for columns.
3. border: This specifies the width of the border of each frame in pixels. For
example border="6". A value of zero specifies that no border should be
there.
86 ZERO TO MASTERY IN WEB DEVELOPMENT
Layer in HTML
The <layer> tag is used to position and animate the elements in a page through
scripting. A layer can be thought of as a separate document that resides on top of
the main one, all existing within one window.
This example creates three overlapping layers. The back one is pink, the middle
one is purple, and the front one is yellow.
<html>
<head>
<title>HTML Layer Tag</title>
</head>
<body>
<p>This example creates three overlapping layers. The back one is pink, the
middle one is purple, and the front one is yellow. </p>
<layer id="layer1" top="250" left="50" width="200"
height="200" bgcolor="pink">
<p>first layer</p>
</layer>
<layer id="layer2" top="350" left="150" width="200"
height="200" bgcolor="purple">
<p>second layer</p>
</layer>
<layer id="layer3" top="450" left="250" width="200"
height="200" bgcolor="yellow">
<p>third layer</p>
88 ZERO TO MASTERY IN WEB DEVELOPMENT
</layer>
</body>
</html>
<audio controls="controls"loop="loop"preload="none"autoplay="autoplay">
<source src="a.ogg" type="audio/ogg">
<source src="a.mp3" type="audio/mpeg">
</audio>
</body>
</html>
Attributes
Attribute Value Description
Autoplay Autoplay It basically specifies that the audio will start
playing as soon as it is ready
Controls Controls It specifies that audio controls should be
displayed (such as a play/pause button etc).
Loop Loop It specifies that the audio will start over
again, every time it is finished
preload auto It specifies if and how the author thinks
Metadata the audio should be loaded when the page
none loads
Src URL It specifies the URL of the audio file
The <source> tag is used to specify multiple media resources for media
elements, such as <video> and <audio>.This tag allows you to specify alternative
video/audio files which the browser may choose from, based on its media type or
codec support.
Tag Description
<video> It defines a video or movie
<source> It defines multiple media resources for media elements,
such as <video> and <audio>
<track> It defines text tracks in mediaplayers
The<video> tag specifies video, such as a movie clip or other video streams.
92 ZERO TO MASTERY IN WEB DEVELOPMENT
Attributes
Attribute Value Description
Autoplay autoplay The autoplay attribute is a boolean attribute.
It specifies that the video will start playing
as soon as it is ready
Controls Controls It specifies that video controls should be
displayed (such as a play/pause button etc).
Height Pixels It specifies the height of the video player
Loop Loop It specifies that the video will start over
again, every time it is finished
Muted Muted It specifies that the audio output of the video
should be muted
poster url It specifies an image to be shown while the
video is downloading, or until the user hits
the play button
Preload Auto It specifies if and how the author thinks
Metadata the video should be loaded when the page
none loads
Src url It specifies the URL of the video file
Width Pixels It specifies the width of the video player
Example
<html>
<body>
<video width="320" height="240" controls="controls" autoplay="autoplay">
<source src="a.mp4" type="video/mp4">
<source src="a.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</body>
</html>
The <source> tag is used to specify multiple media resources for media
elements, such as <video> and <audio>.This tag allows you to specify alternative
video/audio files which the browser may choose from, based on its media type or
codec support.
DYNAMIC HTML AND WEB DESIGNING
93
2.23 Forms in HTML
An HTML form is a section of a document containing normal content, markup,
special elements called controls (checkboxes, radio buttons, menus, etc.), and labels
on those controls. Users generally “complete" a form by modifying its controls
(entering text, selecting menu items, etc.), before submitting the form for processing
(e.g., to a Web server, to a mail server, etc.). A form is simply an area that can
contain form fields.Forms are a characteristic of the HTML standard that let authors
collect information provided by the visitors. These forms can be useful to collect
personal information, contact information, preferences, opinions, or any kind of
user input the author may need.
A form can be inserted in HTML documents using the HTML form element
which acts as a container for all the input elements. All the information collected
by a form can be submitted to a processing agent (a file containing a script made to
process this information) that’s usually specified in the “action" attribute. To handle
forms’ data you must use a server side script.You can also specify how the data
will be sent in the value of the “method" attribute: “post" (the form’s data is attached
to the body of the form) or “get" (the form’s data is attached to the URL). When
the visitor clicks a submit button, the content of the form is usually sent to a
program that runs on the server.
The <form> tag tells the browser where the form starts and ends. You can add
all kinds of HTML tags between the <form> and <form> tags. This means that a
form can easily include a table or an image along with the form fields.
Forms Controls
These fields can be added to your forms:
• Text field: <input type="text"> defines a one-line input field that a user
can enter text into.
• Password field: <input type="password"> defines a password
field, characters in a password field are masked (shown as asterisks or
circles).
• Hidden field:<input type="hidden">Hidden fields are similar to text fields.
The difference is that the hidden field does not show on the page. Therefore
the visitor can’t type anything into a hidden field.
• Text area: The <textarea> tag defines a multi-line text input control. The
size of a text area can be specified by the cols and rows attributes
• Check box: <input type="checkbox"> defines a checkbox. Checkboxes
let a user select ZERO or MORE options of a limited number of choices.
• Radio button: <input type="radio"> defines a radio button. Radio buttons
let a user select ONLY ONE of a limited number of choices
• Drop-down menu: The <select> element is used to create a drop-down
94 ZERO TO MASTERY IN WEB DEVELOPMENT
list. The <option> tags inside the <select> element define the available
options in the list.
• Submit button: <input type="submit"> defines a submit button. A submit
button is used to send form data to a server. The data is sent to the page
specified in the form’s action attribute.
• Reset button: When a visitor clicks a reset button, the entries are reset to
the default values.
Example:
Save the below text with form.html
<html>
<body>
<form>
Enter Name <input type="text">
<br>Enter Password <input type="password">
<br>
Enter Roll No <inputtype="text">
<br>Enter Branch <select>
<option>CSE
<option>ME
<option>ECE
<option>IT
</select>
<br>
Gender
<input type="radio" name="Gen">Male
<input type="radio" name="Gen">Female
<br>
DOB date <select>
<option>1
<option>2
<option>3
<option>4
<option>5
<option>6
<option>7
DYNAMIC HTML AND WEB DESIGNING
95
<option>8
<option>9
<option>10
<option>11
<option>12
<option>13
<option>14
<option>15
<option>16
<option>17
<option>18
<option>19
<option>20
<option>21
<option>22
<option>23
<option>24
<option>25
<option>26
<option>27
<option>28
<option>29
<option>30
<option>31
</select>
Month <select>
<option>Jan
<option>Feb
<option>Mar
<option>Apr
<option>May
<option>June
<option>July
<option>Aug
96 ZERO TO MASTERY IN WEB DEVELOPMENT
<option>Sep
<option>Oct
<option>Nov
<option>Dec
</select>
Year <select>
<option>1985
<option>1986
<option>1987
<option>1988
<option>1989
<option>1990
<option>1991
<option>1992
<option>1993
<option>1994
</select>
<br>
Address
<textarea rows="4"columns="3">
</textarea>
<br>
Enter Hobbies
<br>
<input type="checkbox" checked>Listening Music
<br>
<input type="checkbox" checked>
Playing Cricket
<br>
<input type="checkbox">
Reading Novels
<br>
<input type="button"value="Submit">
<input type="button" value="Reset">
</form>
</body></html>
Output:
DYNAMIC HTML AND WEB DESIGNING
97
Example 2
<html>
<body>
<h2>Contact Form</h2>
<form action="xyz.php" method="post" name="form1" id="form1">
<table border="0">
<tr>
<td>First Name:</td>
<td><input name="firstname" id="firstname" size="40" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastname" id="lastname" size="40" /></td>
</tr>
<tr>
<td>Company:</td>
<td><input name="company" id="company" size="40" /></td>
</tr>
98 ZERO TO MASTERY IN WEB DEVELOPMENT
<tr>
<td>Address:</td>
<td><input name="address" id="address" size="40" /></td>
</tr>
<tr>
<td>City:</td>
<td><input name="city" id="city" size="25" /></td>
</tr>
<tr>
<td>State:</td>
<td><input name="state" id="state" size="2" /></td>
</tr>
<tr>
<td>Country:</td>
<td><input name="country" id="country" size="25" /></td>
</tr>
<tr>
<td>Postal Code:</td>
<td><input name="zip" id="zip" size="10" /></td>
</tr>
<tr>
<td colspan="2"><br />
Enter any comments below:<br />
<textarea name="comments" id="comments" rows="5" cols="45">
</textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
<br />
<br /></td>
</tr>
DYNAMIC HTML AND WEB DESIGNING
99
</table>
</form>
</body>
</html>
Output
Example3
<html>
<head>
<title>forms</title>
<body>
<b><u>Admission Form</u></b>
<form>
<pre>NAME<input type="text" maxlength=20><br>
AGE<input type="text"><br>
PASSWORD<input type="password"><br>
GENDER<input type="radio" name="r1">male
<input type="radio" name="r1">female<br>
COURSES<input type="radio" name="r2">Btech<br>
100 ZERO TO MASTERY IN WEB DEVELOPMENT
Output
STYLE SHEETS
101
CHAPTER 3
STYLE SHEETS
• Inline style
• Internal style sheet
• External style sheet
• Importing a style sheet
3.2.1 Inline Styles
An inline style allows you to change the behaviour of an html tag to achieve a
desired appearance that you wish to have. The change effected by the inline style is
a local one. That is, it applies only to a single tag where the inline style is included.
To use inline styles,the style attribute is used in the relevant tag. The style attribute
can contain any CSS property. If you want to add a style inside an HTML element
all you have to do is specify the desired CSS properties with the style HTML
attribute. The example shows how to change the color and the right margin of a
paragraph:
<p style=”color: pink;margin-right:20px;”>Hie !! We are applying a style to
a paragraph</p>
The example shows how to change the background color and the text color of
a paragraph:
<p style=”background: blue; color: white;”>A new background and font color
with inline CSS</p>
Example1:
<html>
<body>
<h2 style=”font-size:20pt;”> This heading has a 20pt font size</h2>
</body>
</html>
STYLE SHEETS
103
Example2:
<html>
<head>
<Title>Inline</Title>
</head>
<body bgcolor=”pink”>
<center><H1 Style=”background-color:blue” id=”h1">Inline Style</H1></
Center>
<P Style=”font-size:14pt” “font-weight:bold” “font-style:italic” id=”p1">
This is a type of style setting. Here the fonts size of the paragraph is 14pt.
The font appears bold and the font style appears in italic.</P>
<P>
The different types of styles are <Br>
<Span Style=”font-weight:bold” id=”s1">
Inline Style<Br>
Embeded Style<Br>
Linked Style<Br>
</span>
</p>
<p style=”font-size=16pt” “Color:yellow” id=”p2"> This example describes
the inline style</P>
</body>
</html>
background-color:purple;
}
</style>
</head>
<body>
<h3>Learning CSS</h3>
<p>Hello students! I hope now you know how to change the background
color using CSS.</p>
</body>
</html>
Example to set the text color of different element:
<html>
<head>
<style>
body {color:red;}
h1 {color:purple;}
p.ab {color:blue;}
</style>
</head>
<body>
<h4>This is heading with purple color</h4>
<p>Red color for this paragraph has been defined in the body selector.</p>
<p class=”ab”>This is a paragraph with class=”ab”. This text is blue.</p>
</body>
</html>
Example for text transformation:
<html>
<head>
<style>
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
</style>
STYLE SHEETS
105
</head>
<body>
<p class=”uppercase”>This is text in Uppercase.</p>
<p class=”lowercase”>THIS IS TEXT IN LOWERCASE.</p>
<p class=”capitalize”>This is text with intial letter in uppercase.</p>
</body>
</html>
Output:
<body>
<h1>CSS font-family</h1>
<p class=”ab”>This is a paragraph, shown in the Times New Roman font.
</p>
<p class=”xy”>This is a paragraph, shown in the Calibri font.</p>
106 ZERO TO MASTERY IN WEB DEVELOPMENT
</body>
</html>
Output:
CSS font-family
This is a paragraph, shown in the Time New Roman font.
p.a2
{
font:italic bold 15px Arial,serif;
}
</style>
</head>
<body>
<p class=”a1 “>This is a paragraph with the properties specified for class
“a1”</p>
STYLE SHEETS
107
<p class=”a2">This is a paragraph with the properties specified for class
“a2”</p>
</body>
</html>
Output:
Example:
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”mystyle.css”>
</head>
<body>
108 ZERO TO MASTERY IN WEB DEVELOPMENT
mystyle.css file
h2{text-transform: uppercase;}
p{font-style:italic;}
<body>
<p>
The color of this paragraph is purple, and has uppercase letters which are
underlined</p>
</body>
</html>
Style.css
<body>
<h1>This is a heading</h1>
<imgsrc=”rk.jpg” width=”195" height=”184" />
</body>
</html>
right:5px;
}
</style>
</head>
<body>
<p class=”pos_fixed”>Some more text</p>
<p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</
p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</
p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</
p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p>
</body>
</html>
fixed
{
position:fixed;
top:90px;
left:40px;
}
</style>
</head>
STYLE SHEETS
111
<body>
<h2>This is text placed in an absolute position</h2>
<fixed>This is text in a fixed position</fixed>
</body>
</html>
h2.pos_right
{
position:relative;
left:20px;
}
</style>
</head>
<body>
<h2>This is a heading with no position</h2>
<h2 class=”pos_left”>This heading is moved left according to its normal
position</h2>
<h2 class=”pos_right”>This heading is moved right according to its normal
position</h2>
<p>Relative positioning moves an element RELATIVE to its original
position.</p>
<p>The style “left:-20px” subtracts 20 pixels from the element’s original left
position.</p>
112 ZERO TO MASTERY IN WEB DEVELOPMENT
Position: Absolute;
Z-Index: 1;
Position: Absolute;
Z-Index: 2;
p { position: relative;
z-index: 1;
background-color: purple;}
</style>
</head>
<body>
<h4>Header Z-Index = 2</h4>
<p>Some text Some text Some text Some text Some text Some text Some
text Some text Some text. This paragraph has a value of z-index as 1, which is less
than the header. So the header has been moved down, using positioning, and is
now resting on top of this paragraph. If we had not defined the z-index, by default
the paragraph would have been on top of the header because it appears later in our
HTML code.</p>
</body>
</html>
Example
<html>
<head>
114 ZERO TO MASTERY IN WEB DEVELOPMENT
<title>Overlapping Elements</title>
<style>
img
{
position:absolute;
left:60px;
top:60px;
z-index:-1;
}
h2
{
position:absolute;
left:70px;
top:35px;
color:pink;
}
fixed
{
position:fixed;
top:135px;
left:70px;
}
p
{
position:absolute;
left:70px;
top:150px;
}
</style>
</head>
<body>
STYLE SHEETS
115
<imgsrc=”xyz.png” width=”243" height=”70" alt=””>
<h2>Text in an absolute position</h2>
<fixed>Text in a fixed position</fixed>
<p>This image uses the absolute position and is placed 50 pixels<br>
from the top and 50 pixels from the left with a z-index of -1, <br>
which moves the image behind the text.</p>
</body>
</html>
116 ZERO TO MASTERY IN WEB DEVELOPMENT
CHAPTER 4
JAVA SERVER PAGES
Web Server
Internet
JSP
Linux OS Servlet Oracle
Engine Database
Windows XP
Figure 4.1 Web server supporting JSP
• The web server recognizes that the HTTP request is for a JSP page and
forwards the request to a JSP engine. This is done by using the URL or
JSP page which ends with .jsp instead of .html.
• The JSP engine loads the JSP page and converts it into servlet content. In
this conversion all template text is converted to println( ) statements and
all JSP elements are converted to Java code that implements the
corresponding dynamic behaviour of the page.
• The JSP engine compiles the servlet into an executable class and forwards
the original request to a servlet engine.
• Servlet engine, a part of the web server loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format, which
the servlet engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser as static
HTML content.
• Finally web browser handles the dynamically generated HTML page inside
the HTTP response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
5. Execute 4. Compile
Request
Hieservlet.class Processing
Phase
INITIALIZATION
Jsplnit
Request lifecycle
Request
Main Logic
JspService()
Response
Shutdown
jspDestroy()
• buffer Attribute:
This attribute specifies buffering characteristics for the server output response object.
It sets the buffer size in kilobytes to handle output generated by JSP. The default
size of the buffer is 8kb. You may code a value of “none” to specify no buffering so
that all servlet output is immediately directed to the response object or you may
code a maximum buffer size in kilobytes, which directs the servlet to write to the
buffer before writing to the response object.
To direct the servlet to write output directly to the response output object, use
the following:
<%@ page buffer=”none” %>
Use the following to direct the servlet to write output to a buffer of size not
less than 8 kilobytes:
<%@ page buffer=”8kb” %>
• autoFlush Attribute:
The autoFlush attribute specifies whether buffered output should be flushed
automatically or not when the buffer is filled, or whether an exception should be
raised to indicate that the condition of buffer overflow.A value of true indicates
automatic buffer flushing and a value of false throws an exception. Default value is
true.The following directive causes the servlet to throw an exception when the
servlet’s output buffer is full:
<%@ page autoFlush=”false” %>
This directive causes the servlet to flush the output buffer when its full:
<%@ page autoFlush=”true” %>
Usually, the buffer and autoFlush attributes are coded on a single page directive
as follows:
<%@ page buffer=”16kb” autoflush=”true” %>
• errorPage Attribute:
The errorPage attribute tells the JSP engine which page to display if there is an
error while the current page runs. It is used to define an error page, if an exception
occurs in the current page, it will be redirected to another page. The value of the
errorPage attribute is a relative URL.The following directive displays
Myerrorpage.jsp when all uncaught exceptions are thrown:
<%@ page errorPage=”Myerrorpage.jsp” %>
• isErrorPage Attribute:
The isErrorPage attribute indicates that the current JSP can be used as the error
page for another JSP.The value of isErrorPage is either true or false. The default
JAVA SERVER PAGES
125
value of this attribute is false.For example, the handleError.jsp sets the isErrorPage
option to true because it is supposed to handle errors:
<%@ page isErrorPage=”true” %>
getCookies(): This method of request object returns all cookies that were
sent with the request information by the client. The cookies are returned
as an array of Cookie Objects. Cookies are used to allow web browsers to
hold some small amounts of information or state data associated with a
user’s web browsing. Common applications for cookies include storing
user preferences, automating low security user “sign on” facilities, and
helping collect data used for “shopping cart” type applications.
The following example gets a list of available cookies.
<html>
<body>
<%
Cookie[] myStoredCookies = request.getCookies();
for(int n=0; n <myStoredCookies.length; n++)
{
out.print(myStoredCookies[n].getName() + “ “);
out.print(myStoredCookies[n].getValue() + “<BR>”);
}
%>
</body>
</html>
Output:
JAVA SERVER PAGES
129
getHeader(String name): This method of request object is used to return
the value of the requested header. The returned value of header is a string.
As a parameter header name is passed which is retrieved by the method
getHeaderNames() of the request object that gives all the HTTP header
names in the enumeration form which has to be converted into string form
later for getting the value of the HTTP header from it one by one.
General syntax of getHeader() of request object is request.getHeader(“String”).
<%@ page import = “ java.util.* “ %>
<html>
<body>
<%
Enumeration enum = request.getHeaderNames();
while (enum.hasMoreElements())
{
String string = (String)enum.nextElement();
out.println(string +”:” + request.getHeader(string)+”<br>”);
}
%>
</body>
</html>
Output:
host:localhost:8080
user-agent: Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/
13.0.1
accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language:en-us,en;q=0.5
accept-encoding:gzip,deflate
connection:keep-alive
cookie:JSESSIONID=e98ae615c498e047443672ba52b4;username=pridhi
cache-control: max-age=0
130 ZERO TO MASTERY IN WEB DEVELOPMENT
<%}%>
Output:
JAVA SERVER PAGES
131
Getparameter.jsp
<html>
<body>
<%
String username, password;
if(request.getParameter(“txtUserName”) == null)
username = “”;
else
username= request.getParameter(“txtUserName”);
if (request. getParameter (“txtPassword”) == null)
password = “”;
else
password = request.getParameter(“txtPassword”);
%>
Your User Name: <%=username %><br/>
Your Password: <%=password %>
</body>
</html>
Output:
JAVA SERVER PAGES
133
getParameterValues(String name)
This method of request object was used to return the value of a requested given
parameter. The returned value of the parameter is a string. If there are a number of
values of parameter to be returned, then the method getParameterValues (String
name) of request object can be used by the programmer. The getParameterValues
(String name) method of request object is used to return all the values of a given
parameter’s request. The returned value of parameter is an array of string objects.
If the requested parameter is found, then the values associated with it are returned
as array of string object. If the requested given parameter is not found, then null
value is returned by the method.
<html>
<body>
<form method=”post”>
<p>Select Items: </p>
<input type=”checkbox” name=”checkBoxes” value=”ITEM 1" />ITEM 1.
<input type=”checkbox” name=”checkBoxes” value=”ITEM 2" />ITEM 2.
<input type=”checkbox” name=”checkBoxes” value=”ITEM 3" />ITEM 3.
<input type=”checkbox” name=”checkBoxes” value=”ITEM 4" />ITEM 4.
<input type=”checkbox” name=”checkBoxes” value=”ITEM 5" />ITEM
5.<br/>
136 ZERO TO MASTERY IN WEB DEVELOPMENT
<body>
<%
out.println(“URI Requested is “ + request.getRequestURI());
%>
<br>
<%
out.println(“Path of Servlet is “ + request.getServletPath());
%>
</body>
</html>
Setattribute.jsp
<html>
<body>
JAVA SERVER PAGES
139
<%
request.setAttribute(“AttributeName”,”This is the Attribute value.”);
String strViewPage=”setattribute1.jsp”;
RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);
if (dispatcher != null)
{
dispatcher.forward(request, response);
}
%>
</body>
</html>
Setattribute1.jsp
<html>
<body>
<%
out.println(request.getAttribute(“AttributeName”));
%>
</body>
</html>
Output:
140 ZERO TO MASTERY IN WEB DEVELOPMENT
setContentType():
This method of response object is used to set the MIME type(Multipurpose Internet
Mail Extension) and character encoding for the page.
General syntax of setContentType() of response object is as follows:
response.setContentType();
For example:
response.setContentType(“text/html”);
The above statement is used to set the content type as text/html dynamically.
addCookie(Cookie cookie):
This method of response object is used to add the specified cookie to the response.
The addcookie method is used to write a cookie to the response. If the user wants
to add more than one cookie, then using this method by calling it as many times as
the user wants will add cookies.
General syntax of addCookie() of response object is as follows:
response.addCookie(Cookie cookie)
addHeader(String name, String value):
This method of response object is used to write the header as a pair of name and
value to the response. If the header is already present, then value is added to the
existing header values.
General syntax of addHeader() of response object is as follows:
response.addHeader(String name, String value)
Here the value of string is given as second parameter and in below example we
provided “xyz” and this gets assigned to the header given in first parameter as
string name and in example its “Author”.
For example:
response.addHeader(“Author”, “xyz”);
containsHeader(String name):
This method of response object is used to check whether the response already
includes the header given as parameter. If the named response header is set then it
returns a true value. If the named response header is not set, the value is returned as
false. Thus, the containsHeader method is used to test the presence of a header
before setting its value. The return value from this method is a Boolean value of
true or false.
General syntax of containsHeader() of response object is as follows:
response.containsHeader(String name)
Return value of the above containsHeader method is a Boolean value true or false.
JAVA SERVER PAGES
143
setHeader(String name, String value):
This method of response object is used to create an HTTP Header with the name
and value given as string. If the header is already present, then the original value is
replaced by the current value given as parameter in this method.
General syntax of setHeader of response object is as follows:
response.setHeader(String name, String value)
For example:
response.setHeader(“Content_Type”,”text/html”);
sendRedirect(String):
This method of response object is used to send a redirect response to the client
temporarily by making use of redirect location URL given in parameter. Thus the
sendRedirect method of the response object enables one to forward a request to a
new target. But one must note that if the JSP executing has already sent page content
to the client, then the sendRedirect method of response object will not work and
will fail.
General syntax of sendRedirect of response object is as follows:
response.sendRedirect(String)
In the above the URL is given as string.
response.sendRedirect(“http://www.abc.net/error.html”) ;
<%@ page language=”java” %>
<%
response.sendRedirect(“http://yahoo.com”);
(“YouCanSpecifyYourPage.jsp”);
%>
<html>
<body>
This page redirects to specified URL location
</body>
</html>
sendError(intstatus_code):
This method of response object is used to send an error response to the client
containing the specified status code given in parameter.
General syntax of sendError of response object is as follows:
response.sendError(intstatus_code)
144 ZERO TO MASTERY IN WEB DEVELOPMENT
re.html
<html>
<body>
<form method = “post” action = “re.jsp”>
Enter your name<input type = “text” name = “name”><br>
Enter your password<input type=”password” name = “pwd”><br><br>
<input type = “submit” name = “submit” value = “submit” >
</form>
</body>
</html>
re.jsp
<%
String name = request.getParameter(“name”);
String password = request.getParameter(“pwd”);
if(name.equals(“xyz”) &&password.equals(“abcde”))
{
response.sendRedirect(“rrs.html”);
}
else
{
response.sendRedirect(“rrf.html”);
}
%>
Rrs.html
<html>
<head>
<title>Successful Login</title>
</head>
<body>
Hello xyz
</body>
</html>
JAVA SERVER PAGES
145
Rrf.html
<html>
<head>
<title>Failed Login</title>
</head>
<body>
LOGIN UNSUCCESSFULL.You are not xyz
</body>
</html>
Out.println(“welcome”);
Out.println(“IT”);
Output
Welcome
IT
clear ( )
This method of out object is used to clear the output buffer. This method does not
write any contents to the client. An exception is thrown by this method if the buffer
was flushed.
Syntax : out.clear() ;
clearBuffer ( )
This method of out object is used to clear the output buffer. This method does not
write any contents to the client. The only difference between the ‘clear’ method of
out object and ‘clearBuffer’ method is
• ‘clear’ method throws an exception when the buffer is flushed.
• ‘clearBuffer’ method does not throw an exception when the buffer is
flushed.
flush ( )
Two methods of out object, ‘clear’ and ‘clearBuffer’ are used to clear the output
buffer without writing any contents to the client. The ‘flush’ method of out object
is used to flush the buffer by writing the contents to the client.
isAutoFlush ( )
This method of ‘out’ object returns a ‘true’ value if the output buffer is automatically
flushed otherwise returns ‘false’.
Syntax: out.isAutoFlush();
getBufferSize( )
This method of ‘out’ object is used to return the size of the buffer. The returned
value of the size of the buffer is in bytes. If the output is not buffered, then the
“getBufferSize” method returns a 0 byte.
getRemaining( )
This method of out object is used to return the number of empty bytes in the buffer.
Syntax : out.getRemaining();
Example:
<%@ page buffer=”16kb” autoFlush=”true” %>
<table border= 2>
JAVA SERVER PAGES
147
<%
out.println(“<tr><td>Buffer Size : </td><td>” + out.getBufferSize()+”</td></tr>”);
out.println(“<tr><td>Is AutoFlush Enable</td><td> “ + out.isAutoFlush()+”</td></
tr>”);
out.println(“<tr><td>Remaining Buffer Size </td><td>” + out.getRemaining()+”</
td></tr>”);%>
</table>
then session_id value can be used to keep the track of different web
browsers.
(3) URL Rewriting: You can append some extra information on the end of
each URL that identifies the session, and the server can associate that
session identifier with data it has stored about that session.For example,
with http://abc.com/file.htm;sessionid=12345, the session identifier is
attached as sessionid=12345 which can be accessed at the web server to
identify the client.URL rewriting can be used where a cookie is disabled.
In this session ID information is embedded in the URL, which is recieved
by the application through Http GET requests when the client clicks on
the links embedded with a page.
Example:
encodeURL.jsp
<html>
<head>
<title> How to use encodeURL in jsp
</title>
</head>
<body>
<form method = “post” action = “EncodeURLProgram.jsp”>
Enter your name : <input type = “text” name = “name”><br>
Enter your password : <input type=”password” name = “pwd”><br>
<input type = “submit” name = “submit” value = “submit” >
</form>
</body>
</html>
EncodeURLProgram.jsp
<%@ page session =”true” %>
<%
String name = request.getParameter(“name”);
String password = request.getParameter(“pwd”);
if(name.equals(“Williams”) &&password.equals(“abcde”))
{
session.setAttribute(“username”,name);
String string =
JAVA SERVER PAGES
149
response. encode URL (“NextPageAfterFirst. jsp?name=+name+& password=+
password”);
%><p>Please click here to go forward : </p>
<a href =’<%= string %>’>WelcomeEncodeURL.jsp</a>
<%}
else
{
String string =
response.encodeURL(“encodeURL.jsp?name=+name+&password=+password”);%>
<p>You have entered a wrong value : Click here to go back : </p>
<a href =’<%= string %>’>encodeURL.jsp</a>
<% }
%>
NextPageAfterFirst.jsp
<html>
<head>
<title>Welcome in In the program of URL rewriting
</title>
</head>
<body>
Hello <%= session.getAttribute(“username”) %>
</body>
</html>
150 ZERO TO MASTERY IN WEB DEVELOPMENT
invalidate():
This method of session object is used to discard the session and releases any objects
stored as attributes. This method helps to reduce memory overhead and achieves
improvement in performance. It is always a good practice to explicitly remove or
invalidate sessions using session.invalidate() method.
General syntax of invalidate of session object is as follows:
session.invalidate()
getMaxInactiveInterval( ):
This method of session object is used to return the maximum amount of time the
JRun keeps the session open between client accesses. This returns the maximum
amount of time, in seconds, that a session can be inactive before it is deleted. The
returned value of time is in seconds. Thus, by using this method the user determines
how long it will take a session for it to time out. The default timeout period for
sessions defined by the servlet container is determined using the
getMaxInactiveInterval method. The returned value from this method is seconds
and thus, an integer.
General syntax of getMaxInactiveInterval of session object is as follows:
session.getMaxInactiveInterval()
The above method returns value of time in seconds.
For example:
out.println(“Maximum Inactive Interval of Session in Seconds is : “
+session.getMaxInactiveInterval());
The above statement would display
Maximum Inactive Interval of Session in Seconds is : 2000
The above denotes the time in seconds.
setMaxInactiveInterval():
This is another method that a developer can use to set the timeout explicitly for
each session. A user can use this method to set the default timeout.
General syntax of setMaxInactiveInterval of session object is as follows:
session.setMaxInactiveInterval(time)
In the above the time given in parameter is in seconds.For example:
session. setMaxInactiveInterval(600);
In the above statement, the inactivity period for the session would be set to
10minutes.The parameter 600 given in the method would be in seconds.
JAVA SERVER PAGES
153
removeAttribute:
This method of session object is used to remove the attribute and value from the
session.
General syntax of removeAttribute of session object is as follows:
session.removeAttribute(String)
For example:
session.removeAttribute(“ABC”);Example ABC given in parameter of
removeAttribute method is a string.
setAttribute(String, object):
This method of session object is used to set the object to the named attribute. This
method is used to write an attribute and value to the session. If the attribute does
not exist, then it is created and then the object is associated with this.
General syntax of setAttribute of session object is as follows:
session.setAttribute(String, object)
For example:
String a = request.getParameter(“test”);
session.setAttribute(“test”, abc);
In the above example, the first parameter passed to the method setAttribute test
denotes a string and the second parameter abc denotes the object. By passing these
to the setattribute method, the object abc is set with the string test.
<%@page import = “java.util.*” session=”true”%>
<html>
<%
Integer counter = (Integer)session.getAttribute(“counter”);
if (counter == null)
{counter = 1;}
else
{
counter = counter+1;
}
session.setAttribute(“counter”, counter);
%>
<br/>
Session ID:<%=session.getId()%>
154 ZERO TO MASTERY IN WEB DEVELOPMENT
<br/>
Session creation time:<%=new Date(session.getCreationTime())%>
<br/>
Last accessed time:<%=new Date(session.getLastAccessedTime())%>
<br/>
visited<%=counter%> times
<br/>
<% if(session.isNew())
{
out.println(“You have created a new session”);
}
else
{
out.println(“Session already exists”);
}
%>
</body>
</html>
JAVA SERVER PAGES
155
Example: Enumeration e;
e = application. getAttributeNames();
setAttribute(String objName, Object object)
This method stores the ‘object’ in the object name provided(String objname)
in the application.
Example : application.setAttribute(“Variable”, abc);
removeAttribute(String objName)
This method is used to remove the specified attribute (String
objName) from the application.
Example : application.setAttribute(“password”,password);
application.removeAttribute(“password”);
getMajorVersion()
This method is used to return the major version of the Servlet API for the
JSP Container.
Example: out.println(“Major Version:” + application. get Major Version
());
Output : Major Version:2
The above statement gives 2 as the major version of the Servlet API in use
for the Application object.
getMinorVersion()
This method is used to return the minor version of the Servlet API for the
JSP Container.
Example: out.println(“Minor Version:”+ application. getMinorVersion());
Output : Minor Version:1
The above statement gives 1 as the minor version of the Servlet API in use
for the Application object.
getServerInfo():
This method of Application object is used to return the name and version
number of the JRun servlet engine. Information about the JSP Container,
such as, the name and product version, are returned by the method
getServerInfo of Application object.
Example: out.print(“Server Information:”+ application. getServerInfo());
getInitParameter(String name):
This method of Application object is used to return the value of an
initialization parameter. If the parameter does not exist, then null value is
returned.
JAVA SERVER PAGES
157
Example : String xyz = application.getInitParameter(“eURL”);
In the above example, the value of initialization parameter “eURL” is
retrieved and stored in string “xyz”.
getInitParameterNames() :
This method of Application object is used to return the name of all
initialization parameter of the application. The returned value is an
enumeration.
Example: Enumeration e;
e=application. getInitParameterNames();
log(Message):
This method of Application object is used to write a text string to the JSP
Container’s default log file. General syntax of log method of Application
object is as follows :.
application.log(Message);
<%@ page import=”java.io.*,java.util.*” %>
<html>
<body>
<%
Integer hitsCount = (Integer)
application.getAttribute(“hitCounter”);
if( hitsCount ==null || hitsCount == 0 )
{out.println(“Welcome to my website!”);
hitsCount = 1;
}
else
{out.println(“Welcome back to my website!”);
hitsCount += 1;
}
application.setAttribute(“hitCounter”,hitsCount);%>
<center>
<p>Total number of visits: <%= hitsCount%></p>
</center>
<%
out.println(“Major version: “ +application.getMajorVersion());
158 ZERO TO MASTERY IN WEB DEVELOPMENT
Example:
e.jsp
160 ZERO TO MASTERY IN WEB DEVELOPMENT
<html>
<body>
<form action=”e1.jsp” method=”post”>
Enter your age ( in years ) :
<input type=”text” name=”age” />
<input type=”submit” value=”Submit” />
</form>
</body>
</html>
e1.jsp
<%@ page errorPage=”e2.jsp” %>
<html>
<body>
<%
int age;
age = Integer.parseInt(request.getParameter(“age”));
%>
<p>Your age is : <%= age %> years.</p>
<p><a href=”e.jsp”>Back</a>.</p>
</body>
</html>
e2.JSP
<%@ page isErrorPage=”true” %>
<html>
<body>
<%= exception %>
</body>
</html>
ACTIVE SERVER PAGES
161
CHAPTER 5
ACTIVE SERVER PAGES
When the browser requests the file, the webserver is smart enough to preprocess
the file before sending it to the client.
Client request
an ASP File
Client
Web
Server
Server returns the
HTML text to the client
Request
Client
Asp.dllpre- Scripting
processing engine
execution
HTML text
for display Translation to
HTML
Session Variables
Session variables are used to store information about ONE single user, and are
available to all pages in one application. Typically information stored in session
variables are name, id, and preferences.
Application Variables
Application variables are also available to all pages in one application. Application
variables are used to store information about ALL users in one specific application.
In ASP you declare a variable with the use of the Dim keyword, which means
for Dimension. Dimension in english refers to the amount of space something
takes up in the real world, but in computer terms it refers to space in computer
memory.
Example
<%
‘Single Variable Declarations
Dim Variable1
166 ZERO TO MASTERY IN WEB DEVELOPMENT
Dim Variable2
‘Multiple Variable Declarations
Dim Variable6, Variable7, Variable8
%>
<html>
<body>
<p>I write some text, but I will control when the
text will be sent to the browser.</p>
<p>The text is not sent yet. I hold it back!</p>
<p>OK, let it go!</p>
<%
Response.Flush
%>
</body>
</html>
Output:
I write some text, but I will control when the
text will be sent to the browser.
The text is not sent yet. I hold it back!
OK, let it go!
ASP Redirect Method
This method redirects the user to a different URL.
<%
Response.Redirect “http://www.abc.com”
%>
ASP Write Method
This method writes a specified string to the output.
<%
Response.Write “Hello World”
%>
Output:
Hello World
File2.asp
<%
Dim ByteCount
174 ZERO TO MASTERY IN WEB DEVELOPMENT
ByteCount = Request.TotalBytes
Response.Write(“ByteCount = “ &ByteCount& “ bytes”)
%>
Output
It depends on the data that is entered into the form.
For example, if Name=pawan, Age=30.
ByteCount = 39 bytes
Request.BinaryRead(count)
Count: Specifies how many bytes to read from the client
<%
dim p,q
p=Request.TotalBytes
q=Request.BinaryRead(p)
%>
%>
ASP Lock and Unlock Methods
Lock Method
This method prevents other users from modifying the variables in the Application
object (used to ensure that only one client at a time can modify the Application
variables).
Unlock Method
This method enables or allows other users to modify the variables stored in the
Application object (after it has been locked using the Lock method).
<%
Application.Lock
Application(“visits”)=Application(“visits”)+1
Application.Unlock
%>
This page has been visited
<%=Application(“visits”)%> times!!
SubApplication_OnStart
Application(“visitors”)=0
End Sub
ACTIVE SERVER PAGES
177
SubSession_OnStart
Application.Lock
Application(“visitors”)=Application(“visitors”)+1
Application.UnLock
End Sub
SubSession_OnEnd
Application.Lock
Application(“visitors”)=Application(“visitors”)-1
Application.UnLock
End Sub
</script>
To display the number of current visitors in an ASP file:
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application(“visitors”))%>
online now!!
</p>
</body>
</html>
The Global.asa file is an optional file that can contain declarations of objects,
variables, and methods that can be accessed by every page in an ASP application.
All valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be
used within Global.asa.This file must be stored in the root directory of the ASP
application, and each application can only have one Global.asa file.The Global.asa
file can contain only the following:
• Application events
• Session events
• <object> declarations
• TypeLibrary declarations
• the #include directive
178 ZERO TO MASTERY IN WEB DEVELOPMENT
File2.asp:
<%
Response.Write(Session(“name”))
%>
Output:
(none)
ASP Contents.Remove Method
This method deletes an item from the Contents collection.
Example 1
<%
Session(“t1”)=(“First test”)
Session(“t2”)=(“Second test”)
Session(“t3”)=(“Third test”)
Session.Contents.Remove(“t2”)
for each x in Session.Contents
Response.Write(x & “=” &Session.Contents(x) & “<br>”)
next
%>
Output:
t1=First test
t3=Third test
ASP Contents.RemoveAll Method
This method deletes all the items from the Contents collection.
<%
Session.Contents.RemoveAll()
%>
ASP Session_OnStart and Session_OnEnd Events
• Session_OnStart Event: The Session_OnStart event occurs when the
server creates a session.This event is placed in the Global.asa file.
• Session_OnEnd Event: The Session_OnEnd event occurs when the
session ends (abandoned or times out).This event is placed in the Global.asa
file.
5.3.5 ASP Server Object
This object is used to access properties and methods on the server.Its properties
and methods are explained below:
ACTIVE SERVER PAGES
181
Properties
Property Description
ScriptTimeout Specifies or returns the maximum number of seconds
a script can run before it is terminated
Methods
Method Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from another ASP file
GetLastError() Returns an ASPError object that describes the error
that occurred
Transfer Sends or transfers all the information created in one
ASP file to other ASP file
URLEncode Applies URL encoding rules to a specified string
%>
File2.asp:
<%
response.write(“I am in File 2!<br>”)
%>
Output:
I am in File 1!
I am in File 2!
I am back in File 1!
ASPCode
This property returns an error code generated by IIS.
ASPDescription
This property returns a detailed description of the error.
Category
This property returns the source of the error (Was the error generated by IIS? A
scripting language?Or a component?).
Column
This property returns the column position within the ASP file that generated the
error.
Description
This property returns a short description of the error.
File
This property returns the name of the ASP file that generated the error.
184 ZERO TO MASTERY IN WEB DEVELOPMENT
Line
This property returns the number of the line within the ASP file that generated the
error.
Number
This property returns the standard COM error code for the error.
Source
This property returns the actual source code of the line where the error occurred.
Syntax
ASPError.ASPCode()
ASPError.ASPDescription()
ASPError.Category()
ASPError.Column()
ASPError.Description()
ASPError.File()
ASPError.Line()
ASPError.Number()
ASPError.Source()
Example
<%
dim objErr
set objErr=Server.GetLastError()
response.write(“ASPCode=” &objErr.ASPCode)
response.write(“<br>”)
response.write(“ASPDescription=” &objErr.ASPDescription)
response.write(“<br>”)
response.write(“Category=” &objErr.Category)
response.write(“<br>”)
response.write(“Column=” &objErr.Column)
response.write(“<br>”)
response.write(“Description=” &objErr.Description)
response.write(“<br>”)
response.write(“File=” &objErr.File)
response.write(“<br>”)
ACTIVE SERVER PAGES
185
response.write(“Line=” &objErr.Line)
response.write(“<br>”)
response.write(“Number=” &objErr.Number)
response.write(“<br>”)
response.write(“Source=” &objErr.Source)
%>
Studentdetails.html
<html>
<body>
<form method= “get” action=”form1.asp”>
<b> STUDENT INFORMATION FORM </b>
Name: <input type=”text” name=”text1"><br>
Rollno: <input type=”text” name=”text2"><br>
Branch:<select name=”branch”>
<option value= “computer science”>CSE
<option value= “Information Technology”>IT
<option value= “Electronics”>ECE
<option value= “Mechanical”>ME
</select>
<input type=”submit” value=”Click to Submit”>
</form>
</body>
</html>
STUDENT INFORMATION FORM
Name:
Rollno:
Branch:
CSE
Click to Submit
The form1.asp will be called as soon as the user clicks on the button and
contains the scripts that will process the input that user entered in the form
Form1.asp
<% @language=”VBscript” %>
<%option explicit%>
<html>
<body>
<%
Dim name,rollno,branch
Name=request.querystring(“text1”)
Rollno=request.querystring(“text2”)
ACTIVE SERVER PAGES
187
Branch=request.querystring(“branch”)
Response.write(“your name is” &name & “<br>”)
Response.write(“Rollno is” &rollno& “<br>”)
Response.write(“branch is” &branch & “<br>”)
%>
</body>
</html>
Your name is Pridhi
Rollno is 05/IT/39
Branch is Information Technology
5.5 Troubleshooting
Troubleshooting is a form of problem solving most often applied to repair of failed
products or processes. It is a logical, systematic search for the source of a problem
so that it can be solved, and so the product or process can be made operational
again. Troubleshooting is needed to develop and maintain complex systems where
the symptoms of a problem can have many possible causes. Troubleshooting is
used in many fields such as engineering, system administration, electronics,
automotive repair, and diagnostic medicine. Troubleshooting requires identification
of the malfunction(s) or symptoms within a system. Then, experience is commonly
used to generate possible causes of the symptoms. Determining which cause is
most likely is often a process of elimination - eliminating potential causes of a
problem. Finally, troubleshooting requires confirmation that the solution restores
the product or process to its working state.
In general, troubleshooting is the identification of, or diagnosis of “trouble”
in a [system] caused by a failure of some kind. The problem is initially described
as symptoms of malfunction, and troubleshooting is the process of determining
the causes of these symptoms.
A system can be described in terms of its expected, desired or intended
behaviour (usually, for artificial systems, its purpose). Events or inputs to the system
are expected to generate specific results or outputs. (For example selecting the
“print” option from various computer applications is intended to result in a hardcopy
emerging from some specific device). Any unexpected or undesirable behavior is
a symptom. Troubleshooting is the process of isolating the specific cause or causes
of the symptom. Frequently the symptom is a failure of the product or process to
produce any results. (Nothing was printed, for example).
188 ZERO TO MASTERY IN WEB DEVELOPMENT
CHAPTER 6
COOKIES
//File: readcookie.jsp
<html>
<head>
<title>Reading a Cookie</title>
</head>
<body>
<h1>Reading a Cookie</h1>
<%
Cookie[] cookies = request.getCookies();
After clicking the link “Read the Cookie”, you will be displayed with the
cookie value.
Assume that your server has sent all the cookies above to a user.
Now we wish to read all the cookies sent to a user. The example below shows
how to read (note that the code below checks if a cookie has Keys with the HasKeys
property):
<html>
<body>
<%
dim a,b
for each ainRequest.Cookies
response.write(“<p>”)
if Request.Cookies(a).HasKeys then
for each b in Request.Cookies(a)
response.write(a & “:” & b & “=” &Request.Cookies(a)(b))
response.write(“<br>”)
next
else
Response.Write(a & “=” &Request.Cookies(a) & “<br>”)
end if
response.write “</p>”
next
%>
</body>
</html>
Output:
firstname=ABC
user:firstname=Pridhi
user:lastname=Arora
user:country=India
user:age=25
if numvisits=”” then
response.cookies(“NumVisits”)=1
response.write(“Welcome! This is the first time you are visiting this Web
page.”)
else
response.cookies(“NumVisits”)=numvisits+1
response.write(“You have visited this “)
response.write(“Web page “ &numvisits)
ifnumvisits=1 then
response.write” time before!”
else
response.write” times before!”
end if
end if
%>
198 ZERO TO MASTERY IN WEB DEVELOPMENT
After Refreshing:
EXTENSIBLE MARKUP LANGUAGE
199
CHAPTER 7
EXTENSIBLE MARKUP LANGUAGE
How do we
communicate
with each other?
Translator would
translate for us
We will now
communicate in
common
language
I know only I know only
English Language Hindi Language
and common and common
language language
How do we
Application communicate Application
X with each Y
other?
I am a J2EE I am a Mainframe
application using DB2 application using oracle
database on Linus OS database on MVS
Operating System
Application X Application Y
XML
Import java.io.*;
Classstudent
RollNo Name {
Int RollNo.;
1 Pawan String Name;
2 Pridhi ...
3 Ritu ...
4 Tanya }
5 Vijay
STEP2: Same Application Program writes this data to create an XML file
out of it.
The note above is quite self-descriptive. It has the information of sender and
the receiver; it also has a heading and a message body. Don’t expect that XML
files will be displayed as HTML pages. 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. This XML
document does not DO anything. It is just the information that is wrapped in the
tags. Someone must write a piece of software to send, receive or display it.
XML Attributes
XML elements can have attributes, just like HTML. Attributes provide additional
information about an XML element.
XML Elements vs. Attributes
Take a look at these examples:
<person sex=”female”>
<firstname>ABC</firstname>
<lastname>XYZ</lastname>
</person>
<person>
<sex>female</sex>
<firstname>ABC</firstname>
<lastname>XYZ</lastname>
</person>
In the first example sex is an attribute. In the last, sex is an element. Both
examples provide the same information. There are no defined rules about when to
use as attributes or when to use as an elements.
<snack>
<chips>
<price>20</price>
<amount>60gms</amount>
</chips>
</snack>
</inventory>
The root element in the example is <inventory>. All other elements in the
document are contained within <inventory>.
The <chips> element has 2 children: <amount> and <price>.
Inventory
Drink Snack
Chips
Real Juice Pepsi
Price Amount
Price Amount Price Amount
In XML, it is illegal not to have the closing tag. All elements must have a
closing tag:
<p>This is a paragraph.</p>
<br />
• XML Tags are Case Sensitive
The tag <note> is different from the tag <Note>.
Opening and closing tags must be written with the same case:
<Message>This is incorrect</message>
<message>This is correct</message>
• XML Elements Must be Properly Nested
In HTML, Improperly nested elements works:
<b><i>This text is bold and italic</b></i>
In XML, all elements must be properly nested within each other:
<b><i>This text is bold and italic</i></b>
• XML Documents Must Have a Root Element
XML documents must contain one element that is the parent of all other elements.
This element is called the root element.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
• XML Attribute Values must be quoted
XML elements can have attributes in name/value pairs just like as in HTML. In
XML, the attribute values must always be quoted.
Study the two XML documents below. The first one is incorrect, the second is
correct:
<note date=17/11/2013>
<to>Preet</to>
<from>Pridhi</from>
</note>
<note date=”17/11/2013">
<to>Preet</to>
EXTENSIBLE MARKUP LANGUAGE
209
<from>Pridhi</from>
</note>
The error in the first document is that the date attribute in the note element is
not quoted.
• Comments in XML
The syntax for writing comments in XML is similar to that of HTML.
<!— This is a comment —>
• White-space is preserved in XML
HTML truncates multiple white-space characters to one single white-space:
HTML: Hello Pawan
Output: Hello Pawan
With XML, the white-space in a document is not truncated.
Program A
XML Program B
Document
Program C
Validate the contents of the
XML document and then
uses this document
Program A
XML Program B
Document
Validate Program C
No need to validate
DTD this document
<note>
<to>Preet</to>
<from>Pridhi</from>
<heading>Reminder</heading>
<body>Meeting on Monday at 3pm</body>
</note>
The DTD above is interpreted like this:
• !DOCTYPE note defines that the root element of this document is note
• !ELEMENT note defines that the note element contains four elements:
“to,from,heading,body”
• !ELEMENT to defines the to element to be of type “#PCDATA”
• !ELEMENT from defines the from element to be of type “#PCDATA”
• !ELEMENT heading defines the heading element to be of type "#PCDATA”
• !ELEMENT body defines the body element to be of type “#PCDATA”
*PCDATA
PCDATA means parsed character data. PCDATA is text that will be parsed by a
parser. Tags inside the text will be treated as markup and entities will be expanded.
*CDATA
CDATA means character data. CDATA is text that will NOT be parsed by a parser.
Tags inside the text will NOT be treated as markup and entities will not be expanded.
A parser is a software tool that checks to be sure a document follows a particular
syntax. XML parsers come in two varieties:
• A non-validating parser checks a document to be sure XML syntax rules
are followed and builds a document tree from the element tags.
• A validating parser checks the syntax, builds the tree, and compares the
use of element tags to be sure they conform with the rules specified in the
document’s associated DTD.
Parsers can be either external programs or part of the editing tool or browsing
tool.
External DTD Declaration
If the DTD is declared in an external file, it should be wrapped in a DOCTYPE
definition with the following syntax:
<! DOCTYPE root-element SYSTEM “filename”>
DTDs are stored as ascii text files with the extenstion .dtd. Each file begins
with a DOCTYPE definition and includes a series of element definitions, attribute
lists, entity defintions and notation definitions.
EXTENSIBLE MARKUP LANGUAGE
213
<?xml version=”1.0"?>
<!DOCTYPE note SYSTEM “note.dtd”>
<note>
<to>Preet</to>
<from>Pridhi</from>
<heading>Reminder</heading>
<body>Meeting on Monday at 3pm</body>
</note>
And this is the file “note.dtd” which contains the DTD:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
particular element of your document), you identify the namespaces you’ll be using
and where the tag information is located. Then, when you use the tag to identify an
element in your document, you precede it with the appropriate namespace name.
Declaring Namespaces
At the beginning of your document, you’ll want to identify the namespaces you are
using in your document. This process is called declaring the namespace. In this
example, you are creating a namespace called “sales.” The URI for sales is the
mythical fishworld.org/schema:
<document xmlns:SALES=’http://fishworld.org/schema’>
Using Namespaces
When you use the tag to create the element that is defined in one of the namespaces,
the namespace is the first part of the tag, like this:
<SALES: SOURCE>Fish-o-Rama Wholesalers and Suppliers to the Trade</
SOURCE>
When you use your own tag you just use the tag name, like this:
<SOURCE>Mexico, Central America</SOURCE>
The following fragment:
xmlns=”http://www.xyz.com”
specifies the default namespace declaration. This declaration tells the schema
validator that all the elements used in this XML document are declared in the
“http://www.xyz.com” namespace.
Once you have the XML Schema Instance namespace available:
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
you can use the schemaLocation attribute. This attribute has two values,
separated by a space. The first value is the namespace to use. The second value is
the location of the XML schema to use for that namespace:
xsi:schemaLocation=”http://www.xyz.com note.xsd”
An XML Schema (note.xsd)
The following example is an XML Schema file called “note.xsd” that defines
the elements of the XML document above (“note.xml”):
<?xml version=”1.0"?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema”
targetNamespace=”http://www.xyz.com”
xmlns=”http://www.w3schools.com”>
EXTENSIBLE MARKUP LANGUAGE
217
<xs:element name=”note”>
<xs:complexType>
<xs:sequence>
<xs:element name=”to” type=”xs:string”/>
<xs:element name=”from” type=”xs:string”/>
<xs:element name=”heading” type=”xs:string”/>
<xs:element name=”body” type=”xs:string”/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The note element is of complex type as it contains other elements. The other
elements (to, from, heading, body) are simple types because they do not contain
other elements. A simple element is an XML element that can contain only text. It
cannot contain any other elements or attributes. If an element has attributes, it is
considered to be of a complex type. A complex element is an XML element that
contains other elements and/or attributes.
The following fragment:
xmlns:xs=”http://www.w3.org/2001/XMLSchema”
indicates that the elements and data types used in the schema come from the
“http://www.w3.org/2001/XMLSchema” namespace. It also specifies that the
elements and data types that come from the “http://www.w3.org/2001/
XMLSchema” namespace should be prefixed with xs:
This fragment:
targetNamespace=”http://www.xyz.com”
indicates that the elements defined by this schema (note, to, from, heading,
body.) come from the “http://www.XYZ.com” namespace.
This fragment:
xmlns=”http://www.xyz.com”
indicates that the default namespace is “http://www.xyz.com”.
A Cascading Style Sheet is a file that contains instructions for formatting the
elements in an XML document.
Creating and linking a CSS to your XML document is one way to tell browser
how to display each of document’s elements. An XML document with an attached
CSS can be open directly in Internet Explorers. You don’t need to use an HTML
page to access and display the data.
There are two basic steps for using a css to display an XML document:
• Create the CSS file.
• Link the CSS sheet to XML document.
With CSS (Cascading Style Sheets) you can add display information to an
XML document.
Example 1:
Save the code with a.css
tutorials
{
margin:10px;
background-color:pink;
font-family:verdana,helvetica,sans-serif;
}
name
{
font-weight:bold;
}
url
{
display:block;
color:blue;
font-size:small;
font-style:italic;
}
We will use the above code for a xml file named b.xml
EXTENSIBLE MARKUP LANGUAGE
219
Save the code with b.xml
<?xml version=”1.0"?>
<?xml-stylesheet type=”text/css” href=”a.css”?>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.abc.com</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.xyz.com</url>
</tutorial>
</tutorials>
Output:
220 ZERO TO MASTERY IN WEB DEVELOPMENT
Example2:
Save the code with x.css
CATALOG
{
background-color: pink;
width: 100%;
}
CD
{
display: block;
margin-bottom: 30pt;
margin-left: 0;
}
TITLE
{
color: purple;
font-size: 20pt;
}
EXTENSIBLE MARKUP LANGUAGE
221
ARTIST
{
color: green;
font-size: 20pt;
}
COUNTRY,PRICE,YEAR,COMPANY
{
Display: block;
color: #000000;
margin-left: 20pt;
}
<ARTIST>XYZ</ARTIST>
<COUNTRY>India</COUNTRY>
<COMPANY>ABC</COMPANY>
<PRICE>980</PRICE>
<YEAR>1982</YEAR>
</CD>
</CATALOG>
Output:
EXTENSIBLE MARKUP LANGUAGE
223
Output without using the css file:
HTML
XSL XSL Document Web
Transformation Transformation Browser
spec.
<xsl:template match=”/”>
<html>
<body>
<h2>My Book Collection</h2>
<table border=”1">
<tr bgcolor=”#9acd32">
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Year</th>
</tr>
<xsl:for-each select=”catalog/book”>
<tr>
<td><xsl:value-of select=”title”/></td>
<td><xsl:value-of select=”author”/></td>
<td><xsl:value-of select=”price”/></td>
<td><xsl:value-of select=”year”/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Explanation of above example:
<xsl:for-each select=”catalog/book”>
<xsl:sort select=”author”/>
<tr>
<td><xsl:value-of select=”title”/></td>
<td><xsl:value-of select=”author”/></td>
</tr>
</xsl:for-each>
Example 2
Step 1 (XML file): Create an XML file with the following content and save it
with “p.xml”
<?xml version=”1.0" encoding=”UTF-8" standalone=”yes”?>
<?xml-stylesheet type=”text/xsl” href=”q.xsl”?>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.abc.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.xyz.com/html/tutorial</url>
</tutorial>
</tutorials>
Step 2 (XSL file): Create a file with the following content and save it as
“q.xsl” into the same directory as the XML file.
<?xml version=”1.0"?>
<xsl:stylesheet version=”1.0" xmlns:xsl=”http://www.w3.org/1999/XSL/
Transform”>
<xsl:template match=”/”>
<html>
<head>
<title>XML XSL Example</title>
<style type=”text/css”>
body
EXTENSIBLE MARKUP LANGUAGE
229
{
margin:10px;
background-color:#ccff00;
font-family:verdana,helvetica,sans-serif;
}
.tutorial-name
{
display:block;
font-weight:bold;
}
.tutorial-url
{
display:block;
color:#636363;
font-size:small;
font-style:italic;
}
</style>
</head>
<body>
<h2>Easy to learn Tutorials</h2>
<p>Hey, check out these tutorials!</p>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match=”tutorial”>
<span class=”tutorial-name”><xsl:value-of select=”name”/></span>
<span class=”tutorial-url”><xsl:value-of select=”url”/></span>
</xsl:template>
</xsl:stylesheet>
230 ZERO TO MASTERY IN WEB DEVELOPMENT
Output:
inventory element
//@lang Selects all attributes that are named lang
XPath Operators
An XPath expression returns either a node-set, a string, a Boolean, or a number.
Below is a list of the operators that can be used in XPath expressions:
Operator Description Example Return value
+ Addition 6+6 12
- Subtraction 6–2 4
* Multiplication 6*3 18
Div Division 8 div 4 2
= Equal price=5.80 true if price is 5.80false if
price is 5.90
!= Not equal price!=5.80 true if price is 5.90false if
price is 5.80
< Less than price<5.80 true if price is 5.00false if
price is 5.80
<= Less than or equal to price<=5.80 true if price is 5.00false if
price is 5.90
> Greater than price>5.80 true if price is 5.90false if
price is 5.80
>= (Greater than or equal to Price) = 5.80 true if price is 5.90false if
price is 5.70
Or Or price=5.80 or price true if price is
=5.70 5.80false if price is 5.50
And and price>5.00 and true if price is 5.80false if
price<5.90 price is 5.50
Mod Modulus (division 5 mod 2 1
remainder)
<fo:root xmlns:fo=”http://www.w3.org/1999/XSL/Format”>
<fo:layout-master-set>
EXTENSIBLE MARKUP LANGUAGE
233
<fo:simple-page-master master-name=”A4">
<!— Page template goes here —>
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference=”A4">
<!— Page content goes here —>
</fo:page-sequence>
</fo:root>
XSL-FO Areas
XSL-FO uses rectangular boxes (areas) to display output. All output (text, pictures,
etc.) will be formatted into these boxes and then will be displayed. Following areas
are
• Pages
• Regions
• Block areas
• Line areas
• Inline areas
XSL-FO Pages
XSL-FO output is formatted into pages. Printed output will generally go into many
separate pages. Browser output will often go into one long page. XSL-FO Pages
contain many Regions.
XSL-FO Regions
Each XSL-FO Page contains a number of Regions:
• region-body (body of the page)
• region-before (header of the page)
• region-after (footer of the page)
• region-start (left sidebar)
• region-end (right sidebar)
XSL-FO Regions contain many Block areas.
<fo:root xmlns:fo=”http://www.w3.org/1999/XSL/Format”>
<fo:layout-master-set>
<fo:simple-page-master master-name=”A4">
<fo:region-body />
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference=”A4">
<fo:flow flow-name=”xsl-region-body”>
<fo:block>Hello Friends</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
The output from this code would be something like this:
Hello Friends
The file format could not be read or exchanged with other programs, it was useful
only within the application that created it.
Because SGML is a nonproprietary international standard so it helps you to
create documents that are independent of any specific hardware or software. The
document structure is described in a file called the DTD (Document Type
Definition). The DTD defines the relationships between a document’s elements
creating a consistent, logical structure for each document.
SGML is used by defense contractors and electronic publishing industry for
more than a decade and is very useful for managing large-scale, long-term
information management needs. Because SGML is very large, powerful, and
complex so it is difficult to learn and understand and is not well suited for the Web
environment.
In Conclusion
XML will never completely replace SGML because SGML is still considered better
for long-time storage of complex documents. However, XML has already replaced
HTML as the recommended markup language for the Web with the creation of
XHTML 1.0.
XHTML has not made the HTML that currently exists on the Web obsolete;
HTML 4.01 is the last version of HTML. XHTML (an XML application) is the
foundation for a universally accessible, device independent Web.
INDEX
S
Scriplet tag, 120 T
Search interface, 20 Tabindex attribute, 70
Searching, 15, 21 Tag specific, events, 53
Searching, 22 Taglib directive, 125
Searching systems, 18 Target attribute, 69
Selectively indexing, 26 Task-oriented organization scheme, 10
Semantic network, 74 Text level elements, 56
Semantic web, 73 Title attribute, 69
sendError(intstatus_code), 143 Title, 47
sendRedirect(String), 143 Topical organization scheme, 10
Server side image maps, 71 Troubleshooting, 187
Session attribute, 125 Types of metaphor, 29
Session object, 147 Types of navigation systems, 15
Session variables, 165 Typography, 39
session. setMaxInactiveInterval(600), 152
setAttribute(String, object), 153 U
setAttribute(String,Object), 138 Unlock method, 176
setContentType(), 142 URL rewriting, 148
setHeader(String name, String value), 143
setMaxInactiveInterval(), 152
V
Shockwave (Flash) Format, 91 Valid XML, 209
Simple / Basic search interface, 21 Visual metaphors, 29
Site index, 16
Sitemap, 16
SND format, 89
W
WAVE format, 89
Spacing, 39
Web publishing, 40
Static positioning, 112
Website design, 36
Steps of web design, 36
244 ZERO TO MASTERY IN WEB DEVELOPMENT