Sunteți pe pagina 1din 0

JITENDER SINGH LAMBA

LECT IT GITM
132

Unit -2
Lecture no
Security issues, CGI, PERL, HTML, VRML, JAVA, VB script and other internet development tools,
internet networking TCP/IP protocols . ) Network Security and Management.


CGI (Common gateway interface)
Common
Assures you that CGI can be used by many languages and interact with many different types of
systems. It doesn't tie you down to one way of doing what you want.
Gateway
Suggests that CGI's strength lies not in what it does by itself, but in the potential access it offers to
other systems such as databases and graphic generators.
Interface
Means that CGI provides a well-defined way to call up its features--in other words, that you can write
programs that use it.

It is used to make web page dynamic.
CGI is the part of the Web server that can communicate with other programs running on the
server. With CGI, the Web server can call up a program, while passing user-specific data to
the program (such as what host the user is connecting from, or input the user has supplied
using HTML form syntax). The program then processes that data and the server passes the
program's response back to the Web browser.

Figure 1.1: Simple diagram of CGI
Internal Workings of CGI
Most servers expect CGI programs and scripts to reside in a special directory, usually called cgi-bin,
and/or to have a certain file extension. When a user opens a URL associated with a CGI program, the
client sends a request to the server asking for the file. When a server recognizes that the address being
requested is a CGI program, the server does not return the file contents. Instead, the server tries to
execute the program. Here is what a sample client request might look like:
GET /cgi-bin/welcome.pl HTTP/1.0
Accept: www/source
Accept: text/html
Accept: image/gif
User-Agent: Lynx/2.4 libwww/2.14
From: shishir@bu.edu
This GET request identifies the file to retrieve as /cgi-bin/welcome.pl. Since the server is configured to
recognize all files inf the cgi-bin directory tree as CGI programs, it understands that it should execute
the program instead of relaying it directly to the browser.
The string HTTP/1.0 identifies the communication protocol to use.
JITENDER SINGH LAMBA
LECT IT GITM
133
The client request also passes the data formats it can accept (www/source, text/html, and image/gif),
identifies itself as a Lynx client, and sends user information. All this information is made available to
the CGI program, along with additional information from the server.
Once the CGI program starts running, it can either create and output a new document, or provide the
URL to an existing one.
A CGI program can choose to send the newly created data directly to the client or to send it indirectly
through the server. If the output consists of a complete HTTP header, the data is sent directly to the
client without server modification. Or, as is usually the case, the output is sent to the server as a data
stream. The server is then responsible for adding the complete header information and using the HTTP
protocol to transfer the data to the client.
Here is the sample output of a program generating an HTML virtual document, with the complete
HTTP header:
HTTP/1.0 200 OK
Date: Thursday, 22-February-96 08:28:00 GMT
Server: NCSA/1.4.2
MIME-version: 1.0
Content-type: text/html
Content-length: 2000
<HTML>
<HEAD><TITLE>Welcome to Shishir's WWW Server!</TITLE></HEAD>
<BODY>
<H1>Welcome!</H1>
.
.
</BODY>
</HTML>
The header contains the communication protocol, the date and time of the response, the server name
and version, and the revision of the MIME protocol. Most importantly, it also consists of the MIME
content type and the number of characters (equivalent to the number of bytes) of the enclosed data, as
well as the data itself. Now, the output with the partial HTTP header:
Content-type: text/html
<HTML>
<HEAD><TITLE>Welcome to Shishir's WWW Server!</TITLE></HEAD>
<BODY>
<H1>Welcome!</H1>
.
.
</BODY>
</HTML>
Configuring the Server
Before you can run CGI programs on your server, certain parameters in the server configuration files
must be modified. If you are using either the NCSA or CERN HTTP server, you need to first set the
ServerRoot directive in the httpd.conf file to point to the directory where the server software is
located:
ServerRoot /usr/local/etc/httpd

Running CGI Scripts:
On the NCSA server, the ScriptAlias directive in the server resource map file (srm.conf) indicates the
directory where the CGI scripts are placed.
ScriptAlias /cgi-bin/ /usr/local/etc/httpd/cgi-bin/
For example, if a user accesses the URL:
http://your_host.com/cgi-bin/welcome
The local program:
/usr/local/etc/httpd/cgi-bin/welcome
will be executed by the server. You can have multiple directories to hold CGI scripts:
ScriptAlias /cgi-bin/ /usr/local/etc/httpd/cgi-bin/
JITENDER SINGH LAMBA
LECT IT GITM
134
ScriptAlias /my-cgi-bin/ /usr/local/etc/httpd/my-cgi-bin/
You might wonder why all CGI programs must be placed in distinct directories. The most important
reason for this is system security. By having all the programs in one place, a server administrator can
control and monitor all the programs being run on the system. However, there are directives that allow
programs to be run outside of these directories, based on the file extension. The following directives,
when placed in the srm.conf configuration file, allow the server to execute files containing .pl, .sh, or
.cgi extensions.
AddType application/x-httpd-cgi .pl .sh .cgi
Advantages
It make website dynamic.
Disadvantages:
For each client requesting a CGI webpage a new process has to be created by operating system running
on the server so its takes lots of servers resources and processing times especially when multiple
clients requests for some CGI webpage. So this is large overhead.
CGI Applications
CGI turns the Web from a simple collection of static hypermedia documents into a whole new
interactive medium, in which users can ask questions and run applications.
1. Forms
One of the most prominent uses of CGI is in processing forms. Forms are a subset of HTML that
allows the user to supply information. When the form is completed by the user, the Submit Order!
Button is used to send the information to the server, which executes the program associated with the
particular form to "decode" the data.
Generally, forms are used for two main purposes. At their simplest, forms can be used to collect
information from the user. But they can also be used in a more complex manner to provide back-and-
forth interaction. For example, the user can be presented with a form listing the various documents
available on the server, as well as an option to search for particular information within these
documents. A CGI program can process this information and return document(s) that match the user's
selection criteria.
2. Gateways
Web gateways are programs or scripts used to access information that is not directly readable by the
client. For example, say you have an Oracle database that contains baseball statistics for all the players
on your company team and you would like to provide this information on the Web. How would you do
it? You certainly cannot
point your client to the database file (i.e., open the URL associated with the file) and expect to see any
meaningful data. CGI provides a solution to the problem in the form of a gateway. You can use a
language such as oraperl or a DBI extension to Perl to
form SQL queries to read the information contained within the database. Once you have the
information, you can format and send it to the client. In this case, the CGI program serves as a gateway
to the Oracle database.
3. Virtual Documents
Virtual, or dynamic, document creation is at the heart of CGI. Virtual documents are created on the fly
in response to a user's information request. You can create virtual HTML, plain text, image, and even
audio documents. A simple example of a virtual document could be something as trivial as this:
Welcome to Shishir's WWW Server!
You are visiting from diamond.com. The load average on this machine is 1.25.
Happy navigating!
In this example, there are two pieces of dynamic information: the alphanumeric address (IP name) of
the remote user and the load average on the serving machine.

Programming in CGI
1. AppleScript (Macintosh Only)
AppleScript lacks inherent pattern-matching operators, certain extensions have been written to make it
easy to handle various types of data. AppleScript also has the power to interface with other Macintosh
applications through AppleEvents. For example, a Mac CGI programmer can write a program
that presents a form to the user, decode the contents of the form, and query and search a Microsoft
FoxPro database directly through AppleScript.
JITENDER SINGH LAMBA
LECT IT GITM
135
2. C/C++ (UNIX, Windows, Macintosh)
C and C++ are very popular with programmers, and some use them to do CGI programming. These
languages are not recommended for the novice programmer; C and C++ impose strict rules for variable
and memory declarations, and type checking. In addition, these languages lack database extensions and
inherent pattern-matching abilities, although modules and functions can be written to achieve these
functions.
However, C and C++ have a major advantage in that you can compile your CGI application to create a
binary executable, which takes up fewer system resources than using interpreters (like Perl or Tcl) to
run CGI scripts.
3. C Shell (UNIX Only)
C Shell lacks pattern-matching operators, and so other UNIX utilities, such as sed or awk, must be used
whenever you want to manipulate string information. However, there is a software tool, called uncgi
and written in C, that decodes form data and stores the information into shell environment variables,
which can be accessed rather easily. Obviously, communicating with a database directly is impossible,
unless it is done through a foreign application. Finally, the C Shell has some serious bugs and
limitations that make using it a dangerous proposition for the beginner.
4. Perl (UNIX, Windows, Macintosh)
Perl is by far the most widely used language for CGI programming! It contains many powerful
features, and is very easy for the novice programmer to learn. The advantages of Perl include:
It is highly portable and readily available.
It contains extremely powerful string manipulation operators, as well as functions to deal with
binary data.
It contains very simple and concise constructs.
It makes calling shell commands very easy, and provides some useful equivalents of certain
UNIX system functions.
There are numerous extensions built on top of Perl for specialized functions; for example,
there is oraperl(or the DBI Extensions), which contains functions for interfacing with the
Oracle database.
5. Tcl (UNIX Only)
Tcl is gaining popularity as a CGI programming language. Tcl consists of a shell, tclsh, which can be
used to execute your scripts. Like Perl, tclsh also contains simple constructs, but is a bit more difficult
to learn and use for the novice programmer. Like Perl, Tcl contains extensions to databases and
graphic libraries. It also supports regular expressions, but is quite inefficient in handling these
expressions at compile time, especially when compared to Perl.
6. Visual Basic (Windows Only)
With Visual Basic, you can communicate with other Windows applications such as databases and
spreadsheets. This makes Visual Basic a very powerful tool for developing CGI applications on a PC,
and it is very easy to learn. However, Visual Basic lacks powerful string manipulation operators.

Input to the Common Gateway Interface
When a CGI program is called, the information that is made available to it can be roughly broken into
three groups:
Information about the client, server, and user
Form data that the user supplied
Additional pathname information
Most information about the client, server, or user is placed in CGI environment variables. Form data is
either incorporated into an environment variable, or is included in the "body" of the request. And extra
path information is placed in environment variables.
1.Using Environment Variables
Much of the most crucial information needed by CGI applications is made available via UNIX
environment variables. Programs can access this information as they would any environment variable
(e.g., via the %ENV associative array in Perl).
This section concentrates on showing examples of some of the more typical uses of environment
variables in CGI programs. First, however, Table 2.1 shows a full list of environment variables
available for CGI.
JITENDER SINGH LAMBA
LECT IT GITM
136





Let's start with a simple program that displays various information about the server, such as the CGI
and HTTP revisions used and the name of the server software.

Let's go through this program step by step. The first line is very important. It instructs the server to use
the Perl interpreter located in the /usr/local/bin directory to execute the CGI program. Without this
line, the server won't know how to run the program, and will display an error stating that it cannot
execute the program.
Once the CGI script is running, the first thing it needs to generate is a valid HTTP header, ending with
a blank line. The header generally contains a content type, also known as a MIME type. In this case,
the content type of the data that follows is text/html.
After the MIME content type is output, we can go ahead and display output in HTML. We send the
information directly to standard output, which is read and processed by the server, and then sent to the
JITENDER SINGH LAMBA
LECT IT GITM
137
client for display. Five environment variables are output, consisting of the server name (the IP name or
address of the machine where the server is running), the port the server is running on, the server
software, and the HTTP and CGI revisions. In Perl, you can access the environment variables through
the %ENV associative array, keyed by name.
A typical output of this program might look like this:

2.Accessing Form Input
Forms provide a way to get input from users and supply it to a CGI program, The Web browser allows
the user to select or type in information, and then sends it to the server when the Submit button is
pressed.
2.1Query Strings
One way to send form data to a CGI program is by appending the form information to the URL, after a
question mark. You may have seen URLs like the following:
http://some.machine/cgi-bin/name.pl?fortune
Up to the question mark (?), the URL should look familiar. It is merely a CGI script being called, by
the name name.pl.
The information after the "?" character is known as a query string. When the server is passed a URL
with a query string, it calls the CGI program identified in the first part of the URL (before the "?") and
then stores the part after the "?" in the environment variable QUERY_STRING. The following is a
CGI program called name.pl that uses query information to execute one of three possible UNIX
commands.

You can execute this script as either:
http://some.machine/cgi-bin/name.pl?fortune
http://some.machine/cgi-bin/name.pl?finger
or
http://some.machine/cgi-bin/name.pl
and you will get different output. The CGI program executes the appropriate system command (using
backtics) and the results are sent to standard output. In Perl, you can use backtics to capture the output
from a system command.
Other eg.
JITENDER SINGH LAMBA
LECT IT GITM
138

This form consists of one text field titled "Command:" and two buttons. The Submit Form! button is
used to send the information in the form to the CGI program specified by the ACTION attribute. The
Clear Form button clears the information in the field.
The METHOD=GET attribute to the <FORM> tag in part determines how the data is passed to the
server. Now, assuming that the user enters "fortune" into the text field, when the Submit Form! button
is pressed the browser sends the following request to the server:
GET /cgi-bin/unix.pl?command=fortune HTTP/1.0
The server executes the script called unix.pl in the cgi-bin directory, and places the string
"command=fortune" into the QUERY_STRING environment variable. Think of this as assigning the
variable "command" (specified by the NAME attribute to the <INPUT> tag) with the string supplied
by the user, "fortune".
command=fortune
Let's go through the simple unix.pl CGI program that handles this form:

After printing the content type (text/plain in this case, since the UNIX programs are unlikely to
produce HTML output) and getting the query string from the %ENV array, we use the split function to
separate the query string on the "=" character into two parts, with the first part before the equal sign in
$field_name, and the second part in $command. In this case, $field_name will contain "command" and
$command will contain "fortune." Now, we're ready to execute the UNIX command:

Since we used the GET method, all the form data is included in the URL. So we can directly access
this program without the form, by using the following URL:
http://some.machine/cgi-bin/unix.pl?command=fortune
It will work exactly as if you had filled out the form and submitted it.

2.2 The GET and POST Methods
JITENDER SINGH LAMBA
LECT IT GITM
139
In the previous example, we used the GET method to process the form. However, there is another
method we can use, called POST. Using the POST method, the server sends the data as an input stream
to the program. That is, if in the previous example the <FORM> tag had read:
<FORM ACTION="unix.pl" METHOD="POST">
the following request would be sent to the server:

The version of unix.pl that handles the form with POST data follows. First, since the server passes
information to this program as an input stream, it sets the environment variable CONTENT_LENGTH
to the size of the data in number of bytes (or characters). We can use this to read exactly that much
data from standard input.

Second, we read the number of bytes, specified by $size_of_form_information, from standard input
into the variable $form_info.
read (STDIN, $form_info, $size_of_form_information);
Now we can split the $form_info variable into a $field_name and $command, as we did in the GET
version of this example. As with the GET version, $field_name will contain "command," and
$command will contain "fortune" (or whatever the user typed in the text field). The rest of the example
remains unchanged:

Since it's the form that determines whether the GET or POST method is used, the CGI programmer
can't control which method the program will be called by. So scripts are often written to support both
methods.
3 Extra Path Information
Besides passing query information to a CGI script, you can also pass additional data, known as extra
path information, as part of the URL. The extra path information depends on the server knowing where
the name of the program ends, and understanding that anything following the program name is "extra."
Here is how you would call a script with extra path information:
http://some.machine/cgi-bin/display.pl/cgi/cgi_doc.txt
Since the server knows that display.pl is the name of the program, the string "/cgi/cgi_doc.txt" is stored
in the environment variable PATH_INFO. Meanwhile, the variable PATH_TRANSLATED is also set,
which maps the information stored in PATH_INFO to the document root directory (e.g.,
/usr/local/etc/httpd/ public/cgi/cgi-doc.txt).
Here is a CGI script--display.pl--that can be used to display text files located in the document root
hierarchy:
JITENDER SINGH LAMBA
LECT IT GITM
140

In this example, we perform a simple security check. We make sure that the user didn't pass path
information containing "..". This is so that the user cannot access files located outside of the document
root directory.
Output from the Common Gateway Interface
The most basic output for a CGI program is a simple document in either plain text or HTML, which
the browser displays as it would any document on the Web. However, there are other things you can
do, such as:
Return graphics and other binary data
Tell the browser whether to cache the virtual document
Send special HTTP status codes to the browser
Tell the server to send an existing document
Each of these techniques involves knowing a little bit about returning additional headers from the CGI
program.
CGI and Response Headers
CGI programs that create simple virtual documents, like this one:

Up to this point, we have taken the line that outputs "Content-type" for granted. But this is only one
type of header that CGI programs can use. "Content-type" is an HTTP header that contains a MIME
content type describing the format of the data that follows. Other headers can describe:
The size of the data
Another document that the server should return (that is, instead of returning a virtual
document created by the script itself)
HTTP status codes

JITENDER SINGH LAMBA
LECT IT GITM
141


How to Sending Data to the Server
GET vs. POST
There are two methods for sending form data: GET and POST. The main difference between these
methods is the way in which the form data is passed to the CGI program.
GET
If the GET method is used, the query string is simply appended to the URL of the program when the
client issues the request to the server. This query string can then be accessed by using the environment
variable QUERY_STRING. Here is a sample GET request by the client, which corresponds to the first
form example:

The GET method has both advantages and disadvantages. The main advantage is that you can access
the CGI program with a query without using a form. In other words, you can create " canned queries."
Basically, you are passing parameters to the program. For example, if you want to send the previous
query to the program directly, you can do this:

POST
Now, here is a sample POST request:

The main advantage to the POST method is that query length can be unlimited-- you don't have to
worry about the client or server truncating data. To get data sent by the POST method, the CGI
program reads from standard input. However, you cannot create "canned queries."
Understanding the Decoding Process
In order to access the information contained within the form, a decoding protocol must be applied to
the data. First, the program must determine how the data was passed by the client. This can be done by
JITENDER SINGH LAMBA
LECT IT GITM
142
examining the value in the environment variable REQUEST_METHOD. If the value indicates a GET
request, either the query string or the extra path information must be obtained from the environment
variables. On the other hand, if it is a POST request, the number of bytes specified by the
CONTENT_LENGTH environment variable must be read from standard input. The algorithm for
decoding form data follows:
1. Determine request protocol (either GET or POST) by checking the REQUEST_METHOD
environment variable.
2. If the protocol is GET, read the query string from QUERY_STRING and/or the extra path
information from PATH_INFO.
3. If the protocol is POST, determine the size of the request using CONTENT_LENGTH and read that
amount of data from the standard input.
4. Split the query string on the "&" character, which separates key-value pairs (the format is key=value
key=value...).
5. Decode the hexadecimal and "+" characters in each key-value pair.
Create a key-value table with the key as the index. (If this sounds complicated, don't worry, just use a
high-level language like Perl. The language makes it pretty easy.)

Server Side Includes
Server Side Includes are directives which you can place into your HTML documents to execute other
programs or output such data as environment variables and file statistics. Unfortunately, not all servers
support these directives. However, there is a CGI program called fakessi.pl that you can use to emulate
Server Side Includes if your server does not support them.
While Server Side Includes technically are not really CGI, they can become an important tool for
incorporating CGI-like information, as well as output from CGI programs, into documents on the Web.
How does Server Side Includes work?
When the client requests a document from the SSI-enabled server, the server parses the specified
document and returns the evaluated document (see Figure 5.1). The server does not automatically parse
all files looking for SSI directives, but only ones that are configured as such.


SSI sounds like a great feature, but it does have its disadvantages. First, it can be quite costly for a
server to continually parse documents before sending them to the client. And second, enabling SSI
creates a security risk. Novice users could possibly embed directives to execute system commands that
output confidential information. Despite these shortcomings, SSI can be a very powerful tool if used
cautiously.

JITENDER SINGH LAMBA
LECT IT GITM
143


Configuring SSI for the Server
You can use a Perl program called fakessi.pl to emulate SSI behavior.
For example, on the server, all you need to do is:
1. Install fakessi.pl into the cgi-bin directory.
2. Add the following directive to httpd.conf:
Exec /*.shtml /usr/local/etc/httpd/cgi bin/fakessi.pl
(assuming that /usr/local/etc/httpd/cgi-bin is the directory that fakessi.pl was installed into). This tells
the server to execute fakessi.pl whenever a client requests a file ending in .shtml.
You can get fakessi.pl from http://sw.cse.bris.ac.uk/WebTools/fakessi.html.

Debugging and Testing CGI Applications
The hardest aspect of developing CGI applications on the Web is the testing/debugging phase. The
main reason for the difficulty is that applications are being run across a network, with client and server
interaction. When there are errors in CGI programs, it is difficult to figure out where they lie.
1. Common Errors
CGI Script in Unrecognized Directory
Most servers require that CGI scripts reside in a special directory (/cgi-bin), or have certain file
extensions. If you try to execute a script that does not follow the rules for a particular server, the
server will simply retrieve and display the document, instead of executing it.
Missing Interpreter Line
If your CGI application is a script of some sort (a C Shell, Perl, etc.), it must contain a line that
begins with #! (a "sharp-bang," or "shebang"), or else the server will not know what interpreter to
call to execute the script.
File Permission Problems
JITENDER SINGH LAMBA
LECT IT GITM
144
The CGI script must be executable by the server. Most servers are set up to run with the user
identification (UID) of "nobody," which means that your scripts have to be world executable. The
reason for this is that "nobody" has minimal privileges.
If you want the server (running as "nobody") to be able to execute this script, you have to issue the
following command:




Malformed Header from Script
All CGI applications must output a valid HTTP header, followed by a blank line, before any other
data. In other words, two new line characters have to be output after the header. Here is how the
output should look:

The headers must be output before any other data, or the server will generate a server error with a
status of 500. So make it a habit to output this data as early in the script as possible. To make it
easier for yourself, you can use a subroutine in a program
2. Programming/System Errors
Programming errors can cause unexpected results. There is one extremely important point that you
should be aware of:
Always check the return value of all the system commands, including eval, open, and system.
Opening, Reading, and Writing Files
Since the server is running as a user that has minimal privileges (usually "nobody"), you must be
careful when reading from or writing to files. Here is an example:

Now, what if the file that you are trying to read is not accessible? The file handle FILE will not be
created, but the while loop tries to iterate through that file handle. Fortunately, Perl does not get upset,
but you will not have any data. So, it is always better to check the status of the open command, like
this:

This will ensure that the subroutine call_some_subroutine gets called if the script cannot open the file.
Pipes and the open Command
We used pipes to perform data redirection in numerous examples in this book. Unlike files, there is no
easy way to check to see if the contents of the pipe have been successfully executed. Let's take a look
at a simple example:

JITENDER SINGH LAMBA
LECT IT GITM
145
If the cat command cannot be found by the shell, you might expect that an error status will be returned
by the open command, and thus the call_some_subroutine function will be called. However, this is not
the case. An error status will be returned only if a pipe cannot be created (which is almost never the
case). Due to the way the shell operates, the status of the command is available only after the file
handle is closed
Here is an example:

Once the file handle is closed, Perl saves the return status in the variable $?. This is the method that
you should use for all system commands.
3. Environment Variables
Some CGI programmers want to avoid using a file, and try to store the information in an environment
variable. So they write code that resembles the following:

To their surprise, however, the counter value is always the same (1, in this case). The point behind this
is that you cannot save any environment variables directly from Perl, although it is possible to do so by
invoking the shell.

PERL:-
Perl stands for Practical Extraction and Report Language or Pathologically Eclectic Rubbish
Lister. It is a powerful glue language useful for tying together the loose ends of computing life.
1. Uses of Perl
1. Tool for general system administration
2. Processing textual or numerical data
3. Database interconnectivity
4. Common Gateway Interface (CGI/Web) programming
5. Driving other programs! (FTP, Mail, WWW, OLE)
Perl is a language designed to cater to the three chief virtues of a programmer.
Laziness - develop reusable and general solutions to problems
Impatience - develop programs that anticipate your needs and solve problems for you.
Hubris - write programs that you want other people to see (and be able to maintain)
2. Perl Basics
2.1 Language properties
Perl is an interpreted language program code is interpreted at run time. Perl is unique among
interpreted languages, though. Code is compiled by the interpreter before it is actually executed.
Many Perl idioms read like English
Free format language white space between tokens is optional
Comments are single-line, beginning with #
Statements end with a semicolon (;)
Only subroutines and functions need to be explicitly declared
Blocks of statements are enclosed in curly braces {}
JITENDER SINGH LAMBA
LECT IT GITM
146
A script has no main()
2.2 Invocation
On platforms such as UNIX, the first line of a Perl program should begin with
#!/usr/bin/perl
and the file should have executable permissions. Then typing the name of the script will cause it to be
executed.
You can also run the interpreter by itself from the command line. This is often useful to execute short
snippets of code:
perl e code
Alternatively, you can run the interpreter in debugging mode to obtain a shell-like environment for
testing code scraps:
perl de 1
2.3 Data Types & Variables


JITENDER SINGH LAMBA
LECT IT GITM
147

Scalars
Scalars are simple variables that are either numbers or strings of characters. Scalar variable names
begin with a dollar sign followed by a letter, then possibly more letters, digits, or underscores. Variable
names are case-sensitive.
Numbers
Numbers are represented internally as either signed integers or double precision floating point
numbers. Floating point literals are the same used in C. Integer literals include decimal (255), octal
(0377), and hexadecimal (0xff) values.
Strings
Strings are simply sequences of characters. String literals are delimited by quotes:

Basic I/O
The easiest means to get operator input to your program is using the diamond operator:
$input = <>;
The input from the diamond operator includes a newline (\n). To get rid of this pesky character, use
either chop() or chomp()
To do the converse, simply use Perls print function:
print $output.\n;
2.4 Basic Operators

JITENDER SINGH LAMBA
LECT IT GITM
148



Logical


2.5 Conditional Structures (If/else if/else)
JITENDER SINGH LAMBA
LECT IT GITM
149
The basic construction to execute blocks of statements is the if statement. The if statement permits
execution of the associated statement block if the test expression evaluates as true.


Loops
Perl provides several different means of repetitively executing blocks of statements.
While
The basic while loop tests an expression before executing a statement block
while (expression) {
statements;
}
Until
The until loop tests an expression at the end of a statement block; statements will be executed until the
expression evaluates as true.
until (expression) {
statements;
}
Do while
A statement block is executed at least once, and then repeatedly until the test expression is false.
do {
statements;
} while (expression);
Do until
A statement block is executed at least once, and then repeatedly until the test expression is true.
do {
statements;
} until (expression);
For
The for loop has three semicolon-separated expressions within its parentheses. These expressions
function respectively for the initialization, the condition, and re-initialization expressions of the loop.
The for loop
for (initial_exp; test_exp; reinit_exp) {
statements;
}
Foreach
The foreach statement is much like the for statement except it loops over the elements of a list:
foreach $i (@some_list) {
JITENDER SINGH LAMBA
LECT IT GITM
150
statements;
}
If the scalar loop variable is omitted, $_ is used.
2.6 Labels
Any statement block can be given a label. Labels are identifiers that follow variable naming rules.
They are placed immediately before a statement block and end with a colon:
SOMELABEL: {
statements;
}
You can short-circuit loop execution with the directives next and last:
next skips the remaining statements in the loop and proceeds to the next iteration (if any)
last immediately exits the loop in question
redo jumps to the beginning of the block (restarting current iteration)
2.7 Indexed Arrays (Lists)
A list is an ordered set of scalar data. List names follow the same basic rules as for scalars.
List literals
List literals consist of comma-separated values enclosed in parentheses:
(1,2,3)
A range can be represented using a list constructor function (such as ..):
(1..9) = (1,2,3,4,5,6,7,8,9)
($a..$b) = ($a, $a+1, , $b-1,$b)
In the case of string values, it can be convenient to use the quote-word syntax
@a = (fred,barney,betty,wilma);
@a = qw( fred barney betty wilma )
Accessing List Elements
List elements are subscripted by sequential integers, beginning with 0
$foo[5] is the sixth element of @foo
The special variable $#foo provides the index value of the last element of @foo.
List operators and functions
Many list-processing functions operate on the paradigm in which the list is a stack. The highest
subscript end of the list is the top, and the lowest is the bottom.

2.8 Pattern Matching
Regular Expressions
Regular expressions are patterns to be matched against a string. The two basic operations performed
using patterns are matching and substitution:
Matching /pattern/
Substitution s/pattern/newstring/
The simplest kind of regular expression is a literal string. More complicated expressions include
metacharacters to represent other characters or combinations of them.
JITENDER SINGH LAMBA
LECT IT GITM
151



2.9 Subroutines and Functions
Subroutines are defined in Perl as:
sub subname {
statement_1;
statement_2;
}
Subroutine definitions are global; there are no local subroutines.
Invoking subroutines
The ampersand (&) is the identifier used to call subroutines. They may also be called by appended
parentheses to the subroutine name:
name();
&name;
You may use the explicit return statement to return a value and leave the subroutine at any point.
sub myfunc {
statement_1;
if (condition) return $val;
statement_2;
return $val;
}
JITENDER SINGH LAMBA
LECT IT GITM
152
2.10 Filehandles
A filehandle is the name for the connection between your Perl program and the operating system.
Filehandles follow the same naming conventions as labels, and occupy their own namespace.
Every Perl program has three filehandles that are automatically opened for it: STDIN, STDOUT, and
STDERR:
STDIN Standard input (keyboard or file)
STDOUT Standard output (print and write send output here)
STDERR Standard error (channel for diagnostic output)

Using filehandles
After a file has been opened for reading you can read from it using the diamond operator just as you
have already done for STDIN:
$_ = <FILE>; or
while (<FILE>) {
statements;
}
To print to your open output file, use the filehandle as the first argument to the print statement (N.B. no
commas between the filehandle and the string to print).
print FILE Look Ma! No hands!\n;
To change the default output filehandle from STDOUT to another one, use select:
select FILE;

2.11 Manipulating files & directories
The action of opening a file for writing creates it. Perl also provides functions to manipulate files
without having to ask the operating system to do it.
unlink(filename)
Delete an existing file. Unlink can take a list of files, or wildcard as an argument as well:
unlink(<*.bak>)
rename(oldname, newname)
This function renames a file. It is possible to move files into other directories by specifying a path as
part of the new name.
Directories also have some special function associated with them
mkdir(dirname, mode)
Create a new directory. The mode specifies the permissions (set this to 0777 to be safe).
rmdir(dirname)
Removes (empty) directories
chdir(dirname)
Change current working directory to dirname
File and directory attributes can be modified as well:
chmod(permission, list of files)
Change the permissions of files or directories:
666 = read and write
444 = read only
777 = read, write, and executable
utime(atime, mtime, list of files)
Modify timestamps on files or directories. atime is the time of the most recent access, and mtime
is the time the file/directory was last modified.
1)Writing a program to display welcome message
JITENDER SINGH LAMBA
LECT IT GITM
153
#! C:\perl\bin\perl
print welcome to Perl \n;
print This is my first program;

Save with first.pl

Running perl Program in Windows
C:\perl first.pl
#! It is shebang statement, used for to invoke perl interpreter path.

Running perl Program in UNIX/Linux
$ which perl # it displays location of perl
usr/bin/perl
perl v # version of perl
$ man perl # help document
$ vi first.pl
#! usr/bin/perl
print welcome to Perl \n;
print This is my first program;

$ perl first.pl
or
$ chmod 755 first.pl
$./first.pl

Ex2: write a program accepts 2 integer values and find sum?
Print Enter a number 1: ;
Chomp ($a= <STDIN>);
Print Enter a number 2: ;
Chomp ($b= <STDIN>);
$c= $a + $b
print \n $a + $b= $c;
3) Write a program accepting a number and check given number is 3 digit number or not?

Print Enter a number: ;
Chomp ($n= <STDIN>);
If ($n >=100 && $a <=999)
{
print $n is a 3 digit number;
JITENDER SINGH LAMBA
LECT IT GITM
154
}
else
{
print $n is not a 3 digit number;

4) Write a program accepting user name and password and check for given user name &
password are valid or not?

Print \n Enter user name;
Chomp ($uname= <STDIN>);

Print \n Enter password;
Chomp ($pwd= <STDIN>);

If ($uname eq tecno && $pwd eq soft
{
print \n welcome to tecnosoft;
}
else
{
print \n invalid user name or password;
}

5) Write a program to print numbers 1 to 10?
$num=1;
while ($num ,=10)
{
print $num \n;
$num++
}
(or)

for ($num=1; $num <= 10; $num++)
{
print $num \n;
}

(or)
foreach $num(1..10)
{
print $num \n;
}
(or)
foreach (1..10)
{
print $_ \n;
}

(or)
foreach (1..10)
{
print ;
JITENDER SINGH LAMBA
LECT IT GITM
155
}

Note: $_ is Perl special and default variable. If we dont declare any variable for reading data then Perl
will store the value in default variable.



HTML script:
Hyper Text Markup Language
Used to Describe the Web Pages
Specifically created to make World Wide Web pages
Created by Tim Berners-Lee from SGML
Creating an HTML file
Notepad or WordPad
Starting tag: <html>
Indicates that you are starting an HTML document
Ending tag: </html>
Indicates that you are ending an HTML document
The Extension Could be .htm or .html

Tags in html

Basic Text Tags
Function Start Tag Attributes End Tag
Line Break <br> clear="left/right/all" </br> or <br />
Paragraph <p> align="center/right" </p>
Bold <b> none </b>
Italic <i> none </i>
JITENDER SINGH LAMBA
LECT IT GITM
156
Typewriter Text <tt> none </tt>
Headline <h1-6> align="center/right" </h1-6>
Font <font> face="name, name"
size="+/-value/fixed size"
color="color value"
</font>
Horizontal Rule <hr> size="XX"
width="XX/XX%"
noshade
</hr> or <hr />
List Tags
Function Start Tag Attributes End Tag
Unordered List <ul> type="disc/circle/square" </ul>
Ordered List <ol> type="I/A/1/a/i"
start="value to start counting at"
</ol>
List Item <li> type=all ul and ol options </li>
Definition List <dl> none </dl>
Definition List
Item
<dt> none </dt>
Definition List
Definition
<dd> none </dd>
Image Tags
Function Start Tag Attributes End Tag
Insert Image <img> src="filename"
align="left/right"
width="XXX"
height="XXX"
alt="text that desribes
image"
</img>
Table Tags
Function Start Tag Attributes End Tag
Table <table> border="X"
width="XX/X%"
cellspacing="XX"
cellpadding="XX"
bgcolor="color value"
background="filename"
</table>
Table Row <tr> align="left/center/right"
valign="top/middle/bottom"
bgcolor="color value"
</tr>
Table Data <td> align="left/center/right"
valign="top/middle/bottom"
width=X
nowrap
colspan="X"
rowspan="X"
bgcolor="color value"
</td>
Table Header <th> align="left/center/right"
valign="top/middle/bottom"
width=X
nowrap
colspan="X"
rowspan="X"
</th>
JITENDER SINGH LAMBA
LECT IT GITM
157
bgcolor="color value"
Caption <caption> align="left/center/right"
valign="top/middle/bottom"
</caption>
Frame Tags
Function Start Tag Attributes End Tag
Set Frames <frameset> cols="XX/XX%/*"
rows="XX/XX%/*"
</frameset>
Frame Definition <frame> src="filename"
name="framename"
noresize
scroll=auto/yes/no
marginwidth="XX"
marginheight="XX"
</frame>
Base <base> target="framename"/
"_self"/
"_top"/
"_parent"
(Note the underscores)
</base>
No Frames <noframes> Between start and end
tags, place the content
that appears when a non-
frames browser loads this
page.
</noframes>

E.g. 1. First webpage
<html>
<head>
<title>First webpage
</title>
</head>
<body>
Hello World !!
</body>
</html>


2. Marquee or Animated Script
Code
<Marquee behavior=scroll/alternative Direction=left>
Good Afternoon
</Marquee>
JITENDER SINGH LAMBA
LECT IT GITM
158

3. Heading in HTML Document
<html>
<head>
<title>
</title>
</head>
<body>
<H1>This is Heading 1</H1>
<H2>This is Heading 2</H2>
<H3>This is Heading 3</H3>
<H4>This is Heading 4</H4>
<H5>This is Heading 5</H5>
<H6>This is Heading 6</H6>
</body>
</html>

4.Unordered list
<pre>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
<li>Sugar</li>
<li>Etc</li>
</ul>
</pre>

JITENDER SINGH LAMBA
LECT IT GITM
159


5. Ordered list
<ol>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
<li>Sugar</li>
<li>Etc</li>
</ol>


6. Add Image on background
<html>
<head>
<title>
</title>
</head>
<body background=r.jpg">
</body>
</html>
7. Insert image in Web Page
<html>
<head>
<title>
</title>
</head>
<body>
<img src=r.jpg height="100" width="200">
</body>
</html>
8. Add Multimedia
Included in body Part
JITENDER SINGH LAMBA
LECT IT GITM
160
<BGSOUND src="filename" loop="3" autoplay="true">
<EMBED SRC="filename" height="500" width="500">
9. Create Table
<table border=1" cellpading=10 cellspacing=1>
<tr>
<th>Heading</th>
<th>Other </th>
</tr>
<tr>
<td>Row 1, cell1</td>
<td>Row 1, cell2</td>
</tr>
<tr>
<td>Row 2, cell1</td>
<td>Row2, cell2 </td>
<td></td>
</tr>
</table>
Heading Other
Row1, cell1 Row1, cell2
Row2, cell1 Row2, cell2


10. Colspan Attribute
<TABLE BORDER=2 CELLPADDING=4> <TR> <TH COLSPAN=2>Production</TH> </TR>
<TR> <TD>Raha Mutisya</TD> <TD>1493</TD> </TR> <TR> <TD>Shalom Buraka</TD>
<TD>3829</TD> </TR> <TR> <TD>Brandy Davis</TD> <TD>0283</TD> </TR> <TR> <TH
COLSPAN=2>Sales</TH> </TR> <TR> <TD>Claire Horne</TD> <TD>4827</TD> </TR>
<TR> <TD>Bruce Eckel</TD> <TD>7246</TD> </TR> <TR> <TD>Danny Zeman</TD>
<TD>5689</TD> </TR> </TABLE>

11.Rowspan Attribute
JITENDER SINGH LAMBA
LECT IT GITM
161
<TABLE BORDER=2 CELLPADDING=4> <TR> <TH ROWSPAN=3
BGCOLOR="#99CCFF">Production</TH> <TD>Raha Mutisya</TD> <TD>1493</TD>
</TR> <TR> <TD>Shalom Buraka</TD> <TD>3829</TD> </TR> <TR> <TD>Brandy
Davis</TD> <TD>0283</TD> </TR> <TR> <TH ROWSPAN=3
BGCOLOR="#99CCFF">Sales</TH> <TD>Claire Horne</TD> <TD>4827</TD> </TR> <TR>
<TD>Bruce Eckel</TD> <TD>7246</TD> </TR> <TR> <TD>Danny Zeman</TD>
<TD>5689</TD> </TR> </TABLE

12. Form
A form is an area that can contain form elements.
<form></form>
Commonly used form elements includes:
Text fields
Radio buttons
Checkboxes
Submit buttons
a) Text Input Fields
<form>
First name: <input type="text" name="firstname">
<br>
Last name: <input type="text" name="lastname"> </form>


b) Submission Button
<form name="input" action="html_form_action.asp" method="get"> Username: <input
type="text" name="user">
<br>
<input type="submit" value="Submit">
</form>

JITENDER SINGH LAMBA
LECT IT GITM
162


c) Checkboxes
<form>
<input type="checkbox" name="bike value=bike> I have a bike
<br>
<input type="checkbox" name="car value=car> I have a car </form>

o I have a bike
o I have a car


d) Radio Buttons
<form>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
</form>


e) Text Box
<form>
<p>Please provide your suggestion in the text box below:</p>
<textarea row=10 cols=30>
</textarea>
</form>
JITENDER SINGH LAMBA
LECT IT GITM
163


f) Pull-down Menu
<select name=Apples">
<option selected> Old
Apple
<option> New Apple
< option > Local brand
</select>



g) Frameset
<Frameset> Tag is used to divide window into frames
Add code Before <body> Tag
<frameset cols="50%,50%">
<frame src="a.html">
<frame src="b.html"
</frameset>

JITENDER SINGH LAMBA
LECT IT GITM
164


h) Nested frames
<HTML>
<HEAD>
<TITLE>
</TITLE> </HEAD>
<FRAMESET ROWS="15%,*"> <FRAME SRC=a.html> <FRAMESET COLS="20%,*">
<FRAME SRC=b.html" >
<FRAME SRC=c.html" > </FRAMESET> </FRAMESET>
</HTML>


i) Nested Frames
<frameset cols="33%,33%,*">
<frame src=0.html" >
</frameset>
<frameset
rows="33%,33%,33%">
<frame src="1.html" >
<frame src="2.html">
<frame src="3.html">
</frameset">
<frame src=4.html" >
</frameset">
JITENDER SINGH LAMBA
LECT IT GITM
165
0 1
2

3
4

j) Hyperlink
<a href="http://www.google.com">Google</a>

HTML Organization:
Spacing
Spacing organizes your work!
Spacing makes your files easy to read!
Spacing makes no functional difference to your web browser
Comments
Comments are notes in your HTML file
Comments make no functional difference to your web browser
<!-- begins a comment, and --> ends it




Network Management

What Is Network Management?
Network management means different things to different people. In some cases, it involves a solitary
network consultant monitoring network activity with an outdated protocol analyzer. In other cases,
network management involves a distributed database, auto polling of network devices, and high-end
workstations generating real-time graphical views of network topology changes and traffic. In general,
network management is a service that employs a variety of tools, applications, and devices to assist
human network managers in monitoring and maintaining networks.

Network Management Architecture

Most network management architectures use the same basic structure and set of relationships. End
stations (managed devices), such as computer systems and other network devices, run software that
enables them to send alerts when they recognize problems (for example, when one or more user-
determined thresholds are exceeded). Upon receiving these alerts, management entities are
programmed to react by executing one, several, or a group of actions, including operator notification,
event logging, system shutdown, and automatic attempts at system repair.
Management entities also can poll end stations to check the values of certain variables. Polling can be
automatic or user-initiated, but agents in the managed devices respond to all polls. Agents are software
modules that first compile information about the managed devices in which they reside, then store this
information in a management database, and finally provide it (proactively or reactively) to
management entities within network management systems (NMSs) via a network management
protocol.Well-known network management protocols include the Simple Network Management
Protocol (SNMP) and
Common Management Information Protocol (CMIP). Management proxies are entities that provide
management information on behalf of other entities. Figure 6-1 depicts a typical network management
architecture.

JITENDER SINGH LAMBA
LECT IT GITM
166


ISO Network Management Model
The ISO has contributed a great deal to network standardization. Its network management model is the
primary means for understanding the major functions of network management systems. This model
consists of five conceptual areas, as discussed in the next sections.

a) Performance Management
The goal of performance management is to measure and make available various aspects of network
performance so that inter network performance can be maintained at an acceptable level. Examples of
performance variables that might be provided include network throughput, user response times, and
line utilization.
Performance management involves three main steps. First, performance data is gathered on variables
of interest to network administrators. Second, the data is analyzed to determine normal (baseline)
levels.
Finally, appropriate performance thresholds are determined for each important variable so that
exceeding these thresholds indicates a network problem worthy of attention.
Management entities continually monitor performance variables. When a performance threshold is
exceeded, an alert is generated and sent to the network management system.
Each of the steps just described is part of the process to set up a reactive system. When performance
becomes unacceptable because of an exceeded user-defined threshold, the system reacts by sending a
message. Performance management also permits proactive methods: For example, network simulation
can be used to project how network growth will affect performance metrics. Such simulation can alert
administrators to impending problems so that counteractive measures can be taken.

b) Configuration Management
The goal of configuration management is to monitor network and system configuration information so
that the effects on network operation of various versions of hardware and software elements can be
tracked and managed.
Each network device has a variety of version information associated with it. An engineering
workstation, for example, may be configured as follows:
Operating system, Version 3.2
Ethernet interface, Version 5.4
TCP/IP software, Version 2.0
NetWare software, Version 4.1
NFS software, Version 5.1
Serial communications controller, Version 1.1
X.25 software, Version 1.0
SNMP software, Version 3.1
JITENDER SINGH LAMBA
LECT IT GITM
167
Configuration management subsystems store this information in a database for easy access. When a
problem occurs, this database can be searched for clues that may help solve the problem.

c) Accounting Management
The goal of accounting management is to measure network utilization parameters so that individual or
group uses on the network can be regulated appropriately. Such regulation minimizes network
problems (because network resources can be apportioned based on resource capacities) and maximizes
the fairness of network access across all users.

As with performance management, the first step toward appropriate accounting management is to
measure utilization of all important network resources. Analysis of the results provides insight into
current usage patterns, and usage quotas can be set at this point. Some correction, of course, will be
required to reach optimal access practices. From this point, ongoing measurement of resource use can
yield billing information as well as information used to assess continued fair and optimal resource
utilization.

d) Fault Management
The goal of fault management is to detect, log, notify users of, and (to the extent possible)
automatically fix network problems to keep the network running effectively. Because faults can cause
downtime or unacceptable network degradation, fault management is perhaps the most widely
implemented of the ISO network management elements.
Fault management involves first determining symptoms and isolating the problem. Then the problem is
fixed and the solution is tested on all-important subsystems. Finally, the detection and resolution of the
problem is recorded.

e) Security Management
The goal of security management is to control access to network resources according to local
guidelines so that the network cannot be sabotaged (intentionally or unintentionally) and sensitive
information cannot be accessed by those without appropriate authorization. A security management
subsystem, for example, can monitor users logging on to a network resource and can refuse access to
those who enter inappropriate access codes.
Security management subsystems work by partitioning network resources into authorized and
unauthorized areas. For some users, access to any network resource is inappropriate, mostly because
such users are usually company outsiders. For other (internal) network users, access to information
originating from a particular department is inappropriate. Access to Human Resource files, for
example, is inappropriate for most users outside the Human Resources department.
Security management subsystems perform several functions. They identify sensitive network resources
(including systems, files, and other entities) and determine mappings between sensitive network
resources and user sets. They also monitor access points to sensitive network resources and log
inappropriate access to sensitive network resources.

Security issues & Network Security:-
Security is about protecting things of value to an organization, in relation to the possible risks. This
includes material and intellectual assets; it includes the very assumptions that are the foundation of an
organization or humancomputer system. Anything that can cause a failure of those assumptions can
result in loss, and must therefore be considered a threat.
A system can be compromised by:
Physical threats: weather, natural disaster, bombs, power failures etc.
Human threats: cracking, stealing, trickery, bribery, spying, sabotage, accidents.
Software threats: viruses, Trojan horses, logic bombs, denial of service.
Protecting against these issues requires both proactive (preventative) measures and damage control
after breaches. Our task is roughly as follows:
Identify what we are trying to protect.
Evaluate the main sources of risk and where trust is placed.
Work out possible or cost-effective counter-measures to attacks.
JITENDER SINGH LAMBA
LECT IT GITM
168
The OSI security architecture:
The OSI security architecture focuses on security attacks, mechanisms, and services. These can be
defined briefly as follows:
Security attack: Any action that compromises the security of information owned by an
organization.
Security mechanism: A process (or a device incorporating such a process) that is designed to
detect, prevent, or recover from a security attack.
Security service: A processing or communication service that enhances the
security of the data processing systems and the information transfers of an
organization. The services are intended to counter security attacks, and they
make use of one or more security mechanisms to provide the service

Security Attacks:-
a) Passive Attacks
Passive attacks are in the nature of eavesdropping on, or monitoring of, transmissions. The goal of the
opponent is to obtain information that is being transmitted. Two types of passive attacks are release of
message contents and traffic analysis.
The release of message contents is easily understood (Figure 1.3a). A telephone conversation, an
electronic mail message, and a transferred file may contain sensitive or confidential information. We
would like to prevent an opponent from learning the contents of these transmissions.
Figure 1.3. Passive Attacks


A second type of passive attack, traffic analysis, is subtler (Figure 1.3b). Suppose that we had a way
of masking the contents of messages or other information traffic so that opponents, even if they
captured the message, could not extract the information from the message. The common technique for
masking contents is encryption. If we had encryption protection in place, an opponent might still be
able to observe the pattern of these messages. The opponent could determine the location and identity
of communicating hosts and could observe the frequency and length of messages being exchanged.
This information might be useful in guessing the nature of the communication that was taking place.
JITENDER SINGH LAMBA
LECT IT GITM
169
Passive attacks are very difficult to detect because they do not involve any alteration of the data.
Typically, the message traffic is not sent and received in an apparently normal fashion and the sender
nor receiver is aware that a third party has read the messages or observed the traffic pattern. However,
it is feasible to prevent the success of these attacks, usually by means of encryption. Thus, the
emphasis in dealing with passive attacks is on prevention rather than detection.
b) Active Attacks
Active attacks involve some modification of the data stream or the creation of a false stream and can
be subdivided into four categories: masquerade, replay, modification of messages, and denial of
service.
A masquerade takes place when one entity pretends to be a different entity (Figure 1.4a). A
masquerade attack usually includes one of the other forms of active attack. For example, authentication
sequences can be captured and replayed after a valid authentication sequence has taken place, thus
enabling an authorized entity with few privileges to obtain extra privileges by impersonating an entity
that has those privileges.

Replay attacks
An attack in which a service already authorized and completed is forged by another "duplicate
request" in an attempt to repeat authorized commands. Its involves the passive capture of a
data unit and its subsequent retransmission to produce an unauthorized effect (Figure 1.4b).
Modification of messages simply means that some portion of a legitimate message is altered, or that
messages are delayed or reordered, to produce an unauthorized effect (Figure 1.4c). For example, a
message meaning "Allow John Smith to read confidential file accounts" is modified to mean "Allow
Fred Brown to read confidential file accounts."
The denial of service prevents or inhibits the normal use or management of communications facilities
(Figure 1.4d). This attack may have a specific target; for example, an entity may suppress all messages
directed to a particular destination (e.g., the security audit service). Another form of service denial is
the disruption of an entire network, either by disabling the network or by overloading it with messages
so as to degrade performance.
JITENDER SINGH LAMBA
LECT IT GITM
170
Active attacks present the opposite characteristics of passive attacks. Whereas passive attacks are
difficult to detect, measures are available to prevent their success. On the other hand, it is quite
difficult to prevent active attacks absolutely, because of the wide variety of potential physical,
software, and network vulnerabilities. Instead, the goal is to detect active attacks and to recover from
any disruption or delays caused by them. If the detection has a deterrent effect, it may also contribute
to prevention.
Security Services/security goal
1) AUTHENTICATION:-

The assurance that the communicating entity is the one that it claims to be.
Peer Entity Authentication
Used in association with a logical connection to provide confidence in the identity of the entities
connected.
Data Origin Authentication
In a connectionless transfer, provides assurance that the source of received data is as claimed.

2) ACCESS CONTROL:-
The prevention of unauthorized use of a resource (i.e., this service controls who can have access to a
resource, under what conditions access can occur, and what those accessing the resource are allowed to
do).

3) DATA CONFIDENTIALITY:-
The protection of data from unauthorized disclosure.
Connection Confidentiality
The protection of all user data on a connection.
Connectionless Confidentiality
The protection of all user data in a single data block
Selective-Field Confidentiality
The confidentiality of selected fields within the user data on a connection or in a single data block.
Traffic Flow Confidentiality
The protection of the information that might be derived from observation of traffic flows.

4) DATA INTEGRITY
The assurance that data received are exactly as sent by an authorized entity (i.e., contain no
modification, insertion, deletion, or replay).
Connection Integrity with Recovery
Provides for the integrity of all user data on a connection and detects any modification, insertion,
deletion, or replay of any data within an entire data sequence, with recovery attempted.
Connection Integrity without Recovery
JITENDER SINGH LAMBA
LECT IT GITM
171
As above, but provides only detection without recovery.
Selective-Field Connection Integrity
Provides for the integrity of selected fields within the user data of a data block transferred over a
connection and takes the form of determination of whether the selected fields have been modified,
inserted, deleted, or replayed.
Connectionless Integrity
Provides for the integrity of a single connectionless data block and may take the form of detection of
data modification. Additionally, a limited form of replay detection may be provided.
Selective-Field Connectionless Integrity
Provides for the integrity of selected fields within a single connectionless data block; takes the form of
determination of whether the selected fields have been modified.

5) NONREPUDIATION
Provides protection against denial by one of the entities involved in a communication of having
participated in all or part of the communication.
Nonrepudiation, Origin
Proof that the message was sent by the specified party.
Nonrepudiation, Destination
Proof that the message was received by the specified party.

Security Mechanisms:

1) Specific security mechanisms
May be incorporated into the appropriate protocol layer in order to provide some of the OSI security
services.
A) Encipherment:-
The use of mathematical algorithms to transform data into a form that is not readily intelligible. The
transformation and subsequent recovery of the data depend on an algorithm and zero or more
encryption keys.
B) Digital Signature:-
Data appended to, or a cryptographic transformation of, a data unit that allows a recipient of the data
unit to prove the source and integrity of the data unit and protect against forgery (e.g., by the recipient).
C) Access Control:-
A variety of mechanisms that enforce access rights to resources.
D) Data Integrity:-
A variety of mechanisms used to assure the integrity of a data unit or stream of data units.
E) Authentication Exchange:-
A mechanism intended to ensure the identity of an entity by means of information exchange.
F) Traffic Padding:-
The insertion of bits into gaps in a data stream to frustrate traffic analysis attempts
G) Routing Control:-
Enables selection of particular physically secure routes for certain data and allows routing changes,
especially when a breach of security is suspected.
H) Notarization:-
The use of a trusted third party to assure certain properties of a data exchange

JITENDER SINGH LAMBA
LECT IT GITM
172
2) Pervasive security mechanisms
Mechanisms that is not specific to any particular OSI security service or protocol layer
A) Trusted Functionality
That which is perceived to be correct with respect to some criteria (e.g., as established by a security
policy).
B) Security Label
The marking bound to a resource (which may be a data unit) that names or designates the security
attributes of that resource.
C) Event Detection
Detection of security-relevant events.
D) Security Audit Trail
Data collected and potentially used to facilitate a security audit, which is an independent review and
examination of system records and activities.
E) Security Recovery
Deals with requests from mechanisms, such as event handling and management functions, and takes
recovery actions.



Network security:-
Different types of threats to network:
Application backdoors - Some programs have special features that allow for remote access .
Others contain bugs that provide a backdoor , or hidden access , that provides some level of
control of the program.
SMTP session hijacking - SMTP is the most common method of Sending e-mail over the
Internet . By gaining access to a list of e- mail Addresses , a person can send unsolicited junk
e-mail ( spam ) to thousands of users . This is done quite often by redirecting the e-mail
through the SMTP server of an unsuspecting host , making the actual sender of the spam
difficult to trace.
Operating system bugs - Like applications, some operating systems Have backdoors. Others provide
remote access with insufficient security controls or have bugs that an experienced hacker can
take advantage of .
Denial of service - You have probably heard this phrase used in news reports on the attacks
on major Web sites . This type of attack is nearly Impossible quickly from one system to the next.
Viruses range from harmless messages to erasing all of your data .
Spam - Typically harmless but always annoying , spam is the electronic equivalent of junk
mail . Spam can be dangerous though. Quite often it contains links to Web sites. Be careful of
clicking on these because you may accidentally accept a cookie that provides a backdoor to
your computer.
Redirect bombs - Hackers can use ICMP to change ( redirect ) the Path information takes by
sending it to a different router . This is one of the ways that a denial of service attack is set
up.

Network security can be done by various methods.
1. Virtual Private Network:
A virtual private network ( VPN ) is a way to use a public telecommunication infrastructure , such
as the Internet , to provide remote offices or individual users with secure access to their
organization's network. A virtual private network can be contrasted with an expensive system of
owned or leased lines that can only be used by one organization. The goal of a VPN is to
provide the organization with the same capabilities , but at a much lower cost
Implementation of network security by VPN.
Step 1. - The remote user dials into their local ISP and logs into the ISPs network as usual.
JITENDER SINGH LAMBA
LECT IT GITM
173

Step 2. - When connectivity to the corporate network is desired, the user initiates a tunnel request to
the destination Security server on the corporate network. The security server authenticates the user and
creates the other end of tunnel.

Fig : a) A leased line private network b) A virtual private network

Step 3. - The user then sends data through the tunnel which encrypted by the VPN software before
being sent over the ISP connection.
JITENDER SINGH LAMBA
LECT IT GITM
174

Step 4. - The destination Security server receives the encrypted data and decrypts. The Security server
then forwards the decrypted data packets onto the corporate network. Any information sent back to the
Remote user is also encrypted before being sent over the Internet.


2. Firewalls:
A firewall provides a strong barrier between your private network and the Internet. You can set
firewalls to restrict the number of open ports , what type of packets are passed through and which
protocols are allowed through . You should already have a good firewall in place before you
implement a VPN , but a firewall can also be used to terminate the VPN

Fig2: A fire wall consisting of two packet filters and an application gateway
PC to server
A software firewall can be installed on the computer in your home that has an Internet
connection . This computer is considered a gateway because it provides the only point of
access between your home network and the Internet .
JITENDER SINGH LAMBA
LECT IT GITM
175

3. IPSec -
Internet Protocol Security Protocol (IPSec) provides enhanced security features such as
better encryption algorithms and more comprehensive authentication . IPSec has two encryption
modes:
Tunnel
Transport
Tunnel encrypts the header and the payload of each packet while transport only encrypts the
payload. Only systems that are IPSec compliant can take advantage of this Protocol. Also , all
devices must use a common key and the firewalls of each network must have very similar
security policies set up. IPSec can encrypt data between various devices, such as:
Router to router
Firewall to router
PC to router
4. AAA Server - AAA (authentication, authorization and accounting)
servers are used for more secure access in a remote-access VPN environment . When a request
to establish a session comes in from a dial up client , the Request is proxies to the AAA
server . AAA then checks the following:
Who you are (authentication)
What you are allowed to do (authorization)
What you actually do (accounting) the accounting information is especially useful for tracking client.
Use for security auditing, billing or reporting purposes.
A Model for Network Security:
A model for much of what we will be discussing is captured, in very general terms, in Figure 1.5. A
message is to be transferred from one party to another across some sort of internet. The two parties,
who are the principals in this transaction, must cooperate for the exchange to take place. A logical
information channel is established by defining a route through the internet from source to destination
and by the cooperative use of communication protocols (e.g., TCP/IP) by the two principals.

Security aspects come into play when it is necessary or desirable to protect the information
transmission from an opponent who may present a threat to confidentiality, authenticity, and so on. All
the techniques for providing security have two components:
A security-related transformation on the information to be sent. Examples include the
encryption of the message, which scrambles the message so that it is unreadable by the
opponent, and the addition of a code based on the contents of the message, which can be used
to verify the identity of the sender
Some secret information shared by the two principals and, it is hoped, unknown to the
opponent. An example is an encryption key used in conjunction with the transformation to
scramble the message before transmission and unscramble it on reception.
JITENDER SINGH LAMBA
LECT IT GITM
176
A trusted third party may be needed to achieve secure transmission. For example, a third party may be
responsible for distributing the secret information to the two principals while keeping it from any
opponent. Or a third party may be needed to arbitrate disputes between the two principals concerning
the authenticity of a message transmission.
This general model shows that there are four basic tasks in designing a particular security service:
1. Design an algorithm for performing the security-related transformation. The algorithm should
be such that an opponent cannot defeat its purpose.
2. Generate the secret information to be used with the algorithm.
3. Develop methods for the distribution and sharing of the secret information.
4. Specify a protocol to be used by the two principals that makes use of the security algorithm
and the secret information to achieve a particular security service
However, there are other security-related situations of interest that do not neatly fit this model. A
general model of these other situations is illustrated by Figure 1.6, which reflects a concern for
protecting an information system from unwanted access. Most readers are familiar with the concerns
caused by the existence of hackers, who attempt to penetrate systems that can be accessed over a
network. The hacker can be someone who, with no malign intent, simply gets satisfaction from
breaking and entering a computer system. Or, the intruder can be a disgruntled employee who wishes
to do damage, or a criminal who seeks to exploit computer assets for financial gain (e.g., obtaining
credit card numbers or performing illegal money transfers).

Another type of unwanted access is the placement in a computer system of logic that exploits
vulnerabilities in the system and that can affect application programs as well as utility programs, such
as editors and compilers. Programs can present two kinds of threats:
Information access threats intercept or modify data on behalf of users who should not have
access to that data.
Service threats exploit service flaws in computers to inhibit use by legitimate users.
The security mechanisms needed to cope with unwanted access fall into two broad categories (see
Figure 1.6). The first category might be termed a gatekeeper function. It includes password-based login
procedures that are designed to deny access to all but authorized users and screening logic that is
designed to detect and reject worms, viruses, and other similar attacks. Once either an unwanted user
or unwanted software gains access, the second line of defense consists of a variety of internal controls
that monitor activity and analyze stored information in an attempt to detect the presence of unwanted
intruders.



JITENDER SINGH LAMBA
LECT IT GITM
177
Cryptography:-
Cryptography is the science of writing in secret code and is an ancient art. In data and
telecommunications, cryptography is necessary when communicating over any untrusted medium,
which includes just about any network, particularly the Internet.
The three types of cryptographic algorithms that will be discussed are (Figure 1):
1. Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption
2. Public Key Cryptography (PKC): Uses one key for encryption and another for decryption
3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information

1. Secret Key Cryptography
With secret key cryptography, a single key is used for both encryption and decryption. As shown in
Figure the sender uses the key (or some set of rules) to encrypt the plain text and sends the cipher text
to the receiver. The receiver applies the same key (or rule set) to decrypt the message and recover the
plain text. Because a single key is used for both functions, secret key cryptography is also called
symmetric encryption. With this form of cryptography, it is obvious that the key must be known to
both the sender and the receiver; that, in fact, is the secret. The biggest difficulty with this approach, of
course, is the distribution of the key.
Secret key cryptography schemes are generally categorized as being either
Stream ciphers
Block ciphers.
Stream ciphers operate on a single bit (byte or computer word) at a time and implement some form
of feedback mechanism so that the key is constantly changing. A block cipher is so- called because
the scheme encrypts one block of data at a time using the same key on each block.
In general, the same plain text block will always encrypt to the same cipher text when using the same
key in a block cipher whereas the same plaintext will encrypt to different cipher text in a stream cipher.
2. Public key cryptography
Generic PKC employs two keys that are mathematically related although knowledge of one key does
not allow someone to easily determine the other key. One key is used to encrypt the plaintext and the
other key is used to decrypt the cipher text. The important point here is that it does not matter which
key is applied first, but that both keys are required for the process to work (Figure 1B). Because a pair
of keys is required, this approach is also called asymmetric cryptography












3. Hash Functions:
Hash functions, also called message digests and one-way encryption, are algorithms that, in some
sense, use no key (Figure 1C). Instead, a fixed-length hash value is computed based upon the plaintext
that makes it impossible for either the contents or length of the plaintext to be recovered. Hash
algorithms are typically used to provide a digital fingerprint of a file's contents often used to ensure
that the file has not been altered by an intruder or virus. Hash functions are also commonly employed
by many operating systems to encrypt passwords. Hash functions, then, help preserve the integrity of a
file.
4. TRUST MODELS
JITENDER SINGH LAMBA
LECT IT GITM
178
Secure use of cryptography requires trust. While secret key cryptography can ensure message
confidentiality and hash codes can ensure integrity, none of this works without trust. In SKC, PKC
solved the secret distribution problem. There are a number of trust models employed by various
cryptographic schemes.
The web of trust employed by Pretty Good Privacy (PGP) users, who hold their own set of
trusted public keys.
Kerberos, a secret key distribution scheme using a trusted third party.
Certificates, which allow a set of trusted third parties to authenticate each other and, by
implication, each other's users.
Each of these trust models differs in complexity, general applicability, scope, and scalability.
Types of authority
Establish identity: Associate, or bind, a public key to an individual, organization, corporate
position, or other entity.
Assign authority: Establish what actions the holder may or may not take based upon this
certificate.
Secure confidential information (e.g., encrypting the session's symmetric key for data
confidentiality).
Todays latest used cryptographic techniques:
Hash algorithms that are in common use today include:
Message Digest (MD) algorithms
Secure Hash Algorithm (SHA)
Pretty Good Privacy (PGP)
Pretty Good Privacy (PGP) is one of today's most widely used public key cryptography programs. PGP
can be used to sign or encrypt e-mail messages with mere click of the mouse. Depending upon the
version of PGP, the software uses SHA or MD5 for calculating the message hash; CAST, Triple-DES,
or IDEA for encryption; and RSA or DSS/Diffie-Hellman for key exchange and digital signatures. And
much more techniques used.
Time is the only true test of good cryptography; any cryptographic scheme that stays in use year after
year is most likely a good one. The strength of cryptography lies in the choice (and management) of
the keys; longer keys will resist attack better than shorter keys
Encrypt and decrypt messages using any of the classical substitution ciphers
discussed, both by hand and with the assistance of programs. Understand the concepts
of language redundancy and unicity distance.
Comparing Stream and Block Algorithms.
Stream Encryption Algorithms Block Encryption Algorithms
Advantages Speed of transformation. Because each
symbol is encrypted without regard for any
other plaintext symbols, each symbol can be
encrypted as soon as it is read. Thus, the
time to encrypt a symbol depends only on
the encryption algorithm itself, not on the
time it takes to receive more plaintext.
Low error propagation. Because each
symbol is separately encoded, an error in
the encryption process affects only that
character.
High diffusion. Information from
the plain-text is diffused into
several cipher text symbols. One
cipher text block may depend on
several plaintext letters.
Immunity to insertion of symbols.
Because blocks of symbols are
enciphered, it is impossible to
insert a single symbol into one
block. The length of the block
would then be incorrect, and the
decipherment would quickly reveal
the insertion.
JITENDER SINGH LAMBA
LECT IT GITM
179
Comparing Stream and Block Algorithms.
Stream Encryption Algorithms Block Encryption Algorithms
Disadvantages Low diffusion. Each symbol is separately
enciphered. Therefore, all the information
of that symbol is contained in one symbol
of the cipher text.
Susceptibility to malicious insertions and
modifications. Because each symbol is
separately enciphered, an active interceptor
who has broken the code can splice together
pieces of previous messages and transmit a
spurious new message that may look
authentic.
Slowness of encryption. The
person or machine using a block
cipher must wait until an entire
block of plaintext symbols has
been received before starting the
encryption process.
Error propagation. An error will
affect the transformation of all
other characters in the same block.


Comparing Secret Key and Public Key Encryption.
Secret Key (Symmetric) Public Key (Asymmetric)
Number of
keys
1 2
Protection of
key
Must be kept secret One key must be kept secret; the
other can be freely exposed
Best uses Cryptographic workhorse; secrecy and integrity of data
single characters to blocks of data, messages, files
Key exchange, authentication
Key
distribution
Must be out-of-band Public key can be used to distribute
other keys
Speed Fast Slow; typically, 10,000 times slower
than secret key



Q1 Explain difference between substitution ciphers & Transportation ciphers?
Q2. Explain difference between WWW & internet?
Q3. Explain difference between synchronous and asynchronous modem?


JAVA script:-

What is JavaScript?

JavaScript is a World Wide Web Scripting language that is understood by the browser when it is between the
<SCRIPT> and </SCRIPT> tags. JavaScript was developed by Netscape Communications and Sun Microsystems.
JavaScript is an essential tool for advanced web development.

JITENDER SINGH LAMBA
LECT IT GITM
180
Embedding JavaScript in a HTML Document :( structure of HTML Document with Java
Script):
JavaScript scripts are included in HTML documents via the <SCRIPT tag.
Script tag can be placed in HTML Document is 3 ways.
1. Immediate Scripts.
2. Deferred Scripts.
3. Hybrid Scripts.
1. Immediate Scripts:-
It indicates lines of Java Script that not only run when the browser loads the document, but also
influence the layout of the page.

Structure of HTML Document without JavaScript:
<HEAD>
<TITLE>Name of Webpage</TITLE>
</HEAD>
<BODY>

</BODY>
</HTML>
Structure of HTML Document with Immediate JavaScript:

<HTML>
<HEAD>
<TITLE>NAME OF PAGE</TITLE
</HEAD>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT>
//WRITE CODE HERE
</SCRIPT>
</BODY>
</HTML>


2. Deferred Scripts:-
A Deferred scripts that the browser sees when the document loads, but the wording of the script tells
the browser not to-do anything with the code other than to be aware that it exits.
The primary reason you are encouraged to put deferred scripts into the HEAD is that they load into the
browsers memory first-even before any visible content appears on the page.
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JAVASCRIPT>
//Write script code here
</SCRIPT>
</HEAD>
<BODY>
//Staments write here
</BODY>
</HTML>

3. Hybrid Scripts:
Designing a page that requires both immediate and deferred scripts. The immediate script lines help
create the content of the page, deferred script lines react to users actions once the page has fully
loaded.
JITENDER SINGH LAMBA
LECT IT GITM
181
Immediate Script in the Body block calls a Deferred Script in the Head.

<HTML>
<HEAD>
<SCRIPT LANGUAGE=JAVASCRIPT>
//Write script lines
</SCRIPT>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT>
//write script lines
</SCRTPT>
</BODY>
</HTML>

Creating Variables :
Var variablename;

Assigning value to variable:
Assign a value to variable using assignment operator(=).
Variablename = value;
Or
Var variablename=value;
Ex: var range=20;

Print a line or text:
Print a text using document.write() method.
Ex: document.write(HELLOW);

<HTML>
<HEAD>
<TITLE>NAME</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT>
document.write (hellow javascript);
</SCRIPT>
</BODY>
</HTML>
We must save the file .html or .htm and run the program using browser. ex.html

O/p:
Netscape Navigator -+
---------------------------------------------------------------------------------
Address: - c:/msc216/ex.html
---------------------------------------------------------------------------------
hello javascript
Expressions and Evalution:

Var varname=100;
Var varname1=varname-50;
document.write(varname1);
output :50

Statements and Functions:-
JITENDER SINGH LAMBA
LECT IT GITM
182
Statements:-
JavaScript Statements cannot be used as variable names and are used for specific tasks with in the
script.
1. Comments.
2. Conditional Statements.
3. Loop Statements.
4. Object Manipulation Statements.
1. Comments:-
Two types of comments.
a) Single line comments (//).
b) Multiple line comments (/* */).

2. Conditional Statements:-
Conditional Statements are performed based on the logic of the code.There is only one conditional
Statement in JavaScript.
Syntax:-
If..else

Example:
ifdemo.html

<HTML>
<HEAD>
<TITLE>IF STATEMENT</TITLE>
</HEAD>
<BODY FONTCOLR=RED>
<SCRIPT LANGUAGE=JAVASCRIPT><!
a =100
b=50
if(a>b) {
document.write(bignumber is:)
document.write(a)
}
else {
document.write(bignumber is:)
document.write(b);
}
// -->
</SCRIPT>
</BODY>
</HTML>

Output:

NetScape Navigator
Address: c:/ifemo.html

Bignumber is:100

3. Loop Statements:-
A Loop is used to perform a set of code statements repeatedly.
a) While
b) For

whiledemo.html
JITENDER SINGH LAMBA
LECT IT GITM
183

<HTML>
<HEAD>
<TITLE>WHILE STATEMENT</TITLE>
</HEAD>
<BODY FONTCOLR=RED>
<SCRIPT LANGUAGE=JAVASCRIPT><!
I =1;
While(I<6) {
document.write(I)
++I
}
// -->
</SCRIPT>
</BODY>
</HTML
Output:

NetScape Navigator
Address: c:/whiledemo.html

1
2
3
4
5

fordemo.html

<HTML>
<HEAD>
<TITLE>FOR STATEMENT</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT>
for(i=1; i<=5; i++)
document.writeln(i);
</SCRIPT>
</BODY>
</HTML>

Output:
NetScape Navigator
Address: c:/fordemo.html
1
2
3
4
5
With Statement:-
The with statement is provided as a convenience to eliminate retyping the name of an object that is to
be referenced in a series of property references and method invocations.
JITENDER SINGH LAMBA
LECT IT GITM
184
Syntax:

With (variable name) {
Statement
}
example:-
with(Math) {result = pow(6,2) * PI}
which is equal to below statement.
Result=Math.pow(6,2)*Math.PI

JavaScript Functions:-
One of the most important concepts you need to understand about JavaScript is Functions. A
function is basically a segment of code that is called via an event handler or called from another
function.




Defining Functions:-
A Function must be defined before it can be used. Function definitions are usually placed in the head
of an HTML document. Placing function definitions in the head, hower ensures that the definition
occurs before the function is used.

Syntax:-
Function function name (arg1, arg2 ) {
Statements
}

Example:

functiondemo.html


<HTML>
<HEAD>
<TITLE>FUNCTIONS DEMO</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT><!
function biggest(n1,n2) {
if(n1>n2) {
document.write(biggest number is:)
document.write(n1)
}else {
document.write(biggest number is:)
document.write(n2)
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT><!
biggest(100,500)
// -->
</SCRIPT>
</BODY>
</HTML>
JITENDER SINGH LAMBA
LECT IT GITM
185


Output:

InterNet Explorer
Location: c:/functiondemo.html
Biggest number is:100

Built-In JavaScript Functions (or) Conversion Functions:-
JavaScript provides 3 functions which are used to perform explicit type conversion.:
1.eval()
2.parseInt()
3.parseFloat()

Example:
ex.html
<HTML>
<HEAD>
<TITLE> BUILT-IN FUNCTIONS</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT><!
document.write(eval(12.34*10))
document.writeln(parseInt(0x10))
document.writeln(parseFloat(5.4321e6))
// -->
</SCRIPT>
</BODY>
</HTML>


Output:-

Internet Explorer
Location:- c:/ex.html
123.4
16
5432100



Arrays:-

JavaScript supports tow other variables types arrays and objects. These types are referred to as complex data
types because they are built from the primitive string, numeric, logical types.

Declaration:

Array name=new Array (array length)
Array name=new Array ()




JITENDER SINGH LAMBA
LECT IT GITM
186

Example: - arraydemo.html

<HTML>
<HEAD><TITLE>ARRAYS</TITLE></HEAD>
<H1 ALIGN=CENTER>USING ARRAYS</H1>
<SCRIPT LANGUAGE=JAVASCRIPT>
name=new Array(2)
name[0] = suresh
name[1] = kumar
document.write(name[0])
document.write(name[1])
// --></SCRIPT>
</BODY>
</HTML>


Output:
Internet Explorer
Address: c:/arraydemo.html
Using Arrays
suresh
kumar


Math Functions:-
Math.PI // Value=3.141
Math.SQET1-2 // Square root of
Math.SQRT2 //Square root of 2
Math.LN2 //Natural log of 2
Math.LN10 // Natural log of 10

Math Object Methods:-
Math.abs(val)
Math.min(val1,val2)
Math.max(val1,val2)
Math.sqrt(val1)
Math.pow(val1,val2)
Math.tan(val)

String Manipulations:-
To convert from lower case to upper case and vice varsa.
1.String.toLowerCase()
2.string.toUpperCase()

other functions:
string.length //returns the how many characters in that.
String.indexOf(searchString.[,startIndex])
Ex:-name=bananas.indexOf(b)
Output: 0
String.lastIndexOf(character)
String.charAt(position)

String Methods:-
String.big()
JITENDER SINGH LAMBA
LECT IT GITM
187
String.blink() (or) <BLINK> </BLINK>
String.fontSize(0 to 7)
String.strike() (or) <STRIKE> </STRIKE>
String.sup() (or) <SUP> </SUP>
String.bold() (or) <B> </B>
String.fontcolor() <FONT COLOR= > String.italics() (or)
<I> </I>
String.small()
String.sub() (or) <SUB> </SUB>

Date Object Type:-
The Date object type provides a common set of methods for working with dates and times.
Methods:-
getDate() getTime()
getDay() getYear()
getHours() getMinutes()
getSeconds() getMonth()

Date Constructer:
Date()
Example:-
datedemo.html
<HTML>
<HEAD><TITLE>DATEDEMO</TITLE></HEAD>
<BODY>
<SCRIPT LANGUAGE=JAVASCRIPT<!
cd=new Date()
document.write(cd.getMonth()+/+getDate()+/+getYear())
document.write(cd.getHours()+:+cd.getMinutes()+:+cd.getSeconds())
// --></SCRIPT>
</BODY></HTML>

Output:-

Internet Explorer
Address: c:/datedemo.html

8/7/03
9:46:26


Hyper Link:-
Link () method is used to create a link to the website or URL.
Syntax:-
Name=string.link(URL)

JITENDER SINGH LAMBA
LECT IT GITM
188
Example:-
Internet Explorer
Address: c:/linkdemo.html
Mail Room
Rediffmail
Yahoomail
Hotmail

Code:-
<HTML>
<HEAD><TITLE>URL</TITLE></HEAD>
<BODY>
<H1>Mail Romm</H1>
<SCRIPT LANGUAGE=JAVASCRIPT>
name=Rediffmail.link(http://www.rediffmail.com)
document(name)
name1=Yahoo.link(http://www.yahoo.com)
document(name1
name=Hotmail.link(http://www.hotmail.com)
document(name)

</SCRIPT>
</BODY>
</HTML>

Event Handlers:-
An event handler executes a segment of code based on certain events,such as OnLoad and
OnClick,occurring within the application.
JavaScript event handlers can be divided into 2 types.
1. Interactive event handlers.
2. Non-interactive event handlers.
1. Interactive event handlers:-
It depends on the user interaction with the form or document.
Ex: - onMouseOver is an interactive event handler, because it depends on the users action with the
mouse.

2. Non-interactive event handlers:-
OnLoad is a non-interactive event handler, because it automatically executes JavaScript code without
the users interaction.
Below list the event handlers in JavaScript.

Name Used In

OnAbort image
OnBlur select,text,textarea
OnChange select,text,textarea
OnClick button,checkbox,radio,link,submit
OnLoad select,text,textarea
OnUnload window
OnSubmit form
OnMouseOut link,area
OnMouseOver link,area
JITENDER SINGH LAMBA
LECT IT GITM
189
OnFocus select,text,image

OnChange:-
The OnChange eventhandler executes JavaScript code when input focus exits the field after the user
modifies its text.

<HTML>
<HEAD><TITLE>EXAMPLE</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT>
function valid(form) {
var input=0;
input=document.myform.data.value;
alert(you have changed the value from 10 to+input);
}
</SCRIPT>
</HEAD>
<BODY FONT COLOR=RED>
Try changing the value from 10 to something:
<FORM NAME=myform>
<INPUT TYPE=text NAME=data value=10 size=10
onChange=valid(this.form)>
</FORM>
</BODY>
</HTML>



Output:

IE
Address: c:/e.html
Try changining the value from 10 to something:

20


OnBlur:
An OnBlur event handler executes javascript when input focus leaves the field of a text,textarea,or
select. In windows you need to specify the event handler in the <body> attribute.
<HTML>
<HEAD><TITLE>EXAMPLE</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT>
function valid(form) {
var input=0;
input=document.myform.data.value;
if(input<0) {
alert(please input a value that is more than 0);
}
}
</SCRIPT></HEAD>
<BODY>
Try inputing a value less than 0:
<FORM name=myform
<INPUT TYPE=text NAME=data value= SIZE=10
JITENDER SINGH LAMBA
LECT IT GITM
190
OnBlur=valid(this.form)>
</FORM></BODY>
</HTML>
Output:-
Internet Explorer
Address: c:/f.html
Try inputing a value less than 0:
-2
onAbort:-
An onAbort event handler executes javascript code when the user aborts loading an image.

<HTML>
<HEAD><TITLE>EXAMPLE</TITLE></HEAD>
<BODY>
<B> STOP the Loading of this image and see what happens:</B>
<IMG SRC=http://www.cup.com/cup.jpg onAbort=alert(you stopped the loading the image)>
</BODY>
</HTML>

Output:-
Internet Explorer
Address: c:/a.html
STOP Loading this image and see what happens:

JavaScript Alert
You stopped loading the image
OK


onFocus:-
An onFocus event handler executes javascript code when a field receives input focus by the users
tabbling in or by clicking but not selecting in the field.

<HTML>
<HEAD><TITLE>EXAMPLE</TITLE>
<BODY>
<H3>onFocus</H3>
Put your mouse into the textbox:
<FORM NAME=myform>
<INPUT TYPE=text NAME=data VALUE= SIZE=10
onFocus=alert(You foused the textbox)>
</FORM>
</BODY>
</HTML>

Output:
Internet Explorer
Address: c:/f.html
Put your mouse into the textbox.
---------
JITENDER SINGH LAMBA
LECT IT GITM
191
--------- JavaScript Alert
You foused the textbox
OK


onLoad:-
An onLoad event occurs when a window or image finishes loading.For windows this event handler is
specified in the <BODY> attribute.For image in <IMG>.
on.html
<HTML>
<HEAD>EXAMPLE</TITLE></HEAD>
<SCRIPT LANGUAGE=JAVASCRIPT>
<IMG NAME=myimage SRC=http://bec.ac.in/pho.jpg
onLoad=alert(you loaded myimage)>
</IMG>
</SCRIPT></HTML>

Output:-
Internet Explorer
Address: c:/on.html

JavaScript ALERT
You loaded myimage
OK

Scripting Languages Vs Programming Languages

Scripting Language Programming Language
1) It is an Interpreter based Language 1) It is a compiler based Language.
2) Interpreter converts high level
instructions into machine language line by
line
2) Compiler converts the whole program in single short
into machine language.
3) It doesnt create executable file. 3) It Creates .exe file.
4) No need to compile the program Need to compile the program
5) It takes less code 4) It takes numerous lines of code
6) It greatly reduces development time 5) It increases development time
7) It reduces maintenance of cost 7) It Increases maintenance of cost

VBSCRIPT:-

What is VBScript?
VBScript is a scripting language
A scripting language is a lightweight programming language
VBScript is a light version of Microsoft's programming language Visual Basic
How does it Work?
When a VBScript is inserted into an HTML document, the Internet browser will read the HTML and
interpret the VBScript. The VBScript can be executed immediately, or at a later event.
The HTML <script> tag is used to insert a VBScript into an HTML page.
JITENDER SINGH LAMBA
LECT IT GITM
192
Put a VBScript into an HTML Page
The example below shows how to use VBSript to write text on a web page:
Example (IE Only)
<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
Example Explained
To insert a VBScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the
type attribute to define the scripting language. So, the <script type="text/vbscript"> and </script> tells
where the VBScript starts and ends. The document.write command is a standard VBScript command
for writing output to a page. By entering the document.write command between the <script> and
</script> tags, the browser will recognize it as a VBScript command and execute the code line. In this
case the browser will write Hello World! to the page:
Where to Put the VBScript
VBScripts in a page will be executed immediately while the page loads into the browser. This is not
always what we want. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button. When this is the case we put the script inside a function or a sub
procedure, you will learn about procedures in a later chapter.
Scripts in <head>
Put your functions and sub procedures in the head section, this way they are all in one place, and they
do not interfere with page content.
Example (IE Only)
<html>
<head>
<script type="text/vbscript">
function myFunction()
alert("Hello World!")
end function
</script>
</head>
<body onload="myFunction()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function, and especially if your script should write
page content, it should be placed in the body section.
Example (IE Only)
<html>
<head>
<script type="text/vbscript">
function myFunction()
alert("Hello World!")
JITENDER SINGH LAMBA
LECT IT GITM
193
end function
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script type="text/vbscript">
document.write("This message is written by VBScript")
</script>
</body>
</html>
Using an External VBScript
If you want to run the same VBScript on several pages, without having to write the same script on
every page, you can write a VBScript in an external file. Save the external VBScript file with a .vbs
file extension.
Note: The external script cannot contain the <script> tag!
To use the external script, point to the .vbs file in the "src" attribute of the <script> tag:
Example
<html>
<head>
<script type="text/vbscript" src="ex.vbs"></script>
</head>
<body>
</body>
</html>
VBScript Variables
Variables are "containers" for storing information. As with algebra, VBScript variables are used to
hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like
carname. Rules for VBScript variable names:
Must begin with a letter
Cannot contain a period (.)
Cannot exceed 255 characters
In VBScript, all variables are of type variant, that can store different types of data.
Declaring (Creating) VBScript Variables
Creating variables in VBScript is most often referred to as "declaring" variables.You can declare
VBScript variables with the Dim, Public or the Private statement. Like this:
Dim x
Dim carname
Now you have created two variables. The name of the variables are "x" and "carname".
You can also declare variables by using its name in a script. Like this:
carname="Volvo"
Now you have also created a variable. The name of the variable is "carname". However, this method is
not a good practice, because you can misspell the variable name later in your script, and that can cause
strange results when your script is running.
JITENDER SINGH LAMBA
LECT IT GITM
194
If you misspell for example the "carname" variable to "carnime", the script will automatically create a
new variable called "carnime". To prevent your script from doing this, you can use the Option Explicit
statement. This statement forces you to declare all your variables with the dim, public or private
statement.
Put the Option Explicit statement on the top of your script. Like this:
Option Explicit
Dim carname
carname=some value


Assigning Values to Variables
You assign a value to a variable like this:
carname="Volvo"
x=10
The variable name is on the left side of the expression and the value you want to assign to the variable
is on the right. Now the variable "carname" has the value of "Volvo", and the variable "x" has the
value of "10".

Lifetime of Variables
How long a variable exists is its lifetime.
When you declare a variable within a procedure, the variable can only be accessed within that
procedure. When the procedure exits, the variable is destroyed. These variables are called local
variables. You can have local variables with the same name in different procedures, because each is
recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures on your page can access it. The
lifetime of these variables starts when they are declared, and ends when the page is closed.

VBScript Array Variables
An array variable is used to store multiple values in a single variable.
In the following example, an array containing 3 elements is declared:
Dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a
fixed-size array. You assign data to each of the elements of the array like this:
names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
Similarly, the data can be retrieved from any element using the index of the particular array element
you want. Like this:
mother=names(0)
You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the
numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows
and 7 columns:
JITENDER SINGH LAMBA
LECT IT GITM
195
Dim table(4,6)
Asign data to a two-dimensional array:
Example (IE Only)
<html>
<body>

<script type="text/vbscript">
Dim x(2,2)
x(0,0)="Volvo"
x(0,1)="BMW"
x(0,2)="Ford"
x(1,0)="Apple"
x(1,1)="Orange"
x(1,2)="Banana"
x(2,0)="Coke"
x(2,1)="Pepsi"
x(2,2)="Sprite"
for i=0 to 2
document.write("<p>")
for j=0 to 2
document.write(x(i,j) & "<br />")
next
document.write("</p>")
next
</script>

</body>
</html>
VBScript Procedures
VBScript has two kinds procedures:
Sub procedure
Function procedure
VBScript Sub Procedures
A Sub procedure:
is a series of statements, enclosed by the Sub and End Sub statements
can perform actions, but does not return a value
can take arguments
without arguments, it must include an empty set of parentheses ()
Sub mysub()
some statements
End Sub
or
Sub mysub (argument1,argument2)
some statements
End Sub

JITENDER SINGH LAMBA
LECT IT GITM
196
Example (IE Only)
Sub mysub()
alert ("Hello World")
End Sub

Try it yourself
VBScript Function Procedures
A Function procedure:
is a series of statements, enclosed by the Function and End Function statements
can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name
Function myfunction()
some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

Example (IE Only)
function myfunction()
myfunction=Date()
end function

Try it yourself
How to Call a Procedure
There are different ways to call a procedure. You can call it from within another procedure, on an
event, or call it within a script.
Example (IE Only)
Call a procedure when the user clicks on a button:
<body>
<button onclick="myfunction()">Click me</button>
</body>

Try it yourself
Procedures can be used to get a variable value:
carname=findname()
JITENDER SINGH LAMBA
LECT IT GITM
197
Here you call a Function called "findname", the Function returns a value that will be stored in the
variable "carname". Function procedures can calculate the sum of two arguments:
Example (IE Only)
Function myfunction(a,b)
myfunction=a+b
End Function

document.write(myfunction(5,9))


The function "myfunction" will return the sum of argument "a" and argument "b". In this case 14.
When you call a procedure you can use the Call statement, like this:
Call MyProc(argument)
Or, you can omit the Call statement, like this:
MyProc argument
VBScript Conditional Statements
Conditional Statements
Conditional statements are used to perform different actions for different decisions.
In VBScript we have four conditional statements:
If statement - executes a set of code when a condition is true
If...Then...Else statement - select one of two sets of lines to execute
If...Then...ElseIf statement - select one of many sets of lines to execute
Select Case statement - select one of many sets of lines to execute

If...Then...Else
Use the If...Then...Else statement if you want to
execute some code if a condition is true
select one of two blocks of code to execute
If you want to execute only one statement when a condition is true, you can write the code on one line:
If i=10 Then alert("Hello")
There is no ..Else.. in this syntax. You just tell the code to perform one action if a condition is true (in
this case If i=10).
If you want to execute more than one statement when a condition is true, you must put each statement
on separate lines, and end the statement with the keyword "End If":
If i=10 Then
alert("Hello")
i = i+1
End If
There is no ..Else.. in the example above either. You just tell the code to perform multiple actions if
the condition is true.
If you want to execute a statement if a condition is true and execute another statement if the condition
is not true, you must add the "Else" keyword:
JITENDER SINGH LAMBA
LECT IT GITM
198
<html>
<body>
<script type="text/vbscript">
Function greeting()
i=hour(time)
If i < 10 Then
document.write("Good morning!")
Else
document.write("Have a nice day!")
End If
End Function
</script>
</head>

<body onload="greeting()">
</body>

</html>
In the example above, the first block of code will be executed if the condition is true, and the other
block will be executed otherwise (if i is greater than 10).

If...Then...ElseIf
You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to
execute:
JITENDER SINGH LAMBA
LECT IT GITM
199
Example (IE Only)
<html>
<body>
<script type="text/vbscript">
Function greeting()
i=hour(time)
If i = 10 Then
document.write("Just started...!")
ElseIf i = 11 then
document.write("Hungry!")
ElseIf i = 12 then
document.write("Ah, lunch-time!")
ElseIf i = 16 then
document.write("Time to go home!")
Else
document.write("Unknown")
End If
End Function
</script>
</head>

<body onload="greeting()">
</body>

</html>




Select Case
You can also use the "Select Case" statement if you want to select one of many blocks of code to
execute:
JITENDER SINGH LAMBA
LECT IT GITM
200
Example (IE Only)
<html>
<body>
<script type="text/vbscript">
d=weekday(date)
Select Case d
Case 1
document.write("Sleepy Sunday")
Case 2
document.write("Monday again!")
Case 3
document.write("Just Tuesday!")
Case 4
document.write("Wednesday!")
Case 5
document.write("Thursday...")
Case 6
document.write("Finally Friday!")
Case else
document.write("Super Saturday!!!!")
End Select
</script>

</body>
</html>
This is how it works: First we have a single expression (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each Case in the structure. If there is
a match, the block of code associated with that Case is executed.
VBScript Looping
Looping Statements
Looping statements are used to run the same block of code a specified number of times.
In VBScript we have four looping statements:
For...Next statement - runs code a specified number of times
For Each...Next statement - runs code for each item in a collection or each element of an
array
Do...Loop statement - loops while or until a condition is true
While...Wend statement - Do not use it - use the Do...Loop statement instead

For...Next Loop
Use the For...Next statement to run a block of code a specified number of times.
The For statement specifies the counter variable (i), and its start and end values. The Next statement
increases the counter variable (i) by one.
JITENDER SINGH LAMBA
LECT IT GITM
201
Example
<html>
<body>

<script type="text/vbscript">
For i = 0 To 5
document.write("The number is " & i & "<br />")
Next
</script>

</body>
</html>
The Step Keyword
With the Step keyword, you can increase or decrease the counter variable by the value you specify.
In the example below, the counter variable (i) is INCREASED by two, each time the loop repeats.
For i=2 To 10 Step 2
some code
Next
To decrease the counter variable, you must use a negative Step value. You must specify an end value
that is less than the start value.
In the example below, the counter variable (i) is DECREASED by two, each time the loop repeats.
For i=10 To 2 Step -2
some code
Next
Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.
For i=1 To 10
If i=5 Then Exit For
some code
Next

For Each...Next Loop
A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an
array.
JITENDER SINGH LAMBA
LECT IT GITM
202
Example
<html>
<body>

<script type="text/vbscript">
Dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"

For Each x In cars
document.write(x & "<br />")
Next
</script>

</body>
</html>

Do...Loop
If you don't know how many repetitions you want, use a Do...Loop statement.
The Do...Loop statement repeats a block of code while a condition is true, or until a condition becomes
true.
Repeat Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.
Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10.
Repeat Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
some code
Loop Until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...Loop
JITENDER SINGH LAMBA
LECT IT GITM
203
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater
than 10.

VBSCRIPT:-

What is VBScript?
VBScript is a scripting language
A scripting language is a lightweight programming language
VBScript is a light version of Microsoft's programming language Visual Basic
How does it Work?
When a VBScript is inserted into an HTML document, the Internet browser will read the HTML and
interpret the VBScript. The VBScript can be executed immediately, or at a later event.
The HTML <script> tag is used to insert a VBScript into an HTML page.
Put a VBScript into an HTML Page
The example below shows how to use VBSript to write text on a web page:
Example (IE Only)
<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
Example Explained
To insert a VBScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the
type attribute to define the scripting language. So, the <script type="text/vbscript"> and </script> tells
where the VBScript starts and ends. The document.write command is a standard VBScript command
for writing output to a page. By entering the document.write command between the <script> and
</script> tags, the browser will recognize it as a VBScript command and execute the code line. In this
case the browser will write Hello World! to the page:
Where to Put the VBScript
VBScripts in a page will be executed immediately while the page loads into the browser. This is not
always what we want. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button. When this is the case we put the script inside a function or a sub
procedure, you will learn about procedures in a later chapter.
JITENDER SINGH LAMBA
LECT IT GITM
204
Scripts in <head>
Put your functions and sub procedures in the head section, this way they are all in one place, and they
do not interfere with page content.
Example (IE Only)
<html>
<head>
<script type="text/vbscript">
function myFunction()
alert("Hello World!")
end function
</script>
</head>
<body onload="myFunction()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function, and especially if your script should write
page content, it should be placed in the body section.
Example (IE Only)
<html>
<head>
<script type="text/vbscript">
function myFunction()
alert("Hello World!")
end function
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script type="text/vbscript">
document.write("This message is written by VBScript")
</script>
</body>
</html>
Using an External VBScript
If you want to run the same VBScript on several pages, without having to write the same script on
every page, you can write a VBScript in an external file. Save the external VBScript file with a .vbs
file extension.
Note: The external script cannot contain the <script> tag!
To use the external script, point to the .vbs file in the "src" attribute of the <script> tag:
Example
<html>
<head>
<script type="text/vbscript" src="ex.vbs"></script>
</head>
<body>
</body>
</html>
JITENDER SINGH LAMBA
LECT IT GITM
205
VBScript Variables
Variables are "containers" for storing information. As with algebra, VBScript variables are used to
hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like
carname. Rules for VBScript variable names:
Must begin with a letter
Cannot contain a period (.)
Cannot exceed 255 characters
In VBScript, all variables are of type variant, that can store different types of data.
Declaring (Creating) VBScript Variables
Creating variables in VBScript is most often referred to as "declaring" variables.You can declare
VBScript variables with the Dim, Public or the Private statement. Like this:
Dim x
Dim carname
Now you have created two variables. The name of the variables are "x" and "carname".
You can also declare variables by using its name in a script. Like this:
carname="Volvo"
Now you have also created a variable. The name of the variable is "carname". However, this method is
not a good practice, because you can misspell the variable name later in your script, and that can cause
strange results when your script is running.
If you misspell for example the "carname" variable to "carnime", the script will automatically create a
new variable called "carnime". To prevent your script from doing this, you can use the Option Explicit
statement. This statement forces you to declare all your variables with the dim, public or private
statement.
Put the Option Explicit statement on the top of your script. Like this:
Option Explicit
Dim carname
carname=some value


Assigning Values to Variables
You assign a value to a variable like this:
carname="Volvo"
x=10
The variable name is on the left side of the expression and the value you want to assign to the variable
is on the right. Now the variable "carname" has the value of "Volvo", and the variable "x" has the
value of "10".

Lifetime of Variables
How long a variable exists is its lifetime.
When you declare a variable within a procedure, the variable can only be accessed within that
procedure. When the procedure exits, the variable is destroyed. These variables are called local
JITENDER SINGH LAMBA
LECT IT GITM
206
variables. You can have local variables with the same name in different procedures, because each is
recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures on your page can access it. The
lifetime of these variables starts when they are declared, and ends when the page is closed.

VBScript Array Variables
An array variable is used to store multiple values in a single variable.
In the following example, an array containing 3 elements is declared:
Dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a
fixed-size array. You assign data to each of the elements of the array like this:
names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
Similarly, the data can be retrieved from any element using the index of the particular array element
you want. Like this:
mother=names(0)
You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the
numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows
and 7 columns:
Dim table(4,6)
Asign data to a two-dimensional array:
JITENDER SINGH LAMBA
LECT IT GITM
207
Example (IE Only)
<html>
<body>

<script type="text/vbscript">
Dim x(2,2)
x(0,0)="Volvo"
x(0,1)="BMW"
x(0,2)="Ford"
x(1,0)="Apple"
x(1,1)="Orange"
x(1,2)="Banana"
x(2,0)="Coke"
x(2,1)="Pepsi"
x(2,2)="Sprite"
for i=0 to 2
document.write("<p>")
for j=0 to 2
document.write(x(i,j) & "<br />")
next
document.write("</p>")
next
</script>

</body>
</html>
VBScript Procedures
VBScript has two kinds procedures:
Sub procedure
Function procedure
VBScript Sub Procedures
A Sub procedure:
is a series of statements, enclosed by the Sub and End Sub statements
can perform actions, but does not return a value
can take arguments
without arguments, it must include an empty set of parentheses ()
Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub

JITENDER SINGH LAMBA
LECT IT GITM
208
Example (IE Only)
Sub mysub()
alert("Hello World")
End Sub
VBScript Function Procedures
A Function procedure:
is a series of statements, enclosed by the Function and End Function statements
can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name
Function myfunction()
some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

Example (IE Only)
function myfunction()
myfunction=Date()
end function
How to Call a Procedure
There are different ways to call a procedure. You can call it from within another procedure, on an
event, or call it within a script.
Example (IE Only)
Call a procedure when the user clicks on a button:
<body>
<button onclick="myfunction()">Click me</button>
</body>
Procedures can be used to get a variable value:
carname=findname()
Here you call a Function called "findname", the Function returns a value that will be stored in the
variable "carname". Function procedures can calculate the sum of two arguments:
JITENDER SINGH LAMBA
LECT IT GITM
209
Example (IE Only)
Function myfunction(a,b)
myfunction=a+b
End Function

document.write(myfunction(5,9))
The function "myfunction" will return the sum of argument "a" and argument "b". In this case 14.
When you call a procedure you can use the Call statement, like this:
Call MyProc(argument)
Or, you can omit the Call statement, like this:
MyProc argument
VBScript Conditional Statements
Conditional Statements
Conditional statements are used to perform different actions for different decisions.
In VBScript we have four conditional statements:
If statement - executes a set of code when a condition is true
If...Then...Else statement - select one of two sets of lines to execute
If...Then...ElseIf statement - select one of many sets of lines to execute
Select Case statement - select one of many sets of lines to execute

If...Then...Else
Use the If...Then...Else statement if you want to
execute some code if a condition is true
select one of two blocks of code to execute
If you want to execute only one statement when a condition is true, you can write the code on one line:
If i=10 Then alert("Hello")
There is no ..Else.. in this syntax. You just tell the code to perform one action if a condition is true (in
this case If i=10).
If you want to execute more than one statement when a condition is true, you must put each statement
on separate lines, and end the statement with the keyword "End If":
If i=10 Then
alert("Hello")
i = i+1
End If
There is no ..Else.. in the example above either. You just tell the code to perform multiple actions if
the condition is true.
If you want to execute a statement if a condition is true and execute another statement if the condition
is not true, you must add the "Else" keyword:
<html>
<body>
<script type="text/vbscript">
JITENDER SINGH LAMBA
LECT IT GITM
210
Function greeting()
i=hour(time)
If i < 10 Then
document.write("Good morning!")
Else
document.write("Have a nice day!")
End If
End Function
</script>
</head>

<body onload="greeting()">
</body>

</html>
In the example above, the first block of code will be executed if the condition is true, and the other
block will be executed otherwise (if i is greater than 10).

If...Then...ElseIf
You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to
execute:
Example (IE Only)
<html>
<body>
<script type="text/vbscript">
Function greeting()
i=hour(time)
If i = 10 Then
document.write("Just started...!")
ElseIf i = 11 then
document.write("Hungry!")
ElseIf i = 12 then
document.write("Ah, lunch-time!")
ElseIf i = 16 then
document.write("Time to go home!")
Else
document.write("Unknown")
End If
End Function
</script>
</head>

<body onload="greeting()">
</body>

</html>


JITENDER SINGH LAMBA
LECT IT GITM
211
Select Case
You can also use the "Select Case" statement if you want to select one of many blocks of code to
execute:
Example (IE Only)
<html>
<body>
<script type="text/vbscript">
d=weekday(date)
Select Case d
Case 1
document.write("Sleepy Sunday")
Case 2
document.write("Monday again!")
Case 3
document.write("Just Tuesday!")
Case 4
document.write("Wednesday!")
Case 5
document.write("Thursday...")
Case 6
document.write("Finally Friday!")
Case else
document.write("Super Saturday!!!!")
End Select
</script>

</body>
</html>
This is how it works: First we have a single expression (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each Case in the structure. If there is
a match, the block of code associated with that Case is executed.
VBScript Looping
Looping Statements
Looping statements are used to run the same block of code a specified number of times.
In VBScript we have four looping statements:
For...Next statement - runs code a specified number of times
For Each...Next statement - runs code for each item in a collection or each element of an
array
Do...Loop statement - loops while or until a condition is true
While...Wend statement - Do not use it - use the Do...Loop statement instead

For...Next Loop
Use the For...Next statement to run a block of code a specified number of times.
The For statement specifies the counter variable (i), and its start and end values. The Next statement
increases the counter variable (i) by one.
JITENDER SINGH LAMBA
LECT IT GITM
212
Example
<html>
<body>

<script type="text/vbscript">
For i = 0 To 5
document.write("The number is " & i & "<br />")
Next
</script>

</body>
</html>
The Step Keyword
With the Step keyword, you can increase or decrease the counter variable by the value you specify.
In the example below, the counter variable (i) is INCREASED by two, each time the loop repeats.
For i=2 To 10 Step 2
some code
Next
To decrease the counter variable, you must use a negative Step value. You must specify an end value
that is less than the start value.
In the example below, the counter variable (i) is DECREASED by two, each time the loop repeats.
For i=10 To 2 Step -2
some code
Next
Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.
For i=1 To 10
If i=5 Then Exit For
some code
Next

For Each...Next Loop
A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an
array.
JITENDER SINGH LAMBA
LECT IT GITM
213
Example
<html>
<body>

<script type="text/vbscript">
Dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"

For Each x In cars
document.write(x & "<br />")
Next
</script>

</body>
</html>

Do...Loop
If you don't know how many repetitions you want, use a Do...Loop statement.
The Do...Loop statement repeats a block of code while a condition is true, or until a condition becomes
true.
Repeat Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.
Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10.
Repeat Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
some code
Loop Until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...Loop
JITENDER SINGH LAMBA
LECT IT GITM
214
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater
than 10.


Other internet development tools (ASP), JSP, Microsoft .NET

Microsoft DOTNET Technology:-
DOTNET is a platform that provides a standardized set of services.
DOTNET is the Platform for debugging, building, Deploying, Executing Web based,
Windows applications, Web services and Windows services.
It exports a common interface so that its programs can be run on any system that supports
.NET.
DOTNET Framework:- The Framework is the Piece of Software that can be Installed on Computer
System to Support ,Build and Run Dotnet Applications.
Different Versions of DOTNET Framework:-
Dotnet Framework 1.0:-Realesed on 13 feb 2002.
Dotnet Framework 1.1:-Realesed on 3 April 2002.
Dotnet Framework 2.0:-Realesed on 22 Jan 2002.
Dotnet Framework 3.0:-Realesed on 21 Nov 2006.
Dotnet Framework 3.5:-Realesed on 19 Nov 2007.
Dotnet Framework 4.0:-Realesed on 20 May 2009.


Architecture of DOTNET Framework



JITENDER SINGH LAMBA
LECT IT GITM
215
Visual Studio.NET:-The Visual Studio.NET is the Complete Package which contain the Dotnet
Framework Environment, Infrastructure and Resource to execute the API (application Programming
Interface) for DOTNET User.

Language Choice in DOTNET:- The Dotnet Have inbuild Support for three Programming Module
1. C#.Net
2. VB.Net
3. J#.Net
But Dotnet Supports Over 130 Languages. It means Code which is not written in Dotnet framework
can be executed in Dotnet framework if dotnet supports the language in which Code is written.
CLS (Common Language Specification):-
CLS is a set of specifications that all languages and libraries need to follow
This will ensure interoperability between languages
Certain rules which are Common for all the Language under Dotnet Framework
We can not have Language running around with their own extension
CLS is the Collection of Rules and Constraints that every language has to Follow
ASP.NET:- The Use of ASP With Extended features of Dotnet Framework.
ASP.NET provides two types of programming models:
Web Forms: Enable you to create the user interface for a Web application. You use server controls to
design the user interface of a Web application and then write code that will be executed at the server
side, to handle the events triggered by these controls. Asp.net can be used to design web form for
Mobile devices.
WAP (Wide area Protocol) Applications: The Web Applications Developed for Mobile Devices are
also known as Wide area Protocol applications. The main Constraints about WAP are:
WAP is communication Protocol.
WAP is used to Access Services and Information.
WAP is inherited from from Internet Standards.
WAP is for Handled Devices such as Mobile Phone.
WAP is Design for Micro Browsers like Web Browser in Mobile Devices.
WAP Enable the Creating of Web Applications for Mobile Devices.
WAP uses WML (Wireless Markup Language) for Designing Web Applications.
WML uses the XML 1.0 (extensible Markup language) for Designing Web Pages.
Web Services: Enable you to remotely access certain functions at the server side. These services
enable the exchange of data in a client-to-server or a server-to-server environment over the Web by
using the Simple Object Access Protocol (SOAP).Asp.net can be used to create web services for
mobile devices.
Windows forms/ Applications:- Windows Forms is framework for building rich GUI
applications.Three type of Programming Module are Supported by Dotnet to create windows
forms/Applications these are:-
1. C#.net
2. VB.net
3. J#.net
C#/VB/J#.NET provides two types of programming models:

Windows Forms: Enable you to create the user interface for a Window application. You use windows
controls to design the user interface of a Windows application and then write code that will be
executed in Dotnet Envirenment, to handle the events triggered by these controls.

Windows Services: Enable you to access the windows Resources when Installed on the Windows
System.
ADO.NET and XML:- They are the Key components of Data Access layer of Dotnet Framework.
Activex Data Objects (ADO)
Extensible Markup Language (XML)
ADO.Net and XML are used to Create the Database Connection with External Entity or data. The
ADO.Net is used create the Database Connection using following Methods.
JITENDER SINGH LAMBA
LECT IT GITM
216
Sql connection Sql server database Connectivity)
Oracle Connection (OODBC(Oracle ODBC))
MS Access connections (ODBC (open database connectivity) )
JDBC (java database Connectivity)


Base Class Library - The Base Class Library (BCL), part of the Framework Class Library (FCL), is a
library of functionality available to all languages using the .NET Framework. The BCL provides
classes which encapsulate a number of common functions, including file reading and writing, graphic
rendering, database interaction and XML document manipulation. Base Class Library Contains
Object-oriented collection of reusable types
Collections, I/O, Strings,

The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET
initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard,
which defines an execution environment for program code. The CLR runs a form of bytecode called
the Common Intermediate Language (CIL, previously known as MSIL -- Microsoft Standard
Implementation Language).
Developers using the CLR write code in a language such as C# or VB.Net. At compile-time, a .NET
compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler (JIT compiler)
converts the CIL code into code native to the operating system. Alternatively, the CIL code can be
compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software
as the CIL-to-native compilation is no longer necessary.
Although some other implementations of the Common Language Infrastructure run on non-Windows
operating systems, the CLR runs on Microsoft Windows operating systems.
The main Components of CLR are:-
1. CTS
2. Managed Code
3. MSIL
4. JIT



JITENDER SINGH LAMBA
LECT IT GITM
217


MSIL (Microsoft Intermediate Langauge):- It is low-level (machine) language, like Assembler, but
is Object-oriented. .NET languages are compiled to an Intermediate Language (IL).IL is also known as
MSIL or CIL. The MSIL Contain :-
CODE + Metadata (data about data)

Manged Code:- Code that targets the CLR is referred to as managed code
All managed code has the features of the CLR
Object-oriented
Type-safe
Cross-language integration
Cross language exception handling
Multiple version support
Managed code is represented in special Intermediate Language (IL)

CTS (Common Type Specification):- is a rich type system built into the CLR
Implements various types (int, float, string, )
And operations on those types
All .NET languages have the same primitive data types. An int in C# is the same as
an int in VB.NET
When communicating between modules written in any .NET language, the types are
guaranteed to be compatible on the binary level
Types can be:
Value types passed by value, stored in the stack
Reference types passed by reference, stored in the heap
Examples of CTS are:-
Sytem.byte : Occupy 1-byte
Sytem.Int16 : Occupy 2-byte
System.Int32 : Occupy 4-byte
System.Int64 : Occupy 8-byte
System. Single : Occupy 4-byte Floationg Points
System.Double : Occupy 8-byte Floating Points
System.Object : Occupy 4-byte
System.Char : Occupy 2-byte
JITENDER SINGH LAMBA
LECT IT GITM
218
System.String : Occupy 2-billion Unicode Characters
System.Decimal : Occupy 12-btye Signed Integer
System.Boolean : Occupy 4-byte

JIT(Just in time Compiler) :- For Dynamic Compilation of Dotnet Applications.
The virtual machine aspect of the CLR allows programmers to ignore many details of the specific CPU
that will execute the program. The CLR also provides other important services, including the
following:
1. Memory management
2. Thread management
3. Exception handling
4. Garbage collection
5. Security
.
Operating System:- The Dotnet is Compatible with Microsoft windows only. Some Dummy Projects
are deployed on Linux to verify the compatibility of dotnet over Linux . But they are not so successful.

Assemblies
An assembly is the building block of a .NET application. It is a self describing collection of code,
resources, and metadata (data about data, example, name, size, version of a file is metadata about that
file). An Assembly is a complied and versioned collection of code and metadata that forms an atomic
functional unit. Assemblies take the form of a dynamic link library (.dll) file or executable program
file (.exe) but they differ as they contain the information found in a type library and the information
about everything else needed to use an application or component. All .NET programs are constructed
from these Assemblies. Assemblies are made of two parts: manifest, contains information about what
is contained within the assembly and modules, internal files of IL code which are ready to run. When
programming, we don't directly deal with assemblies as the CLR and the .NET framework takes care
of that behind the scenes. The assembly file is visible in the Solution Explorer window of the project

An assembly includes:
1. information for each public class or type used in the assembly information includes class or
type names, the classes from which an individual class is derived, etc
2. information on all public methods in each class, like, the method name and return values (if
any)
3. Information on every public parameter for each method like the parameter's name and type
4. Information on public enumerations including names and values
5. Information on the assembly version (each assembly has a specific version number)
6. Intermediate language code to execute
7. A list of types exposed by the assembly and list of other assemblies required by the assembly
Image of a Assembly file is displayed below
Microsoft .NET Framework was designed with several Features/intentions:
1. Interoperability - Because interaction between new and older applications is commonly
required, the .NET Framework provides means to access functionality that is implemented in
programs that execute outside the .NET environment. Access to COM components is
provided in the System.Runtime.InteropServices and System. Enterprise Services namespaces
of the framework, and access to other functionality is provided using the/Invoke feature.
2. Common Runtime Engine - Programming languages on the .NET Framework compile into
an intermediate language known a the Common Intermediate Language, or CIL (formerly
known as Microsoft Intermediate Language, or MSIL). In Microsoft's implementation, this
intermediate language is not interpreted, but rather compiled in a manner known as just-in-
time compilation (JIT) into native code. The combination of these concepts is called the
Common Language Infrastructure (CLI), a specification; Microsoft's implementation of the
CLI is known as the Common Language Runtime (CLR).
3. Language Independence - The .NET Framework introduces a Common Type System, or
CTS. The CTS specification defines all possible datatypes and programming constructs
supported by the CLR and how they may or may not interact with each other. Because of this
JITENDER SINGH LAMBA
LECT IT GITM
219
feature, the .NET Framework supports development in multiple programming languages. This
is discussed in more detail in Microsoft .NET Languages.
4. Base Class Library - The Base Class Library (BCL), part of the Framework Class Library
(FCL), is a library of functionality available to all languages using the .NET Framework. The
BCL provides classes which encapsulate a number of common functions, including file
reading and writing, graphic rendering, database interaction and XML document
manipulation.
5. Simplified Deployment - Installation of computer software must be carefully managed to
ensure that it does not interfere with previously installed software, and that it conforms to
increasingly stringent security requirements. The NET framework includes design features
and tools that help address these requirements.
6. Security - The design is meant to address some of the vulnerabilities, such as buffer
overflows, that have been exploited by malicious software. Additionally, .NET would provide
a common security model for all applications.
7. Portability - A design goal of the .NET Framework is to remain platform agnostic, and thus
be cross platform compatible. That is, a program written to use the framework should run
without change on any type of system for which the framework is implemented. Microsoft's
commercial implementations of the framework cover Windows.

Dot net vs. Java

1. Language Choice
2. CLR VS JVM
3. Comparing the Structures
4. Security
5. Java or .Net
6. Line of codes
7. O.S Computability
8. Cross Language Integration

1) Language Choice
We can use C#,VB, J# to Build Application in Dotnet Environment.
Dotnet Support over 130 Languages.
We can Develop Application in java using Java Language only.

2) Java (JVM) vs. DOTNET (CLR)
a) JVM designed for platform independence
Single language: Java (?)
A separate JVM for each OS & device
b) CLR designed for language independence
A) Multiple languages for development
C++, VB, C#, (J#)
APL, COBOL, Eiffel, Forth, Fortran, Haskel, SML, Mercury,
Mondrian, Oberon, Pascal, Perl, Python, RPG, Scheme,
SmallScript,
Impressive usage of formal methods and programming language
research during developmentUnderlying OS: Windows (?)


JITENDER SINGH LAMBA
LECT IT GITM
220









4 . Securities
Fair Security Policy is Deployed in .net
Java is more Secure than .net
Strong Code Security Mechanism is followed in Java
Managed Code Security is used in .Net

5. Line of code
The line of code is min in .net platform because of Embedded Controls feature in Dotnet.
Line of Code is max in java since no Embedded Control Feature in Java.
6. O.S Compatibility
Java is Compatible with Most O.S
Like Linux, Mac, Solaris
.net is compatible with MS Windows
JITENDER SINGH LAMBA
LECT IT GITM
221
Like Windows 98,2000,xp,2003,vista
7. Cross language integration
.Net Supports Cross Language Integration.
Java do not support Cross Language Integration.



Active Server Pages (ASP) is Microsoft's server-side script engine for dynamically-generated web
pages. It is marketed as an add-on to Internet Information Services (IIS). Programming ASP websites
is made easier by various built-in objects. Each object corresponds to a group of frequently-used
functionality useful for creating dynamic web pages. In ASP 2.0 there are six such built-in objects:
Application, ASPError, Request, Response, Server, and Session. Session, for example, is a cookie-
based session object that maintains variables from page to page.
Most ASP pages are written in VBScript, but any other Active Scripting engine can be selected instead
by using the @Language directive or the <script language="language" runat="server"> syntax. JScript
(Microsoft's implementation of ECMAScript) is the other language that is usually available. PerlScript
(a derivative of Perl) and others are available as third-party installable Active Scripting engines.

What is ASP?
ASP stands for Active Server Pages
ASP is a program that runs inside IIS
IIS stands for Internet Information Services
IIS comes as a free component with Windows 2000
IIS is also a part of the Windows NT 4.0 Option Pack
The Option Pack can be downloaded from Microsoft
PWS is a smaller - but fully functional - version of IIS
PWS can be found on your Windows 95/98 CD
ASP Compatibility
ASP is a Microsoft Technology
To run IIS you must have Windows NT 4.0 or later
To run PWS you must have Windows 95 or later
ChiliASP is a technology that runs ASP without Windows OS
InstantASP is another technology that runs ASP without Windows
What is an ASP File?
An ASP file is just the same as an HTML file
An ASP file can contain text, HTML, XML, and scripts
Scripts in an ASP file are executed on the server
An ASP file has the file extension ".asp"
How Does ASP Differ from HTML?
When a browser requests an HTML file, the server returns the file
JITENDER SINGH LAMBA
LECT IT GITM
222
When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP
engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP
file is returned to the browser as plain HTML
What can ASP do for you?
Dynamically edit, change or add any content of a Web page
Respond to user queries or data submitted from HTML forms
Access any data or databases and return the results to a browser
Customize a Web page to make it more useful for individual users
The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed
Provide security since your ASP code can not be viewed from the browser
Clever ASP programming can minimize the network traffic
Important: Because the scripts are executed on the server, the browser that displays the ASP file does
not need to support scripting at all!
The Basic Syntax Rule
An ASP file normally contains HTML tags, just like an HTML file. However, an ASP file can also
contain server scripts, surrounded by the delimiters <% and %>. Server scripts are executed on the
server, and can contain any expressions, statements, procedures, or operators valid for the scripting
language you prefer to use.

Write Output to a Browser
The response.write command is used to write output to a browser. The following example sends the
text "Hello World" to the browser:
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
There is also a shorthand method for the response.write command. The following example also sends
the text "Hello World" to the browser:
<html>
<body>
<%="Hello World!"%>
</body>
</html>


VBScript
You can use several scripting languages in ASP. However, the default scripting language is VBScript:
<html>
<body>
<%
response.write("Hello World!")
JITENDER SINGH LAMBA
LECT IT GITM
223
%>
</body>
</html>
The example above writes "Hello World!" into the body of the document.

JavaScript
To set JavaScript as the default scripting language for a particular page you must insert a language
specification at the top of the page:
<%@ language="javascript"%>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>
Note: Unlike VBScript - JavaScript is case sensitive. You will have to write your ASP code with
uppercase letters and lowercase letters when the language requires it.
Displaying the Date
Now let us go one step further, and make a page that tells you the date today!
<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%= Date %>
</BODY>
</HTML>
Using the function Date gives you the current date. And the function, Time returns the time. To
get both, use the function, Now. The following code shows how the Now function is used.
<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%
Response.Write Now
%>
</BODY>
</HTML>
And the output:
7/10/2000 12:35:31 AM
and more
You can also get the individual elements, Year, Date, Month, Hour, Minute & Second of the time by
using the above functions.
<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%
Response.Write Year: & Year (Now)
JITENDER SINGH LAMBA
LECT IT GITM
224
Response.Write Month: & Month (Now)
Response.Write MonthName: & MonthName (Month(Now))
ACTIVE SERVER PAGES 3.0
13
Response.Write Hour: & Hour (Now)
Response.Write Minute: & Minute (Now)
Response.Write Second: & Second (Now)
%>
</BODY>
</HTML>
Notice the mixing of plain text and VBScript code. With this beginning, let us now move on to
handling variables, constants, and various constructs.


Introduction to JSP
JavaServer Pages (JSP) is a technology based on the Java language and enables the development of
dynamic web sites. JSP was developed by Sun Microsystems to allow server side development. JSP
files are HTML files with special Tags containing Java source code that provide the dynamic content.
Why use JSP?
JSP is easy to learn and allows developers to quickly produce web sites and applications in an open
and standard way. JSP is based on Java,an object-oriented language. JSP offers a robust platform for
web development.
Main reasons to use JSP:
Multi platform
Component reuse by using JavaBeans and EJB.
Advantages of Java.
You can take one JSP file and move it to another platform,web server or JSP Servlet engine.
This means you are never locked into one vendor or platform.

JSP compared to ASP
JSP and ASP are fairly similar in the functionality that they provide. JSP may have slightly higher
learning curve. Both allow embedded code in an HTML page,session variables and database access
and manipulation. Whereas ASP is mostly found on Microsoft platforms i.e. NT,JSP can operate on
any platform that conforms to the J2EE specification. JSP allow component reuse by using Javabeans
and EJBs. ASP provides the use of COM / ActiveX controls.
JSP compared to ASP.NET
ASP.NET is based on the Microsoft .NET framework. The .NET framework allows applications to be
developed using different programming languages such as Visual Basic,C# and JavaScript. JSP and
Java still has the advantage that it is supported on many different platforms and the Java community
has many years of experience in designing and developing Enterprise quality scalable applications.
This is not to say that ASP.NET is bad,actually it is quite an improvement over the old ASP code.
JITENDER SINGH LAMBA
LECT IT GITM
225
JSP compared to Servlets
A Servlet is a Java class that provides special server side service. It is hard work to write HTML code
in Servlets. In Servlets you need to have lots of println statements to generate HTML. JSP pages are
converted to Servlets so actually can do the same thing as old Java Servlets.
JSP architecture
JSPs are built on top of SUN Microsystems' servlet technology. JSPs are essential an HTML page
with special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp
rather than .htm or .html. The JSP engine parses the .jsp and creates a Java servlet source file. It then
compiles the source file into a class file,this is done the first time and this why the JSP is probably
slower the first time it is accessed. Any time after this the special compiled servlet is executed and is
therefore returns faster.

Steps required for a JSP request:
1. The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp).
The web browser makes the request via the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognises that the file required is special (.jsp),therefore passes the JSP file
to the JSP Servlet Engine.
4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML required is
converted to println statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated,calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
JITENDER SINGH LAMBA
LECT IT GITM
226
HTML results are displayed on the user's web browser.



A Java Server Page is an HTML page with embedded servlet code, that is surrounded by <% and %>
tags. The servlet code, sometimes called scriptlet, can use four predefined variables:

request - the servlet request, an HTTPServletRequest object
response - the servlet response, an HTTPServletResponse object
out - the output writer, a PrintWriter object
in - the input reader, a BufferedReader object

For example, you could implement a simple Hello World JSP page with the following HTML:

<HTML>
<HEAD><TITLE>Hello World</TITLE></HEAD>
<BODY>
<% out.println("Hello World!"); %>
</BODY>
</HTML>

1. Creating your first JSP page
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%@ page language="java" %>
<% out.println("Hello World"); %>
</body>
</html>
2. Type the code above into a text file. Name the file helloworld.jsp.
3. Place this in the correct directory on your JSP web server and call it via your browser.
Using JSP tags
There are five main tags:
1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag
Declaration tag ( <%! %> )
This tag allows the developer to declare variables or methods.
Before the declaration you must have <%!
JITENDER SINGH LAMBA
LECT IT GITM
227
At the end of the declaration,the developer must have %>
Code placed in this tag must end in a semicolon ( ; ).
Declarations do not generate output so are used with JSP expressions or scriptlets.
For Example,
<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;

%>
Expression tag ( <%= %>)
This tag allows the developer to embed any Java expression and is short for out.println().

A semicolon ( ; ) does not appear at the end of the code inside the tag.
For example,to show the current date and time.
Date : <%= new java.util.Date() %>

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

A JSP directive gives special information about the page to the JSP Engine.
There are three main types of directives:
1) page - processing information for this page.
2) Include - files to be included.
3) Tag library - tag library to be used in this page.

Directives do not produce any visible output when the page is requested but change the way the JSP
Engine processes the page.

For example,you can make session data unavailable to a page by setting a page directive (session) to
false.

1. Page directive

This directive has 11 optional attributes that provide the JSP Engine with special processing
information. The following table lists the 11 different attributes with a brief description:




language

Which language the file uses.

<%@ page language = "java" %>




extends



Superclass used by the JSP engine for the
translated Servlet.



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





import



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



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



JITENDER SINGH LAMBA
LECT IT GITM
228


session



Does the page make use of sessions. By
default all JSP pages have session data
available. There are performance benefits
to switching session to false.






Default is set to true.





buffer



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



<%@ page buffer = "none" %>





autoFlush



Flush output buffer when full.



<%@ page autoFlush = "true" %>





isThreadSafe



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









info



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



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





errorPage



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



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





IsErrorPage



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











contentType



Set the mime type and character set of the
JSP.









2. Include directive
JITENDER SINGH LAMBA
LECT IT GITM
229

Allows a JSP developer to include contents of a file inside another. Typically include files are used for
navigation,tables,headers and footers that are common to multiple pages.

Two examples of using include files:

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

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

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

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

Include files are discussed in more detail in the later sections of this tutorial.

3. Tag Lib directive

A tag lib is a collection of custom tags that can be used by the page.

<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>

Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complex server side code
from web designers.
Scriptlet tag ( <% ... %> )
Between <% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable
or bean declared.
For example,to print a variable.
<%
String username = "visualbuilder" ;
out.println ( username ) ;
%>

Action tag

There are three main roles of action tags :

1) enable the use of server side Javabeans

2) transfer control between pages

3) browser independent support for applets.










JITENDER SINGH LAMBA
LECT IT GITM
230
ASP VS ASP.NET


ASP ASP.NET
Scripting language not compiled Compiled code full language support
Blend of HTML and script on one
page
Code behind page separate VB file
Developer needs to code all server-
side actions
Server-side controls handle most boiler-plate coding
Debugging difficult Debugging runs in the IDE
Only ASP Features ASP features + extended features of .net framework
ASP Do not Support Namespaces ASP.NET support Namespaces Eg: system. web
Database Connectivity is Difficult in
ASP
Database Connectivity is Easily Possible Using ASP in DOTNET
framework
Embedded control are not Possible
in ASP
Embedded Control Are available in ASP.NET LIKE: radio button, text
box
Dynamic Compilation of ASP code
is not Possible
Dynamic Compilation of ASP code is Possible in ASP.Net because of
JIT(just in time Compiler)
Number of Line of Code
Programmer have to write more in
ASP
Number of Line of Code Programmer have to write is Less in ASP.net
ASP Code can be run on any
Operating System Having
Configured IIS
ASP.NET code can be run and Execute only in Framework Environment
It is difficult to develop Web
services in ASP
It is easier to develop Web Services in ASP.net because of Dotnet
framework
ASP do not Support global
variables
ASP.net supports Global variables
Asp do not support web assemblies ASP.net supports web assemblies
JITENDER SINGH LAMBA
LECT IT GITM
231
In asp the Code is interpreted and
executed using Web browser Hosted
by IIS
ASP.net code is first converted in MSIL(Microsoft intermediate
language) during compilation than executable CODE IS CREATED
State Management System is not
Deployed in ASP.NET
State Management System is Deployed in ASP.NET

ASP.NET compared with ASP
ASP.NET attempts to simplify developers' transition from Windows application development to web
development by offering the ability to build pages composed of controls similar to a Windows user
interface. A web control, such as a button or label, functions in very much the same way as its
Windows counterpart: code can assign its properties and respond to its events. Controls know how to
render themselves: whereas Windows controls draw themselves to the screen, web controls produce
segments of HTML and JavaScript which form part of the resulting page sent to the end-user's
browser.
ASP.NET encourages the programmer to develop applications using an event-driven GUI model,
rather than in conventional web-scripting environments like ASP and PHP. The framework attempts to
combine existing technologies such as JavaScript with internal components like "ViewState" to bring
persistent (inter-request) state to the inherently stateless web environment.
Other differences compared to ASP classic are:
Compiled code means applications run faster with more design-time errors trapped at the
development stage.
Significantly improved run-time error handling, making use of exception handling using try-
catch blocks.
Similar metaphors to Microsoft Windows applications such as controls and events.
An extensive set of controls and class libraries allows the rapid building of applications, plus
user-defined controls allow commonly-used web template, such as menus. Layout of these
controls on a page is easier because most of it can be done visually in most editors.
ASP.NET leverages the multi-language capabilities of the .NET Common Language Runtime,
allowing web pages to be coded in VB.NET, C#, J#, Delphi.NET, Chrome etc.
Ability to cache the whole page or just parts of it to improve performance.
Ability to use the code-behind development model to separate business logic from
presentation.
If an ASP.NET application leaks memory, the ASP.NET runtime unloads the AppDomain
hosting the erring application and reloads the application in a new AppDomain.
Session state in ASP.NET can be saved in a Microsoft SQL Server database or in a separate
process running on the same machine as the web server or on a different machine. That way
session values are not lost when the web server is reset or the ASP.NET worker process is
recycled.
Versions of ASP.NET prior to 2.0 were criticized for their lack of standards compliance. The
generated HTML and JavaScript sent to the client browser would not always validate against
W3C/ECMA standards. In addition, the framework's browser detection feature sometimes
incorrectly identified web browsers other than Microsoft's own Internet Explorer as
"downlevel" and returned HTML/JavaScript to these clients with some of the features
removed, or sometimes crippled or broken. However, in version 2.0, all controls generate
valid HTML 4.0, XHTML 1.0 (the default) or XHTML 1.1 output, depending on the site
configuration. Detection of standards-compliant web browsers is more robust and support for
Cascading Style Sheets is more extensive.
Web Server Controls: these are controls introduced by ASP.NET for providing the UI for the
web form. These controls are state managed controls and are WYSIWYG controls
JITENDER SINGH LAMBA
LECT IT GITM
232
COMPARISION ASP & JSP
An Open Approach
The biggest difference between JSP and ASP technologies lies in the approach to the software design
itself. JSP technology is designed to be both platform and server independent, created with input from
a broader community of tool, server, and database vendors. In contrast, ASP is a Microsoft technology
that relies primarily on Microsoft technologies.

Platform and Server Independence
JSP technology adheres to the Write Once, Run Anywhere philosophy of the Java architecture.
Instead of being tied to a single platform or vendor, JSP technology can run on any Web server and is
supported by a wide variety of tools from multiple vendors.
Because ASP uses ActiveX controls for its components, ASP technology is basically restricted to
Microsoft Windows-based platforms. Offered primarily as a feature of Microsoft IIS, ASP technology
does not work easily on a broader range of Web servers because ActiveX objects are platform specific.

Open Development Process, Open Source
Sun developed JSP technology using the Java Community Process. Since 1995, Sun has used this open
process to develop and revise Java technology and specifications in cooperation with the international
Java community. Working with Sun in the JSP effort are authoring tool vendors (such as Macromedia),
container companies (such as Apache and Netscape), end users, consultants, and others.
ASP technology is a specifically Microsoft initiative, developed in a proprietary process.

Object model
Both ASP and JSP technologies let developers separate content generation from layout by accessing
components from the page. ASP supports the COM model, while JSP technology provides components
based on JavaBeans technology or JSP tags.

The Java Advantage
JSP technology uses the Java language for scripting, while ASP pages use Microsoft VBScript or
JScript. The Java language is a mature, powerful, and scalable programming language that provides
many benefits over the Basic-based scripting languages. For example, the Java language provides
superior performance to the interpreted VBScript or JScript languages. Because they use Java
technology and are compiled into Java servlets, The Java language makes the developers job easier in
other ways as well. For example, it helps protect against system crashes, while ASP applications on
Windows NT systems are susceptible to crashing. The Java language also helps in the area of memory
management by providing protection against memory leaks and hard-to-find pointer bugs that can slow
application deployment. Plus, JSP provides
the robust exception handling necessary for real-world applications.

Easier Maintenance
Applications using JSP technology are easier to maintain over time than ASP-based applications.
Scripting languages are fine for small applications, but do not scale well to manage large, complex
applications. Because the Java language is structured, it is easier to build and maintain large, modular
applications with it. JSP technologys emphasis on components over scripting makes it easier to revise
content without affecting logic, or revise logic without changing content. The Enterprise JavaBeans
architecture encapsulates the enterprise logic, such as database access, security, and transaction
integrity, and isolates it from the application itself.
Because JSP technology is an open, cross-platform architecture, Web servers, platforms, and other
components can be easily upgraded or switched without affecting JSP-based applications. This makes
JSP suitable for real-world Web applications, where constant change and growth is the norm.

Scalability in the Enterprise
JITENDER SINGH LAMBA
LECT IT GITM
233
The Java 2 Platform, Enterprise Edition (J2EE) is the Java architecture for developing multitier
enterprise applications. As part of J2EE, JSP pages have access to all J2EE components, including
JavaBeans and Enterprise JavaBeans components and Java servlets. JSP pages are actually compiled
into servlets, so they have all of the benefits of these flexible, server-side Java applications. The J2EE
platform containers manage the complexities of enterprise applications, including transaction
management and resource pooling.
The following table lists some of the pre-established (instantiated, for the purist) objects that are
available in both ASP and JSP.
ASP JSP Definition
Request Request Access to request information. This includes such items as
input/form parameters, HTTP request header information, etc.
Response Response Access to response information and construction. This includes
output MIME type and other HTTP response headers as well as the
output stream itself.
Session Session Access to session information.
Application Application Access to application information.
Response.Write Out Access to the response output stream. JSP provides a convenience
object for direct output to this stream, whereas ASP uses a
Response object method.
Note that JSP is Java, so it is case sensitive. But capitalization doesn't matter in VBScript, so if
you stick to lowercase, there really isn't any difference in the names. These are the main objects
we have to work with when creating dynamic contents in either ASP or JSP.


JITENDER SINGH LAMBA
LECT IT GITM
234
ASP VS J SP
J 2EE ASP Edition Standrad Edition
.jsp .ASP Extension
J ava Beans COM Component Componenet Support
Good Fair Portability
Any ODBC, J DBC Any ODBC Supported Database
Any Web server IIS, Personal Web
server
Web Server Support
Linux, windows,Mac Windows Support only O.S Plateform
J ava VB Script, J ava script Language Used
J SP Software are Free ASP Software are Free COST



What is a Java servlet?
A servlet is a server side program written in Java that resides and executes in an application
server
Servlets are java program that run on Web or application servers, acting as middle layer
between request coming from Web browsers or other HTTP clients and databases or
application on HTTP server.A servlet is an extension to a Web server and is used for
generating dynamic Web content. A servlet gets a request from a client such as a Web
browser, processes the request, and returns the response back to the client. The response
typically contains HTML code or an image that is displayed by the Web browser.
Servlet Request Response Mechanism
If request is for static page
return the page as response
Else
Pass the request to application server

JITENDER SINGH LAMBA
LECT IT GITM
235

HttpServletResponse
Used to send information back to clients.
Methods in HttpServletResponse
getWriter()
getOutputStream()
setContentType()

LIFE CYCLE OF SERVLETS
Servlet
Database
Client
Web Server
Application Server
Request
Response
JITENDER SINGH LAMBA
LECT IT GITM
236



Init () Method-The init method is called on a servlet instance right after it has been
initialized
The method can be overridden in a subclass to provide one-time initialization of the
servlet.
If for some reason this initialization fails, you should throw an UnavailableException.
Without init method servlet will not brought int service.
Called only once
Service () Method-
Called each time when server receives request for servlets.
Service method checks the HTTP request type(GET,POST,PUT,DELETE etc.) and calls
doGet,doPost,doPut,doDelete as appropriate.
You can aso use service directly instead of doGet() and doPost().
Destroy() method
To destroy servlet instance
Client
(Browser)
init()
service()
destroy()
Request
Response
JITENDER SINGH LAMBA
LECT IT GITM
237
To close database connection,halt background threads,write cookies and
perform other cleanup operation.
Task of Servlets
Read the explicit data sent by client.
Read the implicit HTTP request sent by browser.
Generate the Result.
Send the explicit data.
Send the implicit HTTP response data.




What are the benefits of servlets?
1) Servlets are portable. You can develop the servlet on one platform and deploy it on a different
platform.

2) Servlets are simple to write. You have access to the entire family of Java APIs. In addition,
you can use the cookie handling and session tracking classes.

3) Servlets are more efficient than CGI scripts. CGI scripts are typically written in Perl and
whenever a request is made to the CGI script, a Perl interpreter needs to be spawned for each
request. This is very expensive in terms of speed and memory resources. Servlets on the other
hand are loaded once into memory and each request is handled by a separate thread Because a
servlet stays in memory, it can maintain its state and hold onto resources, like database
connections, that may take seconds to establish.

4) Servlets are safer than CGI scripts. CGI scripts written in C++ that mistakenly make
invalid pointer references or divide by zero errors could cause the Web server to crash.
Servlets that make the same errors would cause an exception to be thrown. The servlet engine
would catch the exception and handle it gracefully.

5) Servlets can interact with the server by calling the server to translate file paths, output to
the servers log file, etc. CGI scripts are passed all the information it needs to process a
request and then it is isolated from the server.

6) Servlets are server-independent and do not tie you into a proprietary API like the Netscape
Server API.




JITENDER SINGH LAMBA
LECT IT GITM
238
ADVANTAGES OF SERVLET OVER CGI
Servlets CGI
Handles it by Thread. New process started for each process.
Automatically parsing and decoding. You have to do yourself.
Can communicate directly with web
server.
Requires server based API.
Portable Not portable
Secure Not more secure

What does a simple Hello World-servlet look like?
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{

// set the content type
res.setContentType("text/html");
PrintWriter out = res.getWriter();

// output the HTML that displays "Hello World"
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello World!");
out.println("</BODY>");
out.println("</HTML>");
}
}
Saved with Extension of .Java than Complied and run using JDK
Applets
Small Java program that can be inserted into a Web page and Transmitted over
Internet.
Program that runs in
appletviewer (test utility for applets)
JITENDER SINGH LAMBA
LECT IT GITM
239
Web browser (IE, Communicator)
Applications run in command windows or stand-alone window.

Executes when HTML (Hypertext Markup Language) document containing applet is
opened and downloaded

Merits
Java Applet is Compatible with all Existing operating Systems.
Java Applet is supported by all Web browsers.
Java Applet can be used for Real time Applications.
Java Applet makes web solution more scalable for no of users.
Java Applet runs in Sandbox by Web broswer.
Demerits
To Execute Java Applet We requires Java Plugins.
Java Applet Don't support 64 bit Processor.
Java Applet can't Start Until JVM is not Running on Local System.
Good Interface Design can't Developed easily using Java Applets.

Life Cycle of an Applet
Init: This method is intended for whatever initialization is needed for an applet.

Start: This method is automatically called after init method. It is also called
whenever user returns to the page containing the applet after visiting other pages.
Stop: This method is automatically called whenever the user moves away from the
page containing applets. This method can be used to stop an animation.
Destroy: This method is only called when the browser shuts down normally.



The Applet class
To create an applet, you must import the Applet class
This class is in the java.applet package
The Applet class contains code that works with a browser to create a display window
Capitalization matters!
applet and Applet are different names
Importing the Applet class
Here is the directive that you need:
import java.applet.Applet;
import is a keyword
java.applet is the name of the package
A dot ( . ) separates the package from the class
Applet is the name of the class
There is a semicolon ( ; ) at the end

Create Applet
JITENDER SINGH LAMBA
LECT IT GITM
240
Create Applet
/ / Fi l e: Wel comeAppl et 2. j ava
/ / Di spl ayi ng mul t i pl e st r i ngs i n an appl et .
/ / J ava packages
i mpor t j ava. awt . Gr aphi cs; / / i mpor t cl ass Gr aphi cs
i mpor t j avax. swi ng. J Appl et ; / / i mpor t cl ass J Appl et
publ i c cl ass Wel comeAppl et 2 ext ends J Appl et {
/ / dr aw t ext on appl et s backgr ound
publ i c voi d pai nt ( Gr aphi cs g )
{
/ / cal l super cl ass ver si on of met hod pai nt
super . pai nt ( g ) ;
/ / dr aw t wo St r i ngs at di f f er ent l ocat i ons
g. dr awSt r i ng( " Wel come t o", 25, 25 ) ;
g. dr awSt r i ng( "J ava Pr ogr ammi ng! ", 25, 40 ) ;
} / / end met hod pai nt
} / / end cl ass Wel comeAppl et 2
Saved wi t h Wel comeApl et 2. cl ass
i mpor t allows us to use
predefined classes (allowing
us to use applets and
graphics, in this case).
ext ends allows us to inherit the
capabilities of class J Appl et .
Method pai nt is guaranteed to
be called in all applets. Its first
line must be defined as above.
Applet
<html>
<applet code = "WelcomeApplet2.class" width = "300" height = "60">
</applet>
</html>
Saved with Extension Applet.html


Other Method
JITENDER SINGH LAMBA
LECT IT GITM
241
Other Method
i mpor t j ava. awt . Gr aphi cs; / / i mpor t cl ass Gr aphi cs
i mpor t j avax. swi ng. J Appl et ; / / i mpor t cl ass J Appl et
publ i c cl ass Wel comeAppl et 2 ext ends J Appl et {
/ / dr aw t ext on appl et s backgr ound
publ i c voi d pai nt ( Gr aphi cs g )
{
/ / cal l super cl ass ver si on of met hod pai nt
super . pai nt ( g ) ;
/ / dr aw t wo St r i ngs at di f f er ent l ocat i ons
g. dr awSt r i ng( " Wel come t o", 25, 25 ) ;
g. dr awSt r i ng( "J ava Pr ogr ammi ng! ", 25, 40 ) ;
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello World!");
out.println("</BODY>");
out.println("</HTML>");
}
}
SAVED With Extension .J AVA
What is the Difference b/w Applet and Servlets?

APPLETS:
1)It is a special type of java program which runs on any web browser.
2)Applets resides at server but when client makes a request it completely loaded into a place in the
browser. that place is known as SAND BOX.
3)Applet lives inside the sand box only. it does'nt have any access to any things which exists out side
of the sand box.
4) Applets can't communicate with any other server except where they resides.
5)Applets are useful to develop the static web pages.

SERVLETS:

1) Servlet is a purely server side program
2) Servlets always runs in the server.
3) Servlets can be placed in any web and application servers.
4) Servlets are useful to develop the dynamic web pages.
OR
Applet is client side program and Servlet is Server side.Applets can run under any web server their
execution is dependent on Client as they require JRE Whereas Servlets do not require any thing
specific at client side, as they require java enabled web/application ServerApplet extends the
Functionality of the Browser whereas Servlet Extends the Functionality of the Server.
Applet runs at client side where as servlets run at server side.Unlike applets, however, servlets have no
graphical user interface.
OR
An applet is a Java program that runs within a Web browser on the client machine whereas a servlet
runs on the Web server. An applet can use the user interface classes like AWT or Swing while the
JITENDER SINGH LAMBA
LECT IT GITM
242
servlet does not have a user interface. The servlet behaves like a CGI script; it waits for HTTP requests
from a browser and generates a response that is displayed in the browser.
OR
Applets: Java Applets are the cute little components that run within the confines of a web page.
Unfortunately, their star has faded in the last decade, as newer client/browser side technologies such as
Flash and JavaScripting have provided much of the functionality that was originally delivered by
Applets. Nevertheless, there is still a place for Applets in many enterprise architectures that need
slightly fatter clients on the browser side.

Servlets: An application server must be capable of handling and responding to requests that come in
over the Internet. A Servlet is simply a Java based component that handles web-based requests.

The purpose of a Servlet is to accept and process a web-based request, and subsequently send a
response back to the client. Since the client is likely a person surfing the Internet, the response
delivered to the client usually takes the form of a web page.

Servlets are popular because they are incredibly easy to code. With only a little bit of a Java
background, anyone can code a Servlet and dive head first into the empty pool know as server side
development.
OR
Applet is a part of Core JAVA and Servlet of Advance Java. Applet is client side program and Servlet
is Server side. When Applet runs it take the resources of client whereas Servlet is processed at server.
An Applet's class, jar files can be accessed and downloadable by client but not so in case of servlet.
Applets can run under any web browser their execution is dependent on Client as they require JRE
Whereas Servlets do not require any thing specific at client side, as they require java enabled
web/application Server.



Parameters Applet Servlet
Technology Client side code Server side Code
Web Pages Static Dynamic
GUI Don not support Supports GUI
Reliability Not as reliable as servlet Reliable in nature
Database Connectivity Not supported JDBC
Code Execution Time Take Less time to Execute
Programe Code
Take More time to Execute
Programe Code
Scalability Applet is more scalable Servlet is Less Scalable


What is the difference between servlets and Java Server Pages? Which is preferred?
Answer:
Servlets and Java Server Pages are complementary APIs, both providing a means for generating
dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that
runs within a Web or application server's servlet engine, servicing client requests forwarded to it
through the server. A Java Server Page is a slightly more complicated beast. JSP pages contain a
mixture of HTML, Java scripts (not to be confused with JavaScript), JSP elements, and JSP directives.
The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the
JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.
The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look
and act like programs. A Java Server Page can contain Java program fragments that instantiate and
execute Java classes, but these occur inside an HTML template file and are primarily used to generate
dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The
JITENDER SINGH LAMBA
LECT IT GITM
243
power of JSP is that it is server-based and provides a framework for Web application development.
Rather than choosing between servlets and Java Server Pages, you will find that most non-trivial
applications will want to use a combination of JSP and servlets. In fact, the JSP 1.1 and Servlet 2.2
specifications are based around the concept of the Web application, combining the two APIs into a
unified framework
1]Servlet is a pure java class..whereas jsp is not....
2] We can put HTML Code inside servlets...and jsp.
3]when we use HTML in java code than it is called servlet and when we use Java code is html thsn it is
called jsp.......
By default JSP support MultiThreading, if you know about "isThreadSafe" attribute in page tag, it is by
default "true" .but when you set the value to "false", thenthe service method implements
SingleThreadModel, thus making the JSP to participate in Synchronization

Refer the given below description:

By default, the service method of the JSP page implementation class that services the client request is
multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state
is effectively synchronized. There are a couple of different ways to ensure that the service methods are
thread-safe. The easy approach is to include the JSP page directive:
This causes the JSP page implementation class to implement the SingleThreadModel interface,
resulting in the synchronization of the service method, and having multiple instances of the servlet to
be loaded in memory. The concurrent client requests are then distributed evenly amongst these
instances for processing in a round-robin fashion,

Here we dont have two thread safe in both the servlet and jsp, here the case is when a JSP is converted
to servlet, depending on the Options we use in JSP , the servlet will be generated with those options
only. i,e Here the JSP is nothing but in the form of a servlet,

Servlets-
(1) Bits of HTML embedded in java code.
(2) Suitable for coding business layer of enterprise application.
(3)Created and maintained by Java programmers

JSP-
(1) Bits of java code embedded in HTML.
(2)Suitable for coding presentation layer of enterprise application
(3)Created and maintained by Web designers.
In jsp html pages with javacode embedded inside of them.In servlets java programs with html
embedded inside of them.
In servlet java code can't embedded wih servlet's custome tag.
In jsp java code can embedded with jsp's custome tag
JSP contains more static content and less dynamic content but servlet contains more dynamic and
less static content.

Servlets and Java Server Pages are complementary APIs, both providing a means for generating
dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that
runs within a Web or application server's servlet engine, servicing client requests forwarded to it
through the server. A Java Server Page is a slightly more complicated beast. JSP pages contain a
mixture of HTML, Java scripts (not to be confused with JavaScript), JSP elements, and JSP directives.
The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the
JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.

S-ar putea să vă placă și