Вы находитесь на странице: 1из 25




• The are a number of ways to get data from one computer to
the first was called UNIX-to-UNIX copy

• The next development was the File Transfer Protocol

• Then came HTTP which abstracts content away from files on a
disk to
arbitrary URLs that can be any type of resource

• After HTTP it came HTML that can specify how data should look
through a wide variety of tags, images, links and tables

• The client server technology which is based on request response
mechanism made a big change in file transfer technologies

• Today a web server can do a lot things besides sending a file in
response to a request like running a program and sending the
output of that program to the user

• The world wide web came up with static pages similar to pages
in a
file which had no interaction with the user

• Then came up dynamic pages which has dynamic content that
immediately reacts to the user’s need

• The server generates dynamic content with the help of
programs that
resides inside the server called common gateway interface

A sample CGI program in C

#include <stdio.h>
#include <time.h>
int main(int argc, char **argv) {
time_t now;

printf(“The time is now: %s”, ctime(&now));

Introduction (contd.)

request CGI


• Application servers was introduced to improve the performance of

the server

• The application server runs as a separate process and stays running

between requests

• Application servers are extensible allowing programmers to add new

features as needed

Diagram of an Application Server


1 2

Client Server
4 3

Application Server

1- Browser requests HTML

2- Web server sends request to application server
3 – Application generates HTML
4- Server sends HTML back to browser

• A servlet is a small piece of code that extends a server’s

• A servlet is an object written in Java that is equipped to receive
request and build and send back a response

• Written in java a servlet inherits all of the language’s strength
cross platform so it is possible to develop a servlet under
and deploy it on NT without needing to change or

• If a server supports java it can load a new servlet and there is
need to modify the server

• The servlet architecture is designed to eliminate the need to
the servlet every time a request is made

Servlets and JSP


• The servlet is loaded once as it is needed after that it stays
turning requests into responses as fast as the web server can
send them

• Servlets completely replaced CGI

• The next step was to building a templating system on top of

• A servlet reads a file and figures out what to do based on
special tags
present in the file and does it

• A Boston based company called Art Technology Group (ATG)
up with an idea to translate the special tags directly into Java
and then compile and run the java code

• The revolutionary concept called page compilation was
introduced in
the ATG application server named Dynamo

• Sun was very impressed by the concept of page compilation and
licensed the technology for inclusion in their Java Web Server

• The set of special tags that ATG had defined were somewhat
cumbersome and sun refined these tags to create JSP

• Sun considered JSP as important enough to be included as a
formal part of Java 2 Enterprise Edition

• The flow of information through a JSP is shown in the following

Flow of information through a Java Server Page

Client Server 1. Browser requests HTML
7 2. Server sends request to
6 2 Java Engine
3. If needed the Java Engine
reads the JSP file
Servlet Servlet 5 4. The JSP is turned into a
servlet compiled and loaded
5. The servlet runs and
Servlet HTML generates HTML
6. Java Engine sends HTML to
Java Engine server
7. Server sends HTML back to
4 3

Java Server Pages (JSP)

• In a simple statement Java Server Pages is a combination of
statements and HTML tags
<% if (session.isNew()) %>
<B> Welcome user nice to see you </B>
<% else %>
<U> Glad to welcome you back </U>
JSP comments
• In HTML comments are written like
<!-- This is a program to find the square of a number -- >
• The corresponding JSP comment is
<%-- This is a program to find the square of a number -- %>

A simple JSP
<HEAD><TITLE>Java News Today!</TITLE>



<!-- Begin Header -->

<H1>Welcome To Java News Today</H1>

<P>Your on-line home for up to the minute

Java news</P>
<!-- End Header -->
<TD ALIGN="LEFT" WIDTH="20%" BGCOLOR="#000077">
<!-- Begin Navigation -->
<FONT COLOR="#FF0000">&sect;</FONT>
Home Page<BR>

<FONT COLOR="#FF0000">&sect;</FONT>
Industry news<BR>

<FONT COLOR="#FF0000">&sect;</FONT>
Enterprise Java<BR>

<FONT COLOR="#FF0000">&sect;</FONT>
Standard Edition Java<BR>

<FONT COLOR="#FF0000">&sect;</FONT>
Micro edition &amp; devices<BR>
<FONT COLOR="#FF0000">&sect;</FONT>

<FONT COLOR="#FF0000">&sect;</FONT>
<!-- End Navigation -->

<!-- Content goes here -->


The include directive


• This is a simple jsp which contain only HTML tags

• Let it be a home page of Java News Today

• The page consists of three major sections the header, the
and the main content area

• Different pages have different content but the header and
will be repeated all over the site

• If some new content should be added with the navigation it is
difficult to go back and re-edit all the pages

• The solution is include directive which allows any JSP file to
other JSP or HTML files

• The JSP files come from a designated JSP directory
• The header and navigator are pulled out and placed in a
separate file

The header.jsp part

<%-- Begin Header --%>

<H1>Welcome To Java News Today</H1>

<P>Your on-line home for up to the minute

Java news</P>

<%-- End Header --%>

The navigation.jsp part

<%-- Begin Navigation --%>
<FONT COLOR="#FF0000">&sect;</FONT>
Home Page<BR>
<FONT COLOR="#FF0000">&sect;</FONT>
Industry news<BR>
<FONT COLOR="#FF0000">&sect;</FONT>
Enterprise Java<BR>

<FONT COLOR="#FF0000">&sect;</FONT>
Standard Edition Java<BR>
<FONT COLOR="#FF0000">&sect;</FONT>
Micro edition &amp; devices<BR>
<FONT COLOR="#FF0000">&sect;</FONT>
<FONT COLOR="#FF0000">&sect;</FONT>
<%-- End Navigation --%>

The simple JSP with include directives

<HEAD><TITLE>Java News Today!</TITLE>



<%@include file="global/header.jsp"%>

<TD ALIGN="LEFT" WIDTH="20%" BGCOLOR="#000077">
<%@include file="global/navigation.jsp"%>
<!-- Content goes here -->


• The include directive tag is denoted by <%@include


• The include directive starts with a <%@ and ends with a %>


• The include directive will also point the location where the file to
included is located


• A templating is an HTML page with some spaces where the
spaces are
filled with text plus some way to indicate where this text can

• The advantage of templating is that many pages require the
spaces and all these spaces can be filled from the same place

eg1. <%@include file="global/header.jsp"%> is a type of templating

eg2. special tag for getting date and time from system :- <date/>
eg3. including user’s name : “ Good Morning Mr. Thomas Mathew”

Request Time Expressions

• The JSP Engine turns the .jsp file into a servlet

• The translation happens only once that is the first time the page
requested by a user

• This allows no dynamic content because for a page to be
dynamic it
must be rebuilt each time the page is requested

• Request time is the stage where the servlet is run and produces
• Request time is where true dynamic content really begins
because it
gives the request time output which is the most current one

• An expression is a small piece of Java code that as the name
expresses something


• Expressions are indicated by placing in the special tag


eg. <HTML>
1 + 1 equals <%= 1 + 1 %>
• When the browser access this expression the resulting page will
1 + 1 equals 2
• An expression will be evaluated at the request time and the
result will
be given to the browser for display

The Implicit Objects

• JSP provides a great deal of useful information that the authors
use right away and these are called implicit objects

• Implicit means that there is no need for authors to explicitly
that they will use these objects , they are automatically

• Request is one among the implicit objects
• When a request goes from a user’s browser to a server a lot of
information is also sent including the browser used, the
computer used, the page being requested, the kinds of
information the browser will accept as response etc

eg. <HTML>
Hello user! You are using a computer
called <%= request.getRemoteHost() %>
• Conceptually there is no difference between this example and
previous arithmetic example
• The servlet will send the first part of the HTML and evaluate the
expression request.get RemoteHost() and then send the result
• There are a lot of methods available in the Request Object and
they are

Methods in the Request Object

Method Purpose
getCharacterEncoding() The character set in which this page is
encoded ( eg. ISO )
getProtocol() The protocol used for the request such as
getScheme() The scheme portion of the URL such as
getServerName() The name of the computer on which server
is running
getServerPort() The port server is listening to
getRemoteAddr() The address of the computer the request
came from
getRemoteHost() The name of the computer the request
came from
getAuthType() The type of authorization used for this
request (null value if page not protected)

Methods in the Request Object (contd.)

Method Purpose
getHeader() Any header sent by the browser
getMethod The method used for this request (usually GET
or Post but also HEAD, PUT, DELETE etc)
getPathInfo() The path information

getPathTranslated() The path to the requested file on the server’s

local file system

getQueryString() The query string portion of the URL (ie anything

after a question mark)

getRemoteUser() The name the user logged in as

getRequestURL() The full request URL of the JSP

A simple Calculator Program

<HEAD><TITLE>A simple calculator</TITLE></HEAD>
Enter two numbers and click the 'calculate' button.

<FORM ACTION="calculate.jsp" METHOD="GET">



<INPUT TYPE="SUBMIT" NAME="Calculate" VALUE="Calculate">


<HEAD><TITLE>A simple calculator: results</TITLE></HEAD>
The sum of your two numbers is
<%= Integer.parseInt(request.getParameter("value1")) +
Integer.parseInt(request.getParameter("value2")) %>

• The getParameter() returns a string value

• The Java’ s Integer class has a method called parseInt() that
takes a
string and returns an integer

Using Beans
• JSP can be used to call Java Beans
• JSP provides three basic tags for working with beans
• To find out and use the Bean
• To get a property
• To set one or more properties
• There are many ways to use a bean so the use tag has a
number of
• The most basic form is
<jsp:useBean id=“bean name” class=“bean class” />
• The “bean name” is the name that refers to the bean
• The name should be a valid Java identifier
• The “bean class” is the name of a Java class that defines the
• The trailing slash at the end of the tag signals that there is no

corresponding </jsp:useBean> close tag

• There is another variation of the useBean tag that takes a type
parameter as well as a class
<jsp:useBean id=“name” class=“bean class” type=“another class”>
• This version the bean will be cast into an object whose type is
by type

Getting a Property
• Once the bean has been obtained with jsp:useBean getting a
property is as simple as using the getProperty tag which is
<jsp:getProperty name=“bean name” property=“propertyname”/>

• The “property name” is the name of the property to get

• The following is an example which uses the get property

<jsp:useBean id="bean1" class="com.Bean1"/>



<P>Here is some data that came from bean1:</P>


<LI>The name of this bean is:

<jsp:getProperty name="bean1" property="name"/>

<LI>The 7th prime number is:

<jsp:getProperty name="bean1" property="seventhPrimeNumber"/>

<LI>The current time is:

<jsp:getProperty name="bean1" property="currentTime"/>




<TD BGCOLOR="<jsp:getProperty name="bean1"


<P>The information from a bean can be used

anywhere on the page!</P>


• It is not necessary for the useBean tag to appear right at the top
the page but should appear before any getProperty tags

• Once the bean has been loaded the getProperty tags get various
properties from it

• The getProperty tag can be converted into an expression tag that
the bean’s GET method directly

• The tag
<jsp:getProperty name="bean1" property="seventhPrimeNumber"/>

could be rewritten as
<%= bean1.getSeventhPrimeNumber()%>

Setting Properties
• Setting a property looks like
<jsp:setProperty name="bean name " property=“property name”
value=“property value">

• The “property name” is the name of the property to set and
value is
the new value to assign to the property

• The following is a JSP program that is used to set the date and
in different formats

• The format property is set numerous times and each value of

property will be in effect until the next change

<jsp:useBean id="date" class="com.DateBean"/>




<P>Here is the current date, in a few different formats</P>


<jsp:setProperty name="date" property="format"

value="EEEE, MMMM dd yyyy 'at' hh:mm"/>

<LI><jsp:getProperty name="date" property="currentTime"/>

<jsp:setProperty name="date" property="format"

value="hh:mm:ss MM/dd/yy"/>
<LI><jsp:getProperty name="date" property="currentTime"/>

<jsp:setProperty name="date" property="format"

value="yyyyy.MMMMM.dd GGG hh:mm aaa"/>

<LI><jsp:getProperty name="date" property="currentTime"/>



The Connection between Forms and Properties

• The dynamic pages are driven at least partially by values that
provide through forms

• Most program logic resides in beans and many JSPs take input
values from forms, pass these values into beans via
setProperty tags and then display other properties
representing the result of some computation

• Form values could be passed to beans by a combination of

techniques such as

<jsp:setProperty name=“id" property=“someproperty”

value=<%= request.getParameter(“formparam“) %>”>

• If the form is providing a value called formparam and if the bean
a property that is also called formparam the code can be
replaced by the single tag
<jsp:setProperty name=“id" property=“formparam”/>

• If the name of the form parameter and the name of the
property are
different then they can be connected through another variation
of the setProperty tag as
<jsp:setProperty name=“id" property=“propertyname”

• The JSP uses form parameter called paramname to set the

called propertyname

• There is another version of setProperty tag which is very
<jsp:setProperty name=“id" property=“*”>
• This looks through all the parameters provided by the form and
the methods provided by the bean and links them together

• If the form provides values called param1, param2, and so on
and the
bean has methods called setParam1(), setParam2() and so on
everything matches perfectly

• If the form provides some parameters for which there are no

these will be ignored and no error will occur

• If the bean provides methods for which the form does not
values these methods simply are not called

• The following is the calculator program using beans

• The code that had to deal with the inputs is hidden inside the
along with the computation

The Calculator program using Beans

<jsp:useBean id="calc" class="com.CalcBean"/>

<jsp:setProperty name="calc" property="*"/>

<HEAD><TITLE>A simple calculator: results</TITLE></HEAD>

The sum of your two numbers is
<jsp:getProperty name="calc" property="sum"/>


Bean Instances and Serialization

• Most Java objects live only in memory as long as the Java Virtual
Machine that created them lives

• Through a process called serialization most bean instances can
saved into files and read back later

• Serialization eliminates all the saving complexity by providing
methods that will save any object to a file no matter how
complex the object is or how many other objects it contains

• Every class that is to be serialized must implement the
java.io.Serializable interface

• There is a slight variation in the way the useBean tag gets a

<jsp:useBean id=“name” beanName=“bean name” type=“bean


• Here id is the name by which the JSP will use the bean

• beanName should be the name of a file containing a serialized


• The files end with .ser extension but the extension will not be

included in the name

• type is the class or interface for which the bean is an instance

• The following is a JSP that uses a serialized bean to get


about a record in this case “BAD” by Michael Jackson

An example of a Serialized Bean

<jsp:useBean id="album" beanName=“BAD"


BGCOLOR="<jsp:getProperty name="album" property="bgColor"/>"
TEXT="<jsp:getProperty name="album" property="textColor"/>">

<H1><jsp:getProperty name="album" property="name"/></H1>

<P>Artist: <jsp:getProperty name="album" property="artist"/></P>
<P>Year: <jsp:getProperty name="album" property="year"/></P>

Serialized Bean example explanation

• The properties of the bean is stored in the serialized file
• The background and the text color comes from the bean and is
useful technique when creating online catalog
• The serialization makes bean to behave like a database

• The “BAD” bean came as part of collection of beans for all of the
Michael Jackson albums
• To create pages for others it would only be necessary to change
beanName to “Thriller” or “Dangerous”.

Declarations and Explicit Objects

• Similar to Implicit objects there are Explicit objects those that a
creates before using

• The tag that creates new objects is called a declaration and it
specifies the name and type of the object it is creating as well
as an initial value for it
eg. <%! int myInteger = 8; %>

• This declares that the JSP will use a new integer called
and this integer will start life with a value of 8
• The explicit object is also called a variable because its value can

• The semicolon is necessary to signal the end of a Java statement

including declarations

• The declaration which defines two integers is also valid
<%! int myInteger = 8, anotherInteger = 12; %>
• Once a variable has been declared it can be used just like an
object in expressions

• It is not necessary to give a variable an initial value
• Java sets all integer variables to 0 if they do not have initial
• Following is a JSP which declares a number of variables and used

A JSP which declares a number of variables

<HEAD><TITLE>Some declared variables</TITLE></HEAD>
<%! int anInteger = 5; %>
<%! int anotherInt = 7; %>
<%! double pi = 3.1415926; %>
<P>The value of anInteger is now <%= anInteger %>.</P>
<P>The value of anotherInt is now <%= anotherInt %>.</P>
<P>The value of pi is now <%= pi %>.</P>
<P>The value of anInteger + 1 is <%= anInteger + 1 %>.</P>
<P>The area of a circle with a radius of 2 inches is

<%= pi * 2 * 2 %> inches.</P>

<%! java.util.Date now = new java.util.Date(); %>

<P>Today's date is <%= now.getDate() %>

• A scriptlet is a piece of Java code that is sandwiched between the
characters <% and %>

• Any Java code can be placed within the tag and it will run each
the page is accessed
eg. <%
for (int i=100; i>=1; i--)
out.println(“ characters are there in the drama<br>”);
• The code in a single sciptlet does not need to be self contained

Three important elements of JSP code

The elements Declaration Scriplet Expression
Enclosed in <%! %> <% %> <%= %>
Contains One or more Java code One Java
Java (fragments or expression
declarations complete
What it does Creates a name Tells the Has a value
possibly gives system to do
the name a something
When the JSP When the page Whenever Whenever
container runs is first visited someone visits someone visits
it or the JSP the page the page
reinitializes the

• A counter shows how many times a page has been accessed
• Counters are in use all over the Web

<%! int count =0; %>

<% count = count + 1; %>
<P>This page has been accessed <%= count %> times.</P>

• The scriplet increments the counters value by 1

• The next time someone access the page the count will be

by one

• When the server shuts down the counter value is stored in a file
• Java has a mechanism that can be used in JSP called the if
which can do one of two things based on some condition

<%! int count =0; %>

<% count = count + 1; %>
<P>This page has been accessed <%= count %> times.</P>
if (count == 1) {
out.print("<P>Welcome, first visitor!</P>");
• The if statement can be extended using an else part which can
one thing if a condition is satisfied and another thing if the
condition is not satisfied

<%! int count =0; %>


<% count = count + 1; %>

<% if (count == 1) { %>
<P>Welcome, first visitor!</P>
<% } else { %>
<P>You are not the first visitor. <%= count-1 %> other
visitors have already been here,</P>
<% }%>
• Nesting of conditions can also be used in JSP
<% String browser = request.getHeader(“User-Agent”); %>
<%if (browser.indexOf(4.”) != -1) { %>
<P>You have a recent browser, enjoy the site!</P>
<% } else { %>
<% if (browser.index.of(“MSIE”) != -1) { %>
<P>You do not have a recent enough version of IE to
use all the features of this site. You can download one here..</P>
<% } else if (browser.index.of(“Mozilla”) != -1) { %>
<P>You do not have a recent enough version of Netscape
Navigator to use all the features of this site. You can download
one here..</P>
<% } %>
<% } %>

• The for loop is the most commonly used loop
• A for loop has a counter that starts at some value and repeats
action until that counter reaches another value
• Each time it performs the action it can also add or subtract
quantity from the counter
<%! String confs[ ];%>
<% for (int i=0; i<confs.length; i++) { %>
<LI><%=confs[i] %>
<% } %>

• A while loop can be used when some condition continues to be


<% java.util.Enumeration e = request.getHeaderNames(); %>
<P>Here are the names of the headers that have been sent:</P>

<% while (e.hasMoreElements()) { %>
<LI> <%= e.nextElement() %>
<% } %>

• No matter how carefully constructed a JSP is there will almost
be some kind of user input that the author did not expect
will cause the JSP to break and generate an error
eg. In the calculator if the user puts a non numeric value the calculator
will be unable to handle it
• Java provides a control structure called try/catch block
• The try/catch structure will try to do something and if an error
happens Java will catch it and proceed instead of giving up
• Here the errors are called exceptions and the process is called
exception handling
• There is a wide variety of exceptions each of which is related to a
particular kind of error
• The error that occurs when a string cannot be converted to an
is called NumberFormatException
• The following program shows how the calculator JSP could be
modified to catch a NumberFormatCondition
• Rather than printing the result immediately the JSP first saves
result to a temporary variable
• The result is saved to a temporary variable because everything
a try block is executed up to the statement that causes the
<HEAD><TITLE>A simple calculator: results</TITLE></HEAD>
<% try { %>
<% int result =
Integer.parseInt(request.getParameter("value1")) +
Integer.parseInt(request.getParameter("value2")); %>

<P>The sum of your two numbers is <%= result %></P>

<% } catch (NumberFormatException nfe) { %>
Sorry, I was unable to compute the result, because one of the
values provided was not an integer.
<% } %>


• Beans and scriptlets complement each other quite nicely
• The scriptlet code typically can be removed entirely from a page
placed in a bean
• This will leave only the code that the page needs in order to
react to
different input or loop over a set of data obtained from the
• The following is another version of calculator which uses a bean
• The JSP properly handles the non-numeric input
• The scriptlet uses isValid() method in the bean to determine if
input is valid, if not the bean makes another property called
reason available which contains a description of the problem
<jsp:useBean id="calc" class="com.CalcBean"/>
<jsp:setProperty name="calc" property="*"/>
<HEAD><TITLE>A simple calculator: results</TITLE></HEAD>
<% if (calc.isValid()) { %>
The sum of your two numbers is
<jsp:getProperty name="calc" property="sum"/>
<% } else { %>
Sorry, I could not compute the sum becuase
<jsp:getProperty name="calc" property="reason"/>
<% } %>