Intranet Systems Development: Laboratory Eight Introduction to JSP

mobdescriptiveΛογισμικό & κατασκευή λογ/κού

28 Οκτ 2013 (πριν από 4 χρόνια και 11 μέρες)

78 εμφανίσεις

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
L
, slides 9
-
1
5
, to create a Web Application, Lab8
.

1)

Again, following the steps in Lecture
L
, slides 1
6
-
1
9
, 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
L
, slide
20
) and run the project. Browse to the JSP
(Lecture
L
, slide 2
1
).

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
1

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
web
/

called “Images” and move
logotiny
.png

into i
t.

2)

The firs
t 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


is em扥摤d搠insi摥 tags that f潲m 灡rt 潦 the res灯pse 灡ge⸠v潵
are more familiar with embedding the response output inside “print” statements in
your server
-
side sc
ripts.

In NetBeans, open
welcome.jsp
. You will notice that NetBeans highlights JSP
scripting elements within the page in a
coloured

background. The first of these is:

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


The reference “request” refers to the

Http
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 functiona
lity 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 ret
urn 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” par
ameter 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

replaced 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 f
rom 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
that 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 “
Sandy
” to this field and hit “Submit”, the browser will send
an http request with request line:

GET localhost:8080/.../welcome.jsp?firstName=
Sandy

http/1.1

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

defined by
welcome.jsp
.

If you haven’t already done so,
right click on

welcome.jsp

in the NetBeans explorer
window and run it by click
ing
“run file”
. 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

⸠ lf c潵rseⰠ
getParameter

will just as happ
ily 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:include>

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.

Right click

include.jsp

in th
e 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 pa
ge = "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 co
uld 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 take 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 th
e 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 itself 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.util.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 request by makin
g 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 Java 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 migh
t 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 discussion of the exa
mples 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.



qhere 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. Essentially, 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 writi
ng, 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 is 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.








For those of you wondering, Tomcat is running on p
ort 8081 in my system because I have other web
servers running on my machine. 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 client 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.parameter (“date”);

%>