Servlet and JSP Servlet and JSP Review

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

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

81 εμφανίσεις

© 2009 Marty Hall
Servlet and JSP
Servlet

and

JSP
Review
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2
© 2009 Marty Hall
For live Ajax & GWT training, see training
t htt//l t/
courses a
t

htt
p:
//
courses.coreserv
l
e
t
s.com
/
.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP
and this tutorial Available at public
Servlets

and

JSP
,
and

this

tutorial
.
Available

at

public

venues, or customized versions can be held on-site
at
y
our
or
g
anization.
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
y
g
• Courses developed and taught by Marty Hall
– Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
• Courses developed and taught by coreservlets.com experts (edited by Marty)
– Spring, Hibernate, EJB3, Ruby/Rails
Contact hall@coreservlets.comfor details
Agenda
• What servlets are all about
• Servlet basics
• Creating and deploying projects
• Creating forms and reading form data
• JSP scripting
• Using XML syntax for JSP pages
• JSP file inclusion
• MVC
4
© 2009 Marty Hall
S l t B i
S
erv
l
e
t

B
as
i
cs
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
5
A Servlet’s Job
• Read explicit data sent by client
F d t

F
orm
d
a
t
a
• Read implicit data sent by client
– Re
q
uest headers
q
• Generate the results
• Send the explicit data back to client
HTML XML JSON t d t f t

HTML
or
XML
or
JSON
or cus
t
om
d
a
t
a
f
orma
t
• Send the implicit data to client
– Status codes and res
p
onse headers
p
6
Accessing the Online
Documentation
Documentation
• Servlets and JSP
htt//j/d t/l t/2 5/d/l t
2 5
2/

htt
p:
//j
ava.sun.com
/
pro
d
uc
t
s
/
serv
l
e
t/2
.
5/d
ocs
/
serv
l
e
t
-
2
_
5
-mr
2/
– http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/
– htt
p
://tomcat.a
p
ache.or
g
/tomcat-5.5-doc/servleta
p
i/
p p g
p
– http://tomcat.apache.org/tomcat-5.5-doc/jspapi/
• Java 6 or Java 5
htt//j/j/6/d/i/

htt
p:
//j
ava.sun.com
/j
avase
/6/d
ocs
/
ap
i/
• Class uses Java 6 and Tomcat 6
– http://java.sun.com/j2se/1.5.0/docs/api/
• Advice
– If you have a fast and reliable internet connection,
bookmark these addresses
bookmark

these

addresses
– If not, download a copy of the APIs onto your local
machine and use it
7
A Sample Servlet (Code)
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "+
"Transitional//E
N
\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello (2)</TITLE></HEAD>\n"+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello (2)</H1>\n" +
"</BODY></HTML>");
}
}
8
A Sample Servlet (Result)
Assumes Eclipse project named intro. Code in src/coreservlets/HelloServlet2.java.
If k th b l t i f th i lid ld l
9
If

y
ou ma
k
e
th
e we
b
.xm
l
en
t
r
i
es
f
rom
th
e upcom
i
n
g
s
lid
es,
y
ou cou
ld
a
l
so use
the URL http://localhost/intro/hi2
© 2009 Marty Hall
Testing with
Testing

with

Eclipse
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
10
Installing Eclipse
• Overview
E li i f
d l i

E
c
li
pse
i
s a
f
ree open-source
d
eve
l
opment env
i
ronment
with support for Java and many other languages
• Downloadin
g
g
– http://www.eclipse.org/downloads/
• Choose “Eclipse IDE for Java EE Developers”

As of
12/2008
,version 3.4,called Eclipse Ganymede
As

of

12/2008
,

version

3.4,

called

Eclipse

Ganymede
• Installing
– Unzip into directory of your choice
P h li d k

P
ut s
h
ortcut to ec
li
pse.exe on your
d
es
k
top
• Integrating Tomcat in Eclipse

http://www coreservlets com/
http://www
.
coreservlets
.
com/
Apache-Tomcat-Tutorial/eclipse.html
11
Configuring Eclipse
• Make sure Eclipse
k b T
k
nows a
b
out
T
omcat
– Click on Servers tab at bottom.
R
-
click in window
R
-
click

in

window
.
– New, Server, Apache, Tomcat v6.0,
Next, navigate to folder, Finish.
• Suppress unnecessary
compiler warnings
Wi d

P f


Wi
n
d
ow

P

f
敲敮捥猠

䩡癡J Compiler 
Errors/Warnin
g
s
g
• Change “Serializable class
without ...” to “Ignore”
12
Making Web Apps in Eclipse
• Make empty project
– File 
N
ew Project 
Web Dynamic Web Project

Give it a name (e g

test

)

Give

it

a

name

(e
.
g
.,
test )
– Accept all other defaults
• Shortcut
– If you have made Dynamic
Web Project recently in
workspace you can just do
workspace
,
you

can

just

do
File New 
Dynamic Web Project
13
Adding Code to Eclipse Projects
• Locations
src

src
• Unpackaged Java code
• Packages strongly recommended

src
/
somePackage
src
/
somePackage
•Java code in somePackage package
– WebContent
• Web files
(
HTML, JavaScri
p
t,
( p
CSS, JSP, images, etc.)
– WebContent/some-subdirectory
• Web content in subdirectory
W bC t t
/WEB
INF

W
e
bC
on
t
en
t
/WEB
-
INF
• web.xml (will be discussed later)
• Can also click on
“De
p
lo
y
ment Descri
p
tor”
p y p
• Note
– Can cut/paste or drag/drop files into appropriate locations
14
Starting Server in Eclipse
• Start Tomcat
– Select “Servers” tab at bottom
– R-click on Tomcat
Choose

Start


Choose

Start
• Verify server startup

Open browser
Open

browser
– Enter http://localhost/
• You should see blank directory listing

If you want pretty Tomcat
welcome page, search for a
folder called ROOT in your
Ecli
p
se works
p
ace.
p p
Copy files from
C:\tomcat-dir\webapps\ROOT
to that folder
15
Deploying App in Eclipse
• Deploy project
– Select “Servers” tab at bottom
– R-click on Tomcat
Choose

Add and Remove Projects


Choose

Add

and

Remove

Projects
– Choose project
– Press “Add”
– Click “Finish”
• Restart
Server
– R-click Tomcat
at bottom
at

bottom
– Restart
16
Testing Deployed Apps in Eclipse
• Start a browser
Eclipse also has
builtin
browser

Eclipse

also

has

builtin
browser
,
but I prefer to use Firefox or
Internet Explorer

Test base URL
Test

base

URL
– http://localhost/test/
• Test Web content
http://localhost/test/Hello html

http://localhost/test/Hello
.
html

(case sensitive!)
– http://localhost/test/Hello.jsp

If
you

used

subd
ir
ecto
ri
es
you used subd ecto es
• http://localhost/test/
some-subdirectory/blah.html
• Test servlets

http://localhost/test/servlet/HelloServlet
– http://localhost/test/servlet/coreservlets.HelloServlet2
• Note: custom URLs discussed in next section
17
Defining Custom URLs
• Java code
package
myPackage
;
package

myPackage
;
...
public class MyServlet extends HttpServlet { ... }
• web.xml entry (in <web-app...>...</web-app>)
Gi t l t

Gi
ve name
t
o serv
l
e
t
<servlet>
<servlet-name>MyName</servlet-name>
<servlet
class>
myPackage MyServlet
</servlet
class>
<servlet
-
class>
myPackage
.
MyServlet
</servlet
-
class>
</servlet>
– Give address (URL mapping) to servlet
<servlet
-
mapping>
<servlet
-
mapping>
<servlet-name>MyName</servlet-name>
<url-pattern>/MyAddress</url-pattern>
</servlet-mapping>
• Resultant URL
– http://hostname/webappPrefix/MyAddress
18
Defining Custom URLs: Example
(Assume Eclipse Project is
"
test
"
)
(Assume

Eclipse

Project

is

test )
<?xml version="1.0" encoding="UTF-8"?>
<web
-
app
Don't edit this manually.
Should refer to version 2.4
<web
app

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
...
or 2.5
(
Tomcat 6 onl
y)
.
v
ersion="2.5">
<!-- Use the URL http://hostname/intro/hi instead
of http://hostname/intro/servlet/HelloServlet
--
>
of

http://hostname/intro/servlet/HelloServlet

--
>
<servlet>
<servlet-name>Second Hello Servlet</servlet-name>
<servlet-class>coreservlets.HelloServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Second Hello Servlet</servlet-name>
l
tt/hi2/
l
tt
Any arbitrary name.
But must be the same both times.
Fully qualified classname.
<
u
r
l
-pa
tt
ern>
/hi2
<
/
u
r
l
-pa
tt
ern>
</servlet-mapping>
</web-app>
19
The part of the URL that comes after the app (project) name.
Should start with a slash.
Defining Custom URLs: Result
• Eclipse details
f li j i

N
ame o
f
Ec
li
pse pro
j
ect
i
s “test”
– Servlet is in src/coreservlets/HelloServlet2.java

Deployed by right
-
clicking on Tomcat Add and Remove

Deployed

by

right
-
clicking

on

Tomcat
,
Add

and

Remove

Projects, Add, choosing test project, Finish, right-clicking
again, Start
20
Debugging Servlets
• Use print statements; run server on desktop

Use Apache Log4J

Use

Apache

Log4J
• Integrated debugger in IDE
– Right-click in left margin in source to set breakpoint (Eclipse)

R
-
click Tomcat and use

Debug

instead of

Start

R
click

Tomcat

and

use

Debug

instead

of

Start
• Look at the HTML source
• Return error pages to the client
– Plan ahead for missin
g
or malformed data
g
• Use the log file
– log("message") or log("message", Throwable)
• Se
p
arate the re
q
uest and res
p
onse data .
p q p
– Request: see EchoServer at www.coreservlets.com
– Response: see WebClient at www.coreservlets.com
• Make sure browser is not caching
– Internet Explorer: use Shift-RELOAD
– Firefox: use Control-RELOAD
• Stop and restart the server
21
© 2009 Marty Hall
F D t
F
orm
D
a
t
a
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
26
Using Form Data
• HTML form
– Should have ACTION referring to servlet
• Use relative URL

ACTION
="
/
webAppName
/address
"
ACTION/
webAppName
/address
– ACTION="./address"
– Should have input entries with NAMEs
Sh ld b i t ll d d
W bC t t

Sh
ou
ld

b
e
i
ns
t
a
ll
e
d
un
d
er
W
e
bC
on
t
en
t
• Servlet
Calls
request getParameter
with name as given in HTML

Calls

request
.
getParameter
with

name

as

given

in

HTML
– Return value is entry as entered by end user
– Missin
g
values
g
• null if no input element of that name was in form
• Empty string if form submitted with empty textfield
27
An HTML Form With Three
Parameters
Parameters
<FORM ACTION="./show-params">
First Parameter:<INPUT TYPE=
"
TEXT
"
NAME=
"
param1
"
><BR>
url-pattern of servlet
First

Parameter:

<INPUT

TYPE= TEXT

NAME= param1
><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
28
• Project name is “review”
• Form installed in WebContent/ThreeParamsForm.html
Reading the Three Parameters
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>"+title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}
29
Reading Three Parameters:
web xml
web
.
xml

<servlet>
<servlet>
<servlet-name>Param Servlet</servlet-name>
<servlet-class>coreservlets.ThreeParams</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Param Servlet</servlet-name>
<url-pattern>/show-params</url-pattern>
</
servlet
-
mapping>
</
servlet
-
mapping>

30
Reading Three Parameters:
Result
Result
31
© 2009 Marty Hall
JSP S i ti
JSP

S
cr
i
p
ti
ng
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
32
Uses of JSP Constructs

Scripting elements calling servlet
Scripting

elements

calling

servlet

code directly
• Scriptin
g
elements callin
g
servlet
Simple
Application
g g
code indirectly (by means of utility
classes)
B

B
eans
• Servlet/JSP combo (MVC)
MVC ith JSP i l

MVC
w
ith

JSP
express
i
on
l
anguage
• Custom tags
MVC ith b t t d
Complex
Application

MVC
w
ith

b
eans, cus
t
om
t
ags, an
d

a framework like Struts or JSF
33
Application
JSP Scripting Design Strategy:
Limit Java Code in JSP Pages
Limit

Java

Code

in

JSP

Pages
• You have two options
– Put 25 lines of Java code directly in the JSP page
– Put those 25 lines in a separate Java class and put 1 line
in the JSP page that invokes it
in

the

JSP

page

that

invokes

it
• Why is the second option much better?
– Develo
p
ment. You write the se
p
arate class in a
J
ava
p
p J
environment (editor or IDE), not an HTML environment
–Debugging. If you have syntax errors, you see them
immediately at compile time Simple print statements can
immediately

at

compile

time
.
Simple

print

statements

can

be seen.
– Testin
g
. You can write a test routine with a loo
p
that
g
p
does 10,000 tests and reapply it after each change.
–Reuse. You can use the same class from multiple pages.
34
JSP Expressions
• Format
– <%= Java Expression %>
• Result
Expression evaluated converted to String and placed

Expression

evaluated
,
converted

to

String
,
and

placed

into HTML page at the place it occurred in JSP page
– That is, expression placed in _jspService inside out.print
• Examples
– Current time: <%= new java.util.Date() %>
Y h t <% t tR t H t() %>

Y
our
h
os
t
name:
<%
= reques
t
.ge
tR
emo
t
e
H
os
t()

%>
• XML-compatible syntax

<jsp:expression>
Java Expression
</jsp:expression>
<jsp:expression>
Java

Expression
</jsp:expression>
– You cannot mix versions within a single page. You must
use XML for entire page if you use jsp:expression.
35
Predefined Variables
• request
– The HttpServletRequest (1st argument to service/doGet)
• response
Th H S l R (2 d i/d G )

Th
e
H
ttp
S
erv
l
et
R
esponse
(2
n
d
arg to serv
i
ce
/d
o
G
et
)
• out
The Writer (a buffered version of type JspWriter) used to

The

Writer

(a

buffered

version

of

type

JspWriter)

used

to

send output to the client
• session
– The HttpSession associated with the request (unless
disabled with the session attribute of the page directive)

application

application
–The ServletContext (for sharing data) as obtained via
getServletContext().
36
JSP Scriptlets
• Format
– <%Java Code %>
• Result
C d i i d b i i l'j S i

C
o
d
e
i
s
i
nserte
d
ver
b
at
i
m
i
nto serv
l
et
'
s _
j
sp
S
erv
i
ce
• Example
<%

<%

String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
%>
– <% response.setContentType("text/plain"); %>

XML
-
compatible syntax
XML
compatible

syntax
– <jsp:scriptlet>Java Code</jsp:scriptlet>
37
JSP Declarations
• Format
– <%!Java Code %>
• Result
Code is inserted verbatiminto servlet's class definition

Code

is

inserted

verbatim

into

servlet's

class

definition
,
outside of any existing methods
• Exam
p
les
p
– <%! private int someField = 5; %>
– <%! private void someMethod(...) {...} %>
D i id ti

D
es
i
gn cons
id
era
ti
on
– Fields are clearly useful. For methods, it is usually better
to define the method in a separate Java class.
to

define

the

method

in

a

separate

Java

class.
• XML-compatible syntax
– <jsp:declaration>Java Code</jsp:declaration>
38
© 2009 Marty Hall
JSP Pages with
JSP

Pages

with

XML S
y
ntax
y
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
39
Why Two Versions?
• Classic syntax is not XML-compatible
– <%= ... %>, <% ... %>, <%! ... %> are illegal in XML
– HTML 4 is not XML compatible either
So you cannot use XML editors like XML Spy

So
,
you

cannot

use

XML

editors

like

XML

Spy
• You might use JSP in XML environments

To build
xhtml
pages
To

build

xhtml
pages
– To build regular XML documents
• You can use classic syntax to build XML documents, but it
i ti i if ki i XML t t t ith
i
s some
ti
mes eas
i
er
if
you are wor
ki
ng
i
n
XML

t
o s
t
ar
t
w
ith
– For Web services
– For Ajax applications
• So, there is a second syntax
– Following XML rules
40
XML Syntax for Generating XHTML
Files (somefile jsp
x
)
Files

(somefile
.
jsp
x
)
<?xml version="1.0" encoding="UTF-8" ?>
<html mlns jsp"http//ja a s n com/JSP/Page">
The jsp namespace is required if you
use jsp:blah commands. You can use
<html
x
mlns
:
jsp
=
"http
:
//ja
v
a
.
s
u
n
.
com/JSP/Page">
<jsp:output
omit-xml-declaration="true"
other namespaces for other custom ta
g
libraries.
Needed because of Internet Explorer bug where xhtml pages
that have the XML declaration at the top run in quirks mode.
doct
y
pe-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
Builds DOCTYPE line.
<jsp:directive.page contentType="text/html"/>
<head><title>Some Title</title></head>
<
body bgcolor
="
#fdf5e6
">
For JSP pages in XML syntax, default content
type is text/xml.
body

bgcolor#fdf5e6
Body
</body></html>
Normal xhtml content, plus JSP commands that use
j
s
p
:blah s
y
ntax,
p
lus JSP custom ta
g
libraries.
41
j p y p g
XML Syntax for Generating Regular
XML Files (somefile jsp
x
)
XML

Files

(somefile
.
jsp
x
)
<?xml version="1.0" encoding="UTF-8" ?>
///S/
<
y
our-root-element xmlns:
j
sp="http:
//j
ava.sun.com
/
J
S
P
/
Pa
g
e">
<your-tag1>foo</your-tag1>
<your
-
tag2>bar</your
-
tag2>
<your
tag2>bar</your
tag2>
<your-root-element>
U

U
ses
– When you are sending to client that expects real XML
• A
j
ax
j
• Web services
• Custom clients

N
ote
• You can omit the xmlns declaration if you are not using
any JSP tags. But then you could just use .xml extension.
42
XML Syntax for Generating HTML 4
Files (somefile jsp
x
)
Files

(somefile
.
jsp
x
)
• Many extra steps required
– Enclose the entire page in jsp:root
– Enclose the HTML in CDATA sections
• Between <![CDATA[ and ]]>
• Because HTML 4 does not obey XML rules
U ll t th th b th

U
sua
ll
y no
t
wor
th

th
e
b
o
th
er
43
Sample HTML 4 Page: Classic
Syntax (sample
jsp
)
Syntax

(sample
.
jsp
)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD ...">
<HTML>
<HTML>
<HEAD><TITLE>Sample (Classic Syntax)</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<CENTER>
<H1>Sample (Classic Syntax)</H1>
<H2>Num1:<%
=
Math.random()
*
10 %></H2>
<H2>Num1:

<%

Math.random() 10

%></H2>
<% double num2 = Math.random()*100; %>
<H2>Num2: <%= num2 %></H2>
<
%!

p
riv
ate

doub
l
e
n
u
m
3
= M
at
h
.
r
a
n
do
m
()
*1
000;

%
>
%!p ate doub e u 3 at.a do () 000;%
< H 2 > N u m 3: < % = n u m 3 % > </H 2 >
</C E N T E R >
</BODY></HTML>
44
Sample XHTML Page: XML Syntax
(sample
jspx
)
(sample
.
jspx
)
<?xml version="1.0" encoding="UTF-8" ?>
<html xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:output
omit-xml-declaration="true"
doctype-root-element="html"
doctype-public="-//W3C//DTD ..."
doctype-system="http://www.w3.org...dtd" />
<jsp:directive.page contentType="text/html"/>
<head><title>Sample (XML Syntax)</title></head>
<body bgcolor="#fdf5e6">
di li
<
di
v a
li
gn="center">
<h1>Sample (XML Syntax)</h1>
<h2>Num1: <jsp:expression>Math.random()*10</jsp:expression></h2>
<jsp:scriptlet>
d bl 2 M th d ()*100
d
ou
bl
e num
2
=
M
a
th
.ran
d
om
()*100
;
</jsp:scriptlet>
<h2>Num2: <jsp:expression>num2</jsp:expression></h2>
<jsp:declaration>
i t d bl 3 M th d ()*1000
pr
i
va
t
e
d
ou
bl
e num
3
=
M
a
th
.ran
d
om
()*1000
;
</jsp:declaration>
<h2>Num3: <jsp:expression>num3</jsp:expression></h2>
</div></body></html>
45
Sample Pages: Results
46
XML Document Generated with
XML Syntax
XML

Syntax
<?xml version="1.0" encoding="UTF-8" ?>
<some
-
root
-
element
<some
root
element
xmlns:jsp="http://java.sun.com/JSP/Page">
<some-element-1>Text</some-element-1>
<some-element-2>
Number:
<jsp:expression>Math.random()*10</jsp:expression>
</some-element-2>
</some-root-element>
47
© 2009 Marty Hall
j i l d
j
sp:
i
nc
l
u
d
e
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
48
Including Files at Request Time:
jsp:include
jsp:include
• Format
– <
j
sp:include
p
age="Relative URL" />
• Purpose
T JSP HTML l i t t t t

T
o reuse
JSP
,
HTML
, or p
l
a
i
n
t
ex
t
con
t
en
t
– To permit updates to the included content without
changing the main JSP page(s)
• Notes
– JSP content cannot affect main page:
onl
t t
of incldedJSP page is sed
onl
y ou
t
pu
t
of

incl
u
ded

JSP

page

is
u
sed
– Don't forget that trailing slash
– Relative URLs that starts with slashes are inter
p
reted
p
relative to the Web app, not relative to the server root.
– You are permitted to include files from WEB-INF
49
jsp:include Example: A News
Headline Page (Main Page)
Headline

Page

(Main

Page)

<BODY>
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
What's New at JspNews.com</TABLE>
<P>
Here is a summary of our three
most recent news stories:
<OL>
<LI><jsp:include page="/WEB-INF/includes/item1.jsp" />
<LI><jsp:include page="/WEB-INF/includes/item2.jsp" />
LI
j i l d
"/
WEB
INF/i l d/it 3 j"
/
<
LI
><
j
sp:
i
nc
l
u
d
e page=
"/
WEB
-
INF/i
nc
l
u
d
es
/it
em
3
.
j
sp
"

/
>
</OL>
</BODY></HTML>
50
A News Headline Page,
Continued (First Included Page)
Continued

(First

Included

Page)
<B>Bill Gates acts humble.</B> In a startling
and unexpected development Microsoft big wig
and

unexpected

development
,
Microsoft

big

wig

Bill Gates put on an open act of humility
yesterday.
<A HREF="http://www.microsoft.com/Never.html">
More details...</A>

N
ote that the
p
a
g
e is no
t
a com
p
lete HTML document
;
it
p g
p;
has only the tags appropriate to the place that it will be
inserted
51
A News Headline Page: Result
52
© 2009 Marty Hall
MVC
MVC
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
53
MVC Flow of Control
HTML or JSP
Java Code
(Business Logic)
R l
Form
Servlet
submit form
(URL matches url-
pattern of servlet)
R
esu
l
ts
(beans)
(Store beans in
request, session, or
a
pp
lication sco
p
e
)
pp p )
JSP
1
JSP
2
JSP
JSP
3
(Extract data from beans
and put in output. Pages
usually under WEB-INF.)
Eg: request.setAttribute("customer", customerObject);
54
Eg: ${customer.firstName}
Simple MVC Example:
Request
-
Scoped Data
Request
-
Scoped

Data
• Goal
– Display a random number to the user
Type of sharing

Type

of

sharing
– Each request should result in a new number, so request-
b
ased sharin
g
is a
pp
ro
p
riate.
g pp p
55
Request-Based Sharing: Bean
package coreservlets;
public class NumberBean {
private double num = 0;
public NumberBean(double number) {
setNumber(number);
}
}
public double getNumber() {
r
etu
rn
(
n
u
m
);
etu ( u );
}
p
ublic void setNumber
(
double number
)

{
p ( ) {
num = number;
}
}
56
Request-Based Sharing: Servlet
public class RandomNumberServlet extends HttpServlet {
public void
doGet
(
HttpServletRequest
request
public

void

doGet
(
HttpServletRequest
request
,
HttpServletResponse response)
throws ServletException, IOException {
NumberBean
bean
=
NumberBean
bean

RanUtils.getRandomNum(request.getParameter("range"));
request.setAttribute("randomNum", bean);
Strin
g
address = "
/
WEB-INF
/
mvc-sharin
g/
RandomNum.
j
s
p
"
;
g/
/
g/j p;
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
57
Request-Based Sharing:
Business Logic
Business

Logic
public class RanUtils {
public static
NumberBean
getRandomNum
(String
rangeString
) {
public

static

NumberBean
getRandomNum
(String

rangeString
)

{
double range;
try {
range
=
Double.parseDouble
(
rangeString
);
range

Double.parseDouble
(
rangeString
);
} catch(Exception e) {
range = 10.0;
}
}
return(new NumberBean(Math.random() * range));
}
}
58
Request-Based Sharing:
URL Pattern (web xml)
URL

Pattern

(web
.
xml)
...
<servlet>
<servlet>
<servlet-name>RandomNumberServlet</servlet-name>
<servlet-class>
coreservlets.RandomNumberServlet
coreservlets.RandomNumberServlet
</servlet-class>
</servlet>
<servlet
-
mapping>
<servlet
mapping>
<servlet-name>RandomNumberServlet</servlet-name>
<url-pattern>/random-number</url-pattern>
<
/se
rvl
et
-m
app
in
g
>
/se et
app g
...
59
Request-Based Sharing:
Input Form
Input

Form
...
<fieldset>
<fieldset>
<legend>Random Number</legend>
<form action="./random-number">
Range:<input type=
"
text
"
name=
"
range
"
><br/>
Range:

<input

type= text

name= range
><br/>
<input type="submit" value="Show Number">
</form>
</fieldset>
</fieldset>
...
60
Request-Based Sharing:
Results Page
Results

Page

<body>
<body>
<h2>Random Number: ${randomNum.number}</h2>
</body></html>
61
Request-Based Sharing:
Results
Results
62
Summary
• Set up Java 6, Tomcat, and Eclipse
h//l/

h
ttp:
//
www.coreserv
l
ets.com
/
Apache-Tomcat-Tutorial/eclipse.html
• Give custom URLs to all servlets
– Use servlet, servlet-mapping, and url-pattern in web.xml
• Forms
U l ti URL f ACTION

U
se re
l
a
ti
ve
URL
s
f
or
ACTION
.
– Read parameters with request.getParameter

JSP Scripting
JSP

Scripting
– If you use scripting, put most Java code in regular classes
• MVC
id l li bl h
– Very w
id
e
l
y app
li
ca
bl
e approac
h
.
– Consider using it in many (most?) applications
63
© 2009 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
64