Jsp
Transcript of Jsp
JSP [JAVA SERVER PAGES]
Introduction••• The are a number of ways to get data from one computer to
another 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 (CGI)
A sample CGI program in C
#include <stdio.h>#include <time.h>int main(int argc, char **argv) {time_t now;printf(“<HTML>\n”);printf(“<BODY>\n”);
1
time(&now);printf(“The time is now: %s”, ctime(&now));printf(“</BODY>\n”);printf(“</HTML>\n”);exit(0);};
Introduction (contd.)
• 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
CGIrequest
ClientServer
response
CGI CGI
CGI CGI
1 2
34Client Server
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
Diagram of an Application Server
2
Servlets • A servlet is a small piece of code that extends a server’s
functionality •• A servlet is an object written in Java that is equipped to receive
a request and build and send back a response •• Written in java a servlet inherits all of the language’s strength
like cross platform so it is possible to develop a servlet under linux and deploy it on NT without needing to change or recompiling•• If a server supports java it can load a new servlet and there is no
need to modify the server•• The servlet architecture is designed to eliminate the need to
reload the servlet every time a request is made
Servlets and JSP•• The servlet is loaded once as it is needed after that it stays
active 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
servlet•• 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)
came 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
3
•• Sun was very impressed by the concept of page compilation and
they 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
figure
Servlet
Client Server
Java Engine
Flow of information through a Java Server Page
Servlet
Servlet HTML
1
2
34
5
6
7
1. Browser requests HTML
2. Server sends request to Java Engine
3. If needed the Java Engine reads the JSP file
4. The JSP is turned into a servlet compiled and loaded
5. The servlet runs and generates HTML
6. Java Engine sends HTML to server
7. Server sends HTML back to browser
Java Server Pages (JSP)• In a simple statement Java Server Pages is a combination of Java
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
4
<HTML><HEAD><TITLE>Java News Today!</TITLE>
<BODY BGCOLOR="#FFFFFF">
<TABLE BORDER="0" WIDTH="100%">
<TR> <TD BGCOLOR="#0000FF" ALIGN="CENTER" COLSPAN="2"> <!-- 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> </TR><TR> <TD ALIGN="LEFT" WIDTH="20%" BGCOLOR="#000077"> <!-- Begin Navigation --> <FONT COLOR="FFFFFF"> <FONT COLOR="#FF0000">§</FONT> Home Page<BR>
<FONT COLOR="#FF0000">§</FONT> Industry news<BR>
<FONT COLOR="#FF0000">§</FONT> Enterprise Java<BR>
<FONT COLOR="#FF0000">§</FONT> Standard Edition Java<BR>
<FONT COLOR="#FF0000">§</FONT> Micro edition & devices<BR><FONT COLOR="#FF0000">§</FONT> Beans<BR>
<FONT COLOR="#FF0000">§</FONT> Editorials<BR> </FONT> <!-- End Navigation --> </TD>
<TD> <!-- Content goes here -->
5
</TD>
</TR> </TABLE></BODY></HTML>
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
navigation, and the main content area•• Different pages have different content but the header and
navigation will be repeated all over the site•• If some new content should be added with the navigation it is
very difficult to go back and re-edit all the pages•• The solution is include directive which allows any JSP file to
include 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 minuteJava news</P>
<%-- End Header --%>
The navigation.jsp part<%-- Begin Navigation --%><FONT COLOR="FFFFFF">
6
<FONT COLOR="#FF0000">§</FONT>Home Page<BR><FONT COLOR="#FF0000">§</FONT>Industry news<BR><FONT COLOR="#FF0000">§</FONT>Enterprise Java<BR><FONT COLOR="#FF0000">§</FONT>Standard Edition Java<BR><FONT COLOR="#FF0000">§</FONT>Micro edition & devices<BR><FONT COLOR="#FF0000">§</FONT>Beans<BR><FONT COLOR="#FF0000">§</FONT>Editorials<BR></FONT><%-- End Navigation --%>
The simple JSP with include directives <HTML><HEAD><TITLE>Java News Today!</TITLE>
<BODY BGCOLOR="#FFFFFF">
<TABLE BORDER="0" WIDTH="100%">
<TR> <TD BGCOLOR="#0000FF" ALIGN="CENTER" COLSPAN="2"> <%@include file="global/header.jsp"%> </TD> </TR>
<TR> <TD ALIGN="LEFT" WIDTH="20%" BGCOLOR="#000077"> <%@include file="global/navigation.jsp"%> </TD><TD> <!-- Content goes here --> </TD>
</TR></TABLE></BODY></HTML>
• The include directive tag is denoted by <%@include file=“---"%>
7
•• The include directive starts with a <%@ and ends with a %>•• The include directive will also point the location where the file to
be included is located
Templating •• 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 be found•• The advantage of templating is that many pages require the
same spaces and all these spaces can be filled from the same place
eg1. <%@include file="global/header.jsp"%> is a type of templatingeg2. 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
is 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
output • Request time is where true dynamic content really begins
because it gives the request time output which is the most current one
Expressions • An expression is a small piece of Java code that as the name
implies expresses something •
8
• Expressions are indicated by placing in the special tag <%=------%>
eg. <HTML> <BODY> 1 + 1 equals <%= 1 + 1 %> </BODY> </HTML>• When the browser access this expression the resulting page will
be 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
can use right away and these are called implicit objects •• Implicit means that there is no need for authors to explicitly
declare that they will use these objects , they are automatically available •• 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> <BODY> Hello user! You are using a computer called <%= request.getRemoteHost() %> </BODY> </HTML>• Conceptually there is no difference between this example and
the 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
9
The type of authorization used for this request (null value if page not protected)
getAuthType()
The name of the computer the request came from
getRemoteHost()
The address of the computer the request came from
getRemoteAddr()
The port server is listening togetServerPort()
The name of the computer on which server is running
getServerName()
The scheme portion of the URL such as HTTP
getScheme()
The protocol used for the request such as HTTP/1.0
getProtocol()
The character set in which this page is encoded ( eg. ISO )
getCharacterEncoding()
PurposeMethod
Methods in the Request Object
PurposeMethod
The full request URL of the JSPgetRequestURL()
The name the user logged in asgetRemoteUser()
The query string portion of the URL (ie anything after a question mark)
getQueryString()
The path to the requested file on the server’s local file system
getPathTranslated()
The path informationgetPathInfo()
The method used for this request (usually GET or Post but also HEAD, PUT, DELETE etc)
getMethod
Any header sent by the browsergetHeader()
Methods in the Request Object (contd.)
A simple Calculator Program <HTML><HEAD><TITLE>A simple calculator</TITLE></HEAD><BODY><P> Enter two numbers and click the 'calculate' button.</P>
10
<FORM ACTION="calculate.jsp" METHOD="GET">
<INPUT TYPE="TEXT" NAME="value1"><BR><INPUT TYPE="TEXT" NAME="value2"><BR>
<INPUT TYPE="SUBMIT" NAME="Calculate" VALUE="Calculate"></FORM></BODY></HTML>
calculate.jsp<HTML><HEAD><TITLE>A simple calculator: results</TITLE></HEAD><BODY><P>The sum of your two numbers is <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %></P></BODY></HTML>
• 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 variations • 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
bean • 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
11
<jsp:useBean id=“name” class=“bean class” type=“another class”> • This version the bean will be cast into an object whose type is
given 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"/>
<HTML>
<HEAD><TITLE>Beans!</TITLE></HEAD>
<BODY BGCOLOR="#FFFFFF"><P>Here is some data that came from bean1:</P>
<UL>
<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"/>
</UL>
<CENTER>
<TABLE BORDER="0"><TR><TD BGCOLOR="<jsp:getProperty name="bean1" property="color"/>">
<P>The information from a bean can be usedanywhere on the page!</P>
12
</TD></TR></TABLE></BODY></HTML>
• It is not necessary for the useBean tag to appear right at the top of
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
calls 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
time in different formats•• The format property is set numerous times and each value of
the property will be in effect until the next change <jsp:useBean id="date" class="com.DateBean"/>
<HTML>
<HEAD><TITLE>The Date Bean</TITLE></HEAD>
<BODY BGCOLOR="#FFFFFF">
13
<P>Here is the current date, in a few different formats</P>
<UL>
<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"/>
</UL>
</BODY></HTML>
The Connection between Forms and Properties • The dynamic pages are driven at least partially by values that
users 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
has a property that is also called formparam the code can be replaced by the single tag <jsp:setProperty name=“id" property=“formparam”/>
14
•• 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” param=“paramname”/>
• The JSP uses form parameter called paramname to set the property
called propertyname•• There is another version of setProperty tag which is very
powerful <jsp:setProperty name=“id" property=“*”>• This looks through all the parameters provided by the form and
all the methods provided by the bean and links them together automatically•• 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 methods
these will be ignored and no error will occur •• If the bean provides methods for which the form does not supply
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
bean along with the computation
The Calculator program using Beans
<jsp:useBean id="calc" class="com.CalcBean"/>
<jsp:setProperty name="calc" property="*"/>
<HTML><HEAD><TITLE>A simple calculator: results</TITLE></HEAD><BODY>
15
<P>The sum of your two numbers is <jsp:getProperty name="calc" property="sum"/></P>
</BODY></HTML>
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
be 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
serialized bean
<jsp:useBean id=“name” beanName=“bean name” type=“bean class”>
• Here id is the name by which the JSP will use the bean
• beanName should be the name of a file containing a serialized bean
• 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 information
16
about a record in this case “BAD” by Michael Jackson
An example of a Serialized Bean
<jsp:useBean id="album" beanName=“BAD" type="com.AlbumInfo"/>
<HTML><BODY 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></UL></BODY></HTML>
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 a
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
JSP 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 myInteger
and this integer will start life with a value of 8 • The explicit object is also called a variable because its value can
change
17
• 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
implicit 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
values • Following is a JSP which declares a number of variables and used
A JSP which declares a number of variables
<HTML><HEAD><TITLE>Some declared variables</TITLE></HEAD><BODY><%! 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() %></P></BODY></HTML>Scriptlets•• 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
time the page is accessed eg. <% for (int i=100; i>=1; i--) { out.print(i)
18
out.println(“ characters are there in the drama<br>”); } %>• The code in a single sciptlet does not need to be self contained
Whenever someone visits the page
Whenever someone visits the page
When the page is first visited or the JSP container reinitializes the page
When the JSP container runs it
Has a valueTells the system to do something
Creates a name possibly gives the name a value
What it does
One Java expression
Java code (fragments or complete statements)
One or more Java declarations
Contains
<%= %><% %><%! %>Enclosed in
ExpressionScripletDeclarationThe elements
Three important elements of JSP code
COUNTER• A counter shows how many times a page has been accessed • Counters are in use all over the Web
<%! int count =0; %><HTML><HEAD><TITLE>A Counter</TITLE></HEAD><BODY><% count = count + 1; %><P>This page has been accessed <%= count %> times.</P></BODY></HTML>
• The scriplet increments the counters value by 1 • The next time someone access the page the count will be
incremented by one
• When the server shuts down the counter value is stored in a file CONDITIONALS• Java has a mechanism that can be used in JSP called the if
statement
19
which can do one of two things based on some condition <%! int count =0; %><HTML><HEAD><TITLE>A Counter</TITLE></HEAD><BODY><% count = count + 1; %><P>This page has been accessed <%= count %> times.</P><%if (count == 1) { out.print("<P>Welcome, first visitor!</P>"); }%></BODY></HTML>• The if statement can be extended using an else part which can
do one thing if a condition is satisfied and another thing if the condition is not satisfied
<%! int count =0; %><HTML><HEAD><TITLE>A Counter</TITLE></HEAD><BODY><% 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><% }%></BODY></HTML>• 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> <% } %>
20
<% } %>
LOOP• The for loop is the most commonly used loop• A for loop has a counter that starts at some value and repeats
some action until that counter reaches another value • Each time it performs the action it can also add or subtract
some 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 true
<HTML><BODY><% java.util.Enumeration e = request.getHeaderNames(); %><P>Here are the names of the headers that have been sent:</P><UL><% while (e.hasMoreElements()) { %><LI> <%= e.nextElement() %><% } %></UL></BODY></HTML
TRY N CATCH• No matter how carefully constructed a JSP is there will almost
always be some kind of user input that the author did not expect which 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
integer
21
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
the result to a temporary variable • The result is saved to a temporary variable because everything
inside a try block is executed up to the statement that causes the errorEG;<HTML><HEAD><TITLE>A simple calculator: results</TITLE></HEAD><BODY><P><% 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) { %><P>Sorry, I was unable to compute the result, because one of the values provided was not an integer.</P><% } %></BODY></HTML>
BEANS AND SCRIPLETS• Beans and scriptlets complement each other quite nicely • The scriptlet code typically can be removed entirely from a page
and 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 bean • 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
the input is valid, if not the bean makes another property called reason available which contains a description of the problem EG:<jsp:useBean id="calc" class="com.CalcBean"/>
22
<jsp:setProperty name="calc" property="*"/><HTML><HEAD><TITLE>A simple calculator: results</TITLE></HEAD><BODY><% if (calc.isValid()) { %><P>The sum of your two numbers is <jsp:getProperty name="calc" property="sum"/></P><% } else { %><P>Sorry, I could not compute the sum becuase<jsp:getProperty name="calc" property="reason"/></P><% } %></BODY></HTML>
23