Servlet and JSP Review

VISoftware and s/w Development

Oct 14, 2011 (6 years and 11 days ago)

1,268 views

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. 2 Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2010 Marty Hall
Servlet and JSP
Servlet

and

JSP
Review
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2
© 2010 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
More
Servlets and JSP
,
and this tutorial
.
Available at
public venues, or customized versions can be held
on-site at your
organization.
C d l d d t ht b M t H ll
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

C
ourses
d
eve
l
ope
d
an
d

t
aug
ht

b
y
M
ar
t
y
H
a
ll
– Java 6, servlets/JSP (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics
– Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) or survey several
• Courses developed and taught by coreservlets.com experts (edited by Marty)
– Spring, Hibernate/JPA, EJB3, SOAP-based and RESTful Web Services
Contact hall@coreservlets.com for details
Agenda
• Eclipse and Tomcat setup
• Deploying apps from Eclipse to Tomcat
• Making new apps in Eclipse
• Servlet basics
• Creating forms and reading form data
• JSP scripting
• Using XML syntax for JSP pages
• JSP file inclusion
• MVC
4
© 2010 Marty Hall
I t lli E li
I
ns
t
a
lli
ng
E
c
li
pse
For even more detailed step-by-step instructions, see tutorials on using Eclipse with
Tomcat 6 or Tomcat 7 at http://www.coreservlets.com/Apache-Tomcat-Tutorial/
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
5
Installing Eclipse
• Overview

Eclipse is a
a
free open source IDE

Eclipse

is

a

a
free

open

source

IDE

for Java. Support for Java, HTML,
CSS, JavaScript, C++, PHP, and
more.
http://eclipse org/downloads/

http://eclipse
.
org/downloads/
• Choose “Eclipse IDE for Java EE
Developers”
– Need version 3.6 (Helios) for Tomcat 7
F t

F
ea
t
ures
– Checks your syntax as you type
– Automatically compiles every
time you save file
time

you

save

file
– Many tools: refactoring,
debugging, server integration,
tem
p
lates for common tasks, etc.
p
• Low learning curve: beginners can
use Eclipse without knowing these
tools
Note: step-by-step Eclipse/Tomcat integration guide at http://www.coreservlets.com/ (click “Apache Tomcat 7” in top left).
Running Eclipse
• Unzip the downloaded file
– Call the folder you unzip into “installDir”
• Double click eclipse.exe
F
i llDi
/bi

F
rom
i
nsta
llDir
/bi
n
• Click on

Workbench

icon
Workbench

icon
– Next time you bring
up Eclipse, it will
come up in workbench automatically
• Shortcut
M d l t E li li k th i d kt

M
any
d
eve
l
opers pu
t

E
c
li
pse
li
n
k
on
th
e
i
r
d
es
kt
op
• R-click eclipse.exe, Copy, then go to desktop, R-click, and
Paste Shortcut (not just Paste!)
Configuring Eclipse
• Tell Eclipse about Java version
Wi d

P f

J


Wi
n
d
ow

P

f
敲敮捥猠

J
慶愠

䥮獴慬汥搠䩒䕳I Press “Add”, choose
“Standard VM”, navigate to JDK folder
(not

bin

subdirectory)
(not

bin

subdirectory)
• E.g., C:\Program Files\Java\jdk1.6.0_21
• Tell Eclipse about Tomcat
Cli k S b b

Cli
c
k
on
S
ervers ta
b
at
b
ottom.
R-click in window.
– New, Server, Apache, Tomcat v7.0,
N t i t t f ld Fi i h
N
ex
t
, nav
i
ga
t
e
t
o
f
o
ld
er,
Fi
n
i
s
h
.
• Suppress serializable warnings

Window Preferences Java 
Compiler Errors/Warnings
• Change “Serializable class
without ...” to “Ignore”
8
Tomcat v7.0 is choice only in Eclipse 3.6 (Helios). If you
prefer Tomcat 6, choose Tomcat v6.0 above instead. If
you lose the “Servers” tab at the bottom of Eclipse, use
Window, Show View, and hunt for “Servers”.
© 2010 Marty Hall
Deploying Apps
Deploying

Apps

from Eclipse
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
9
Download and Import Sample
Project
Project
• Get test-app.zip from coreservlets.com
– Start at Ajax tutorials
• http://courses.coreservlets.com/
Course-Materials/a
j
ax.html
j
– Go to first section (Servlet and JSP Review)
– Or, start at Apache Tomcat tutorial

http://www coreservlets com/Apache
Tomcat
Tutorial/

http://www
.
coreservlets
.
com/Apache
-
Tomcat
-
Tutorial/
– Choose Tomcat 7 (recommended) or Tomcat 6 version
• Then, download test-app.zip
– Then, import into Eclipse.
• File, Import, General, Existing
Projects,Select archive file.
Projects,

Select

archive

file.

Then click Browse and navigate
to test-app.zip.
10
Deploying App in Eclipse
• Deploy project
– Select “Servers” tab at bottom
– R-click on Tomcat

Choose

Add and Remove

Choose

Add

and

Remove
– Choose project
– Press “Add”
– Click “Finish”
• Start Server
R
click Tomcat at bottom

R
-
click

Tomcat

at

bottom
– Start (use “Restart” if
Tomcat already running)
• Test URL
– http://localhost/test-app/ in any Web browser
11
Testing Deployed App in Eclipse
• Start a browser

Eclipse also has builtin browser,
but I prefer to use Firefox or
Internet Explorer
• Test base URL
– http://localhost/test-app/
T t W b t t

T
es
t

W
e
b
con
t
en
t
– http://localhost/test-app/hello.html

http://localhost/test
-
app/hello.jsp
http://localhost/test
app/hello.jsp
• Test servlets
– http://localhost/test-app/hello
– http://localhost/test-app/test1
– http://localhost/test-app/test2
12
© 2010 Marty Hall
Making New Apps
Making

New

Apps

from Eclipse
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
13
Making Web Apps in Eclipse
• Make empty project
– File 
N
ew Project 
Web Dynamic Web Project

For

Target runtime

choose

For

Target

runtime
,
choose
“Apache Tomcat v7.0”
– Give it a name (e.g., “test”)
– Accept all other defaults
• Shortcut
If h d D i

If
you
h
ave ma
d
e
D
ynam
i
c
Web Project recently in
works
p
ace,
y
ou can
j
ust do
p y j
File New 
Dynamic Web Project
14
Adding Code to Eclipse Projects
• Locations
Java Resources:src

Java

Resources:

src
• R-click and New Package
• Never use default package

src/
testPackage
src/
testPackage
•Java code in testPackage package
– WebContent
• Web files (HTML, JavaScript,
CSS JSP i t )
CSS
,
JSP
,
i
mages, e
t
c.
)

– WebContent/some-subdirectory
• Web content in subdirectory

R
-
click on WebContent New

䙯汤敲
•
R
-
捬楣c



坥扃潮瑥湴

乥N


䙯汤敲
– WebContent/WEB-INF
• web.xml

O
p
tional with servlets 3.0. Re
q
uired in 2.5 & earlier.
p q
– Will be discussed later
• Note
– Can cut/paste or drag/drop files into appropriate locations
15
Testing New App
• Follow same procedure as “deploying app”
f i i
f
rom prev
i
ous sect
i
on
– Deploy project

Select

Servers

tab at bottom
Select

Servers

tab

at

bottom
• R-click on Tomcat
• Choose “Add and Remove”

Choose project

Choose

project
• Press “Add”
• Click “Finish”
Start Server

Start

Server
• R-click Tomcat at bottom
• Restart (use “Start” if Tomcat not already running)
– Test URL
• http://localhost/appName/ in any Web browser
16
© 2010 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, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
17
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
18
Accessing the Online
Documentation
Documentation
• Servlets and JSP
htt//d l t/l t
3 0
i/

htt
p:
//d
ocs.coreserv
l
e
t
s.com
/
serv
l
e
t
-
3
.
0
-ap
i/
• Servlets 3.0 and JSP 2.2 (Tomcat 7)
– http://java.sun.com/products/servlet/2.5/docs/servlet-2_5-mr2/
S l t 2 5 (T t 6)

S
erv
l
e
t
s
2
.
5

(T
omca
t

6)
– http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/
• JSP 2.1 (Tomcat 6)
J 6

J
ava
6
– http://java.sun.com/javase/6/docs/api/

C
l
ass

uses

Ja
v
a

6

a
n
d
T
o
m
cat
7
Cass uses Ja a 6 a d o cat
• 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
19
A Sample Servlet (Code)
@WebServlet("/test1")
public class
TestServlet
extends HttpServlet {
public

class

TestServlet
extends

HttpServlet

{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException IOException {
throws

ServletException
,
IOException

{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println
out.println
("<!DOCTYPE html>\n" +
"<html>\n" +
"<h
ead
><
t
i
t
l
e
>A T
est

Se
rvl
et
<
/t
i
t
l
e
><
/
h
ead
>
\
n" +
ead t t e est Se et/t t e/ead
\
"<body bgcolor=\"#fdf5e6\">\n" +
"<h1>Test</h1>\n" +
"<
p
>Sim
p
le servlet for testin
g
.<
/p
>
\
n" +
p p g/p
\
"</body></html>");
}
}
20
A Sample Servlet (Result)
Screenshot assumes project is named “review”. Code for this app can be downloaded from the tutorial Web site.
Eclipse users can use the TestServlet code as a basis for their own servlets.
A
void usin
g
“New Servlet” in Ecli
p
se since it results in u
g
l
y
code.
21
g
p
g y
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
22
© 2010 Marty Hall
Giving URLs to Servlets
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
23
Tomcat 7 or Other Servlet 3.0
Containers
Containers
• Give address with @WebServlet
@WebServlet("
/
my-address")
public class MyServlet extends HttpServlet { … }
– Resulting URL
• http://hostName/appName/my-address
• Omit web.xml entirely
You are permitted to use web xml even when using

You

are

permitted

to

use

web
.
xml

even

when

using

@WebServlet, but the entire file is completely optional.
• In earlier versions, you must have a web.xml file even if
th t th th th i t t d d t
th
ere were no
t
ags o
th
er
th
an
th
e ma
i
n s
t
ar
t
an
d
en
d

t
ags
(<web-app …> and </web-app>).
24
Example: URLs with
@WebServlet
@WebServlet
package coreservlets;


@WebServlet("/test1")
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response getWriter();
PrintWriter

out

=

response
.
getWriter();
out.println
("<!DOCTYPE html>\n" +
…);
}
}
25
Defining Custom URLs in
web xml (Servlets 2 5 & Earlier)
web
.
xml

(Servlets

2
.
5

&

Earlier)
• 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>/my-address</url-pattern>
<
/servlet-ma
pp
in
g
>
pp g
• Resultant URL
– http://hostname/appName/my-address
26
Defining Custom URLs: Example
<?xml version="1.0" encoding="UTF-8"?>
<web
-
app version=
"
2 4
"
Don't edit this manually.
Should match version supported
by your server If your server
<web
app

version= 2
.
4
... >
<!
--
Use the URL http://hostName/appName
/test2
for
by your server
.
If your server
supports 3.0, can omit web.xml
totally and use annotations.
<!
Use

the

URL

http://hostName/appName
/test2
for
testPackage.TestServlet -->
<servlet>
<servlet-name>Test</servlet-name
>
Fully qualified classname.
<servlet-class>coreservlets.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
Any arbitrary name.
But must be the same both times.
<servlet-name>Test</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
The part of the URL that comes after the app (project) name.
</web-app>
27
Should start with a slash.
Defining Custom URLs: Result
• Eclipse details
f li j i i

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

Deployed by right
-
clicking on Tomcat Add and Remove

Deployed

by

right
-
clicking

on

Tomcat
,
Add

and

Remove

Projects, Add, choosing review project, Finish,
right-clicking again, Start (or Restart)
28
© 2010 Marty Hall
F D t
F
orm
D
a
t
a
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
29
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 “name” attributes
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
30
An HTML Form With Three
Parameters
Parameters
<FORM ACTION="three-params">
First Parameter:<INPUT TYPE
="
TEXT
"
NAME
="
param1
"
><BR>
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>
31
• Project name is “review”
• Form installed in WebContent/three-params-form.html
Reading the Three Parameters
@WebServlet("three-params")
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>: "
+ re
q
uest.
g
etParameter("
p
aram1") + "\n" +
q g p
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ re
q
uest.
g
etParameter
(
"
p
aram3"
)
+ "\n" +
q g ( p )
"</UL>\n" +
"</BODY></HTML>");
}
}
32
Reading Three Parameters:
Result
Result
33
© 2010 Marty Hall
JSP S i ti
JSP

S
cr
i
p
ti
ng
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
34
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
35
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.
36
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.
37
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().
38
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
();%>

<%

String

queryData
=

request
.
getQueryString
();

%>
Attached GET data: <%= queryData %>
– <% response.setContentType("text/plain"); %>
• XML-compatible syntax
– <jsp:scriptlet>Java Code</jsp:scriptlet>
39
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>
40
© 2010 Marty Hall
JSP Pages with
JSP

Pages

with

XML S
y
ntax
y
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
41
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
42
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.
43
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.
44
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
45
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;%
<H2>Num3: <%= num3 %></H2>
</
CENTER
>
/
</BODY></HTML>
46
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>
47
Sample Pages: Results
48
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>
49
© 2010 Marty Hall
j i l d
j
sp:
i
nc
l
u
d
e
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
50
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
ofincl dedJSPpage 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
51
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 Js
p
News.com</TABLE
>
p
<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>
52
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.

This style of having servlets or JSP pages build only small
This

style

of

having

servlets

or

JSP

pages

build

only

small

pieces of HTML (or other data types) is even more widely
used in Ajax programming
53
A News Headline Page: Result
54
© 2010 Marty Hall
MVC
MVC
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
55
MVC Flow of Control
HTML or JSP
Java Code
(Business Logic)
R l
Form
Servlet
submit form
(Form ACTION matches
url-pattern of servlet)
R
esu
l
ts
(beans)
(Store beans in request,
session, or application scope)
re
q
uest.setAttribute
(
"customer"
,

JSP
q (,
currentCustomer);
JSP
1
JSP
2
JSP
3
(Extract data from beans
and
p
ut in out
p
ut
)
56
p p )
${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
57
Request-Based Sharing: Bean
package coreservlets;
public class NumberBean {
private final double num;
public NumberBean(double number) {
this.num = number;
}
}
public double getNumber() {
r
etu
rn
(
n
u
m
);
etu ( u );
}
}
The property name in JSP will be

number

. The property name is derived from the method name, not from
58
The property name in JSP will be number. The property name is derived from the method name, not from
the instance variable name. Also note the lack of a corresponding setter.
Request-Based Sharing: Servlet
@WebServlet("/random-number")
public class
RandomNumberServlet
extends HttpServlet {
public

class

RandomNumberServlet
extends

HttpServlet

{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws
ServletException
,
IOException
{
throws

ServletException
,

IOException
{
NumberBean bean =
RanUtils.randomNum(request.getParameter("range"));
re
q
uest.setAttribute
(
"randomNum"
,
bean
);
q
(
,);
String address = "/WEB-INF/mvc-sharing/RandomNum.jsp";
RequestDispatcher dispatcher =
re
q
uest.
g
etRe
q
uestDis
p
atcher(address);
q g q p
dispatcher.forward(request, response);
}
}
59
Request-Based Sharing:
Business Logic
Business

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

static

NumberBean
randomNum
(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));
}
private RanUtils() {} // Uninstantiable class
}
60
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
...
The web.xml file is not needed with servlets 3.0, and the downloadable

review

project does not have this file However for those who are using
61
review project does not have this file
.
However
,
for those who are using
containers that support only servlets 2.5 or 2.4, a “review2” app is also online.
That app uses web.xml instead of @WebServlet for all of the URL patterns.
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>
...
62
Request-Based Sharing:
Results Page
Results

Page

<body>
<body>
<h2>Random Number: ${randomNum.number}</h2>
</body></html>
63
Request-Based Sharing:
Results
Results
64
Summary
• Set up Java 6, Tomcat, and Eclipse
S htt//l t/A h
T t
T t i l/

S
ee
htt
p:
//
www.coreserv
l
e
t
s.com
/A
pac
h
e-
T
omca
t
-
T
u
t
or
i
a
l/
• Give custom URLs to all servlets
– Servlets 3.0
• Use @WebServlet annotation
– Servlets 2.5 and 2.4
• Use servlet, servlet-mapping, and url-pattern in web.xml
F

F
orms
– Use relative URLs for “action”.
– Read parameters with request.getParameter
• JSP Scripting
– If you use scripting, put most Java code in regular classes

MVC
MVC
– Very widely applicable approach.
– Consider using it in many (most?) applications
65
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
66