Laboratory Five

braintreesmileSoftware and s/w Development

Aug 15, 2012 (5 years and 2 days ago)

394 views

Intranet Sys
te
ms Development: Laboratory Eight

Introduction to JSP

In this lab w
e will

use NetBeans to set up a
number of
Java Server Page (JSP)

examples
.

NetBeans provides an instance of the Tomcat web container so that it is
possible to test develop JSP/
servlet
-
based web applications using a local browser and
calls to Tomcat through lo
calhost (IP address 127.0.0.1).

First, we need to set up a web application in NetBeans.
Follow the steps given in
Lecture O, slides 9
-
14, to create a Web Application, Lab8
.

1)

Again, following the steps in Lecture O, slides 15
-
18, c
reate a new JSP called
clock.jsp

in
the Lab8 project
. Delete the default content that NetBeans supplies and
replace it by the contents of
clock.jsp

from
the Lab8 Resources File
. Now
Build the
projec
t
. This initiates two actions. First, the JSP is converted into a Java source file
that extends the
servlet

class then that source is compiled to create a
servlet

that will
accept an http request and return a web page containing the date and time.
Now star
t
up the bundled Tomcat (Lecture O, slide 19) and run the project. Browse to the JSP
(Lecture O, slide 20).

There are one or two things to note here. First, the server address is
localhost

so IE is
sending an http request to the Tomcat web
-
container runnin
g on your machine and
started up by NetBeans. In my example,
808
4

is the port on which Tomcat is listening
for requests. Tomcat then passes the request on to the
servlet

created from
clock.jsp

and it creates the response; an XHTML page.

View the source of

this page in IE and note that a text string representing the date and
time at which you ran the
clock.jsp

has been inserted as a text string. The browser has
no knowledge of how the page has been generated.

Note also that the page refreshes every 60 sec
onds. This is nothing to do with JSP. It
is achieved by the
<meta http
-
equiv = "refresh" content = "60" />

instruction
contained at the top of the page, which is simply functionality offered by IE6..
However it does serve to illustrate one point about JSP.

When you first run the JSP, it
takes a little while to load up. However subsequent refreshes are significantly faster.
This is because, on the first call to the page, the
servlet

is initiated and installed in
memory. On subsequent calls, the
servlet

is al
ready running and so there is no delay
before the request is processed.

The
remaining
examples in this laboratory are all taken from Chapter 10 Advanced
Java 2 Platform: How to Program
[by Deitel, Deitel and Santry, published in 2002 by
Prentice Hall, ISBN
: 0
-
13
-
089560
-
1]
*
. There is no coding involved. Al
l you need to
do is to add

the examples
to your Web App
and read through the code accompanied
by this commentary.

First,
c
reate a subdirectory
of src
called “Images” and move
logotiny
.png

into i
t.

2)

The first

example implements a simple request and response structure, recalling
the sort of simple CGI examples you will have implemented in other modules. The
JSP contains scripting elements that read a parameter submitted as part of the http
request and then use
that to decide how to construct the response. The
difference

here
is that the scripting


楳ie浢敤摥搠楮獩摥 瑡g猠瑨慴tf潲洠灡牴r潦o瑨攠re獰潮獥s灡来⸠奯甠
are more familiar with embedding the response output inside “print” statements in
your server
-
side scr
ipts.

In NetBeans, open
welcome.jsp
. You will notice that NetBeans highlights JSP
scripting elements within the page in an orange background. The first of these is:

String name = request.getParameter( "firstName" );


The reference “request” refers to the H
ttp
Servlet
Request object that will be
automatically created when the http request for
welcome
.jsp

arrives

at the server.
Such an object has a
getParameter (String paramName)

method that returns the
value of the named parameter. This is the same functionali
ty as the Perl CGI.pm
module
param

function provides. The parameters
you can get with this method
are all
the data sent with the http request, for example from HTML form elements
. If there is
no such parameter sent with the request,
getParameter

will retur
n the
null

reference.

This leads us nicely onto the next scripting element, which begins with an
if

clause
that fires when there is a “firstName” String to work with. the scriptlet breaks off to
provide the HTML for a welcome message. The “firstName” param
eter is inserted in
the text of the HTML using an expression element:

<%= name %>

Note here that the content of the scriptlet is an
expression

and not a
statement
. You
need an expression that returns a String in this type of element, which will simply be
r
eplaced by the value of the String in the eventual HTML output by the JSP.

The final part of the JSP is the
else

clause that handles the situation where no
“firstName” parameter has been supplied. This is a situation with which you are
already familiar fro
m CGI programming. The same “script” produces both the output
and input pages for the particular request. In this case we output a form that provides
a text field into which the firstName should be typed. Note in particular the key pieces
of information th
at are passed between client and server. The
action

attribute of the
form is “welcome.jsp”, i.e. the page points at itself. When the submit button is clicked
the web browser will send an http request to the same URL that it got the form from
and so will re
-
run the same JSP. Note also that the HTML text field is called
“firstName”. If I type in “John” to this field and hit “Submit”, the browser will send
an http request with request line:

GET localhost:8080/.../welcome.jsp?firstName=John http/1.1

to Tomcat,

which will create an Http
Servlet
Request object, containing the parameter
firstName=John, and pass it to the
servlet

defined by
welcome.jsp
.

If you haven’t already done so, highlight
welcome.jsp

in the NetBeans explorer
window and run it by clicking the ru
n arrow on the NetBeans toolbar. When IE6 pops
up with the form, type in your name and hit Submit. Your response will resemble the
following:


Note the URL in the address bar, showing how the GET request sent the data to the
JSP

⸠佦 c潵牳oI
getParameter

will just as happily pull form parameters out of a
POST request and you should in fact normally use POST to submit HTML form
information to a web server.

3)

The next example uses standard action tags (from the jsp tag library). The
example used the
<jsp:inclu
de>

action tag to bring in content from another JSP.
Therefore one can create HTML pages that contain standard content and then write a
separate JSP to build up a response HTML page containing the standard content plus
some customised content.

Highlight
in
clude.jsp

in the NetBeans explorer window and run it. You will see a
browser page looking like this:


Now compare the source of this page (as viewed from IE6) with the content of
include.jsp

in NetBeans. You will see that the
<jsp:include>

elements in the

JSP
have been replaced by fragments of HTML content held in the files that they
respectively refer to. Inspect the content of
banner.html

and
toc.html

to see this.
Note also that one is not restricted to including static content only. The action
element:

<jsp:include page = "clock2.jsp" flush = "true" />

includes the output of a JSP that generates a digital clock
§
. This refreshes each time
the page is requested.

In this example, the results of the
<jsp:include>

elements are formatted by arranging
them in
a table. One could equally well use CSS2 positioning properties to include
predefined layers of content existing within DIV elements or any other well
-
known
client
-
side content
-
formatting trick.

4)

The next example uses the
<jsp:forward>

action element to tak
e in a request with
one JSP, add some further parameters to the request and then forward it on to a
second JSP. Essentially , this is an elaboration of
welcome.jsp

with some added
functionality split over two logically separate steps. Doing things in this
way
enhances the re
-
useability of the code.

In NetBeans, look at the code in
forward1.jsp
. You will notice a strong resemblance
to
welcome.jsp

in that the processing forks depending on the presence or absence of a
“firstName” parameter. If the parameter is

null,
forward1.jsp

returns exactly the
same form as
welcome.jsp

requesting that the data is input. The interesting part is in
the
if
clause fired when there is a non
-
nu;; “firstName” parameter. The clause contains
a
<jsp:include>

action element, which itse
lf contains a
<jsp:param>

action element.
The line:

<jsp:forward page = "forward2.jsp">

redirects processing to
forward2.jsp

as soon as the end
-
tag of the element is reached.
Before this however, the line:

<jsp:param name = "date” value = "<%= new java.uti
l.Date() %>" />

adds the parameter “date” to the Http
Servlet
Request object before it is passed on to
forward2.jsp
. Note that it is a Java java.util.Date object that is passed, not a String
representing the date.

Now look at
forward2.jsp
. It reacts to the r
equest by making two calls on
getParameter
: one to get the “firstName” and the other to get a String representation
of the Date object (the call to the Date.toString() method is implicit because the
scripting element is expecting a String result from a Jav
a expression
**
)
.


Run
forward1.
jsp
. You should get the form up first in IE6, then when you sublit the
data, processing will be re
-
directed to
forward2.
jsp

and you will see something like
the following in your browser:


You

can easily imagine other examples

where you might use a “front
-
line” JSP to
take in initial data and then re
-
direct processing to other JSPs depending on what the
submitted data turned out to be.





*

I am in no way expecting you to buy or even to refer to this book. My discus
sion of the examples here
is entirely self
-
contained. The purpose of the reference is to correctly attribute the source of the code
and to provide direction for those seeking other sources to supplement their understanding and interest
in the subject.




ere is a world of difference between this sort of “scripting” in Java and, say, writing web pages
containing JavaScript. If you don’t see the difference, then you don’t properly understand what’s going
on and should get someone to explain it to you. Essent
ially, in a JSP, scripting elements contain
isolated Java statements. Although this looks like genuine scripting, where isolated code statements are
interpreted line
-
by
-
line by a scripting engine, what you are actually doing here is using the JSP format
as

a way of writing, and then compiling, fully formed Java code, but without the effort of having to
type in a lot of boilerplate class and method definitions, specifically those needed to define a
servlet
.
When the JSP runs, it is fully compiled Java that i
s running. When JavaScript runs (usually in a web
browser) there is no pre
-
compilation at all. The text of the script is delivered to the (browser) scripting
engine and statements are interpreted and run one at a time.



䙯r 瑨os攠of you wond敲楮g
I qom捡琠
楳 runn楮g on por琠tM84 楮 my sys瑥m b散慵s攠f h慶e
o瑨敲 w敢
s敲v敲
s

runn楮g on
my m慣hine
. In the lab you will see “8080” in the address bar.

§

A
souped
-
up version of the first

example, which returns the date formatted according to Local Time
on the clie
nt rather than Local Time on the server.

**

Note again here that the content of this element is an
expression

not a
statement
. Therefore the
element is correctly written:

<%= request.parameter (“date”) %>

and is most definitely NOT written:

<%= request.para
meter (“date”); %>