You are on page 1of 32

© 2009 Marty Hall

Servlet and JSP


Review

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
2 Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2009 Marty Hall

For live Ajax & GWT training, see training


courses att http://courses.coreservlets.com/.
htt // l t /
Taught by the author of Core Servlets and JSP, More
Servlets and JSP,
JSP and this tutorial.
tutorial Available at public
venues, or customized versions can be held on-site at
your organization.
• Courses
C d
developed
l d and
d ttaught
ht b
by M
Marty
t HHallll
– Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics
Customized
– Ajax courses Java
can concentrate on EE Training:
one library http://courses.coreservlets.com/
(jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several
• Courses developed and taught by coreservlets.com experts (edited by Marty)
Servlets, –JSP, JSFHibernate/JPA,
Spring, 1.x & JSF 2.0,
EJB3,Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Ruby/Rails
Developed and taught by well-known author
Contact and developer. At public
hall@coreservlets.com venues or onsite at your location.
for 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

© 2009 Marty Hall

S
Servlet
l t Basics
B i

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
5 Developed and taught by well-known author and developer. At public venues or onsite at your location.
A Servlet’s Job
• Read explicit data sent by client
– Form
F ddata
t
• Read implicit data sent by client
– Request
q headers
• Generate the results
• Send the explicit data back to client
– HTML or XML or JSON or custom
t ddata
t fformatt
• Send the implicit data to client
– Status codes and response
p headers

Accessing the Online


Documentation
• Servlets and JSP
– http://java.sun.com/products/servlet/2.5/docs/servlet-2_5-mr2/
htt //j / d t/ l t/2 5/d / l t 2 5 2/
– http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/
p p g p
– http://tomcat.apache.org/tomcat-5.5-doc/servletapi/
– http://tomcat.apache.org/tomcat-5.5-doc/jspapi/
• Java 6 or Java 5
– http://java.sun.com/javase/6/docs/api/
htt //j /j /6/d / 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
– 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//EN\">\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 you make
k th
the web.xml
b l entries
t i ffrom th
the upcoming
i slides,
lid you could
ld also
l use
the URL http://localhost/intro/hi2

9
© 2009 Marty Hall

Testing with
Eclipse

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
10 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Installing Eclipse
• Overview
–E
Eclipse
li is
i a free
f open-source development
d l environment
i
with support for Java and many other languages
• Downloading
g
– http://www.eclipse.org/downloads/
• Choose “Eclipse IDE for Java EE Developers”
• As of 12/2008, version 3.4, called Eclipse Ganymede
• Installing
– Unzip into directory of your choice
– Put
P shortcut
h to eclipse.exe
li on your desktop
d k
• Integrating Tomcat in Eclipse
– http://www
http://www.coreservlets.com/
coreservlets com/
Apache-Tomcat-Tutorial/eclipse.html
11
Configuring Eclipse
• Make sure Eclipse
k
knows about
b T
Tomcat
– Click on Servers tab at bottom.
R-click in window.
window
– New, Server, Apache, Tomcat v6.0,
Next, navigate to folder, Finish.
• Suppress unnecessary
compiler warnings
– Wi d  Preferences
Window P f 
Java  Compiler 
Errors/Warnings
g
• Change “Serializable class
without ...” to “Ignore”
12

Making Web Apps in Eclipse


• Make empty project
– File  New  Project 
Web  Dynamic Web Project
– Give it a name (e.g.,
(e g “test”)
test )
– Accept all other defaults
• Shortcut
– If you have made Dynamic
Web Project recently in
workspace you can just do
workspace,
File  New 
Dynamic Web Project

13
Adding Code to Eclipse Projects
• Locations
– src
• Unpackaged Java code
• Packages strongly recommended
– src/somePackage
• Java code in somePackage package
– WebContent
• Web files ((HTML, JavaScript,
p
CSS, JSP, images, etc.)
– WebContent/some-subdirectory
• Web content in subdirectory
– WebContent/WEB-INF
W bC t t/WEB INF
• web.xml (will be discussed later)
• Can also click on
“Deployment
p y Descriptor”
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”
Start
• Verify server startup
– 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
Eclipse
p workspace.
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
Add and Remove Projects”
Projects
– Choose project
– Press “Add”
– Click “Finish”
• Restart
Server
– R-click Tomcat
at bottom
– Restart
16

Testing Deployed Apps in Eclipse


• Start a browser
– Eclipse also has builtin browser,
browser
but I prefer to use Firefox or
Internet Explorer
• Test base URL
– http://localhost/test/
• Test Web content
– http://localhost/test/Hello
http://localhost/test/Hello.html
html
(case sensitive!)
– http://localhost/test/Hello.jsp
– If you used subd
subdirectories
ecto es
• http://localhost/test/
some-subdirectory/blah.html
• Test servlets
– http://localhost/test/servlet/HelloServlet
– http://localhost/test/servlet/coreservlets.HelloServlet2
17 • Note: custom URLs discussed in next section
Defining Custom URLs
• Java code
package myPackage; ...
public class MyServlet extends HttpServlet { ... }
• web.xml entry (in <web-app...>...</web-app>)
– Give
Gi name to
t servlet
l 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-name>MyName</servlet-name>
<url-pattern>/MyAddress</url-pattern>
</servlet-mapping>
pp g
• Resultant URL
– http://hostname/webappPrefix/MyAddress
18

Defining Custom URLs: Example


(Assume Eclipse Project is "test")
test )
<?xml version="1.0" encoding="UTF-8"?> Don't edit this manually.
<web-app
<web app Should refer to version 2.4
or 2.5 (Tomcat 6 only).
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
...
version="2.5">

<!-- Use the URL http://hostname/intro/hi instead


of http://hostname/intro/servlet/HelloServlet -->
<servlet>
<servlet-name>Second Hello Servlet</servlet-name>
<servlet-class>coreservlets.HelloServlet2</servlet-class>
</servlet> Fully qualified classname. Any arbitrary name.
<servlet-mapping> But must be the same both times.
<servlet-name>Second Hello Servlet</servlet-name>
< l
<url-pattern>/hi2</url-pattern>
tt >/hi2</ l tt >
</servlet-mapping> The part of the URL that comes after the app (project) name.
</web-app> Should start with a slash.
19
Defining Custom URLs: Result

• Eclipse details
– Name off Eclipse
li project
j is i “test”
– Servlet is in src/coreservlets/HelloServlet2.java
– Deployed by right-clicking on Tomcat,
Tomcat Add and Remove
Projects, Add, choosing test project, Finish, right-clicking
20
again, Start

Debugging Servlets
• Use print statements; run server on desktop
• Use Apache Log4J
• Integrated debugger in IDE
– Right-click in left margin in source to set breakpoint (Eclipse)
– R
R-click
click Tomcat and use “Debug”
Debug instead of “Start”
Start
• Look at the HTML source
• Return error pages to the client
– Plan ahead for missingg or malformed data
• Use the log file
– log("message") or log("message", Throwable)
• Separate
p the request
q and response
p data .
– 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
21
• Stop and restart the server
© 2009 Marty Hall

D l i to
Deploying t JHU

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
22 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Setup
• Install an sftp client
– Google “free sftp client”
• Eclipse also supports sftp via “Remote System Explorer”
perspective. See http://www.eclipse.org/dsdp/tm/
– I use filezilla,, but there are many
y reliable free clients that support
pp
drag-and-drop from your PC to remote server
• In FileZilla, File  Site Manager lets you save locations
• If you are prompted, sftp port is 22
• Find
Fi d the
th location
l ti Eclipse
E li uses for
f webapps
b
– Deploy a project, go to eclipse-workspace/.metadata/ and search for
a filename in that project
• O
On my system
t it is
i …\.metadata\.plugins\...\tmp1\wtpwebapps
\ t d t \ l i \ \t 1\ t b
• Can deploy project folder from here or deploy WAR file
• Learn to create WAR files from Eclipse
– R
R-click
li k project,
j t Export,
E t WAR file
fil
– You can deploy this WAR file to server or use project folder from
bullet above
23
Sending Apps to Tomcat on
web4 apl jhu edu
web4.apl.jhu.edu
• Make project starting with your name or ID
– E.g.,
E name your Eclipse
E li project
j t “hall-intro”
“h ll i t ”
– Use same naming scheme all semester
• Deploy from Eclipse and test at home
• http://localhost/hall-intro/Hello.jsp
• http://localhost/hall-intro/servlet/coreservlets.HelloServlet2
• Send app to web4
– Find project
• Find deployed project folder (e.g., “wtpwebapps/hall-intro”)
• Or, build WAR file (e.g., “hall-intro.war”)
– Connect to web4.apl.jhu.edu
– Copy project folder or WAR file to /usr/local/tomcat/webapps
– Test ((onlyy hostname changes!)
g )
• http://web4.apl.jhu.edu/hall-intro/Hello.jsp
• http://web4.apl.jhu.edu/hall-intro/servlet/coreservlets.HelloServlet2
24

Example: “intro” project


• On local PC
– R-click Servers, Add &
Remove Projects,
select intro, Restart
– http://localhost/intro/Hello.jsp
• Deploying
p y g to web4
– Started FileZilla
– Copied “intro” folder
from wtpwebapps to
/usr/local/tomcat/webapps
• On web4
– http://web4.apl.jhu.edu/
25
intro/Hello.jsp
© 2009 Marty Hall

F
Form Data
D t

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
26 Developed and taught by well-known author and developer. At public venues or onsite at your location.

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
– Should
Sh ld be
b installed
i t ll d under
d WebContent
W bC t t
• Servlet
– Calls request.getParameter
request getParameter with name as given in HTML
– Return value is entry as entered by end user
– Missingg values
• 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
<FORM ACTION="./show-params"> url-pattern of servlet
First Parameter: <INPUT TYPE="TEXT"
TYPE TEXT NAME NAME="param1"><BR>
param1 ><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>

• Project name is “review”


28 • 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>:
p "
+ 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-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>

30

Reading Three Parameters:


Result

31
© 2009 Marty Hall

JSP S
Scripting
i ti

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
32 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Uses of JSP Constructs

• Scripting elements calling servlet


Simple code directly
Application
• Scriptingg elements calling
g servlet
code indirectly (by means of utility
classes)
• Beans
B
• Servlet/JSP combo (MVC)
• MVC with
ith JSP expression
i language
l
Complex • Custom tags
Application • MVC with
ith beans,
b custom
t tags,
t andd
a framework like Struts or JSF
33
JSP Scripting Design Strategy:
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
• Why is the second option much better?
– Development.
p You write the separate
p class in a JJava
environment (editor or IDE), not an HTML environment
– Debugging. If you have syntax errors, you see them
immediately at compile time.
time Simple print statements can
be seen.
g You can write a test routine with a loop
– Testing. p that
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
evaluated, converted to String,
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() %>
– Your
Y hhostname:
t <%=
<% request.getRemoteHost()
t tR t H t() %>
• XML-compatible syntax
– <jsp:expression>Java Expression</jsp:expression>
– You cannot mix versions within a single page. You must
35
use XML for entire page if you use jsp:expression.
Predefined Variables
• request
– The HttpServletRequest (1st argument to service/doGet)
• response
– The
Th HttpServletResponse
H S l R (2nd
(2 d arg to service/doGet)
i /d G )
• out
– 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
– The ServletContext (for sharing data) as obtained via
36 getServletContext().

JSP Scriptlets
• Format
– <% Java Code %>
• Result
– Code
C d is
i inserted
i d verbatim
b i into
i servlet's
l ' _jspService
j S i
• Example
– <%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
– <% response.setContentType("text/plain"); %>
• XML
XML-compatible
compatible syntax
– <jsp:scriptlet>Java Code</jsp:scriptlet>
37
JSP Declarations
• Format
– <%! Java Code %>
• Result
– Code is inserted verbatim into servlet's class definition,
definition
outside of any existing methods
• Examples
p
– <%! private int someField = 5; %>
– <%! private void someMethod(...) {...} %>
• Design
D i consideration
id ti
– Fields are clearly useful. For methods, it is usually better
to define the method in a separate Java class.
• XML-compatible syntax
38 – <jsp:declaration>Java Code</jsp:declaration>

© 2009 Marty Hall

JSP Pages with


y
XML Syntax

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
39 Developed and taught by well-known author and developer. At public venues or onsite at your location.
Why Two Versions?
• Classic syntax is not XML-compatible
– <%= ... %>, <% ... %>, <%! ... %> are illegal in XML
– HTML 4 is not XML compatible either
– So,
So you cannot use XML editors like XML Spy
• You might use JSP in XML environments
– To build xhtml pages
– To build regular XML documents
• You can use classic syntax to build XML documents, but it
i sometimes
is ti easier
i if you are working
ki iin XML tto start
t t with
ith
– For Web services
– For Ajax applications
• So, there is a second syntax
– Following XML rules
40

XML Syntax for Generating XHTML


Files (somefile
(somefile.jspx)
jspx)
<?xml version="1.0" encoding="UTF-8" ?> The jsp namespace is required if you
use jsp:blah commands. You can use
<html xmlns:jsp="http://java.sun.com/JSP/Page">
mlns jsp "http //ja a s n com/JSP/Page"> other namespaces for other custom tag
libraries.
<jsp:output
Needed because of Internet Explorer bug where xhtml pages
omit-xml-declaration="true" that have the XML declaration at the top run in quirks mode.
doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" Builds DOCTYPE line.

doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<jsp:directive.page contentType="text/html"/>
For JSP pages in XML syntax, default content
<head><title>Some Title</title></head> type is text/xml.
body bgcolor
<body bgcolor="#fdf5e6">
#fdf5e6
Body
</body></html> Normal xhtml content, plus JSP commands that use
jjsp:blah
p syntax,
y pplus JSP custom tagg libraries.

41
XML Syntax for Generating Regular
XML Files (somefile.jspx)
(somefile jspx)
<?xml version="1.0" encoding="UTF-8" ?>
<your-root-element xmlns:jsp="http://java.sun.com/JSP/Page">
// / S /
<your-tag1>foo</your-tag1>
<your tag2>bar</your tag2>
<your-tag2>bar</your-tag2>
<your-root-element>

• Uses
U
– When you are sending to client that expects real XML
• Ajax
j
• Web services
• Custom clients
– Note
• 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
(somefile.jspx)
jspx)
• 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
– Usually
U ll nott worth
th the
th bother
b th

43
Sample HTML 4 Page: Classic
Syntax (sample
(sample.jsp)
jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD ...">
<HTML>
<HEAD><TITLE>Sample (Classic Syntax)</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>Sample (Classic Syntax)</H1>

<H2>Num1: <%
<%= Math.random()
Math.random()*10
10 %></H2>
<% double num2 = Math.random()*100; %>
<H2>Num2: <%= num2 %></H2>
<%!
%! private
p ate double
doub e num3
u 3 = Math.random()*1000;
at . a do () 000; %%>
<H2>Num3: <%= num3 %></H2>

</CENTER>
/
</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">
<div
di align="center">
li
<h1>Sample (XML Syntax)</h1>
<h2>Num1: <jsp:expression>Math.random()*10</jsp:expression></h2>
<jsp:scriptlet>
d bl num2
double 2 = MMath.random()*100;
th d ()*100
</jsp:scriptlet>
<h2>Num2: <jsp:expression>num2</jsp:expression></h2>
<jsp:declaration>
private
i t d double
bl num3 3 = M
Math.random()*1000;
th d ()*1000
</jsp:declaration>
<h2>Num3: <jsp:expression>num3</jsp:expression></h2>
45
</div></body></html>
Sample Pages: Results

46

XML Document Generated with


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
jsp:include
i l d

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
48 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Including Files at Request Time:


jsp:include
• Format
– <jsp:include page="Relative URL" />
• Purpose
–TTo reuse JSP,
JSP HTML
HTML, or plain
l i text
t t content
t t
– To permit updates to the included content without
changing the main JSP page(s)
• Notes
– JSP content cannot affect main page:
onl output
only t t of incl
included
ded JSP page is used
sed
– Don't forget that trailing slash
– Relative URLs that starts with slashes are interpreted
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)

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
p
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
<LI><jsp:include
i l d page="/WEB-INF/includes/item3.jsp"
"/WEB INF/i l d /it 3 j " />
</OL>
</BODY></HTML>

50

A News Headline Page,


Continued (First Included Page)
<B>Bill Gates acts humble.</B> In a startling
and unexpected development
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>

– Note that the ppage


g is not a complete
p HTML document;; it
has only the tags appropriate to the place that it will be
inserted

51
A News Headline Page: Result

52

© 2009 Marty Hall

MVC

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
53 Developed and taught by well-known author and developer. At public venues or onsite at your location.
MVC Flow of Control

HTML or JSP
Java Code
(Business Logic)
R l
Results
(beans)
submit form
Servlet
Form (URL matches url-
pattern of servlet)
(Store beans in
request, session, or
pp
application scope)
p )

JSP1
JSP2
JSP3
(Extract data from beans
and put in output. Pages
usually under WEB-INF.)

Eg: request.setAttribute("customer", customerObject);

Eg: ${customer.firstName}

54

Simple MVC Example:


Request-Scoped Data
• Goal
– Display a random number to the user

• Type of sharing
– Each request should result in a new number, so request-
based sharingg is appropriate.
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() {


etu ( u );
return(num);
}

public void setNumber(double


p ( number)
) {
num = number;
}
56 }

Request-Based Sharing: Servlet


public class RandomNumberServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
request
HttpServletResponse response)
throws ServletException, IOException {
NumberBean bean =
RanUtils.getRandomNum(request.getParameter("range"));
request.setAttribute("randomNum", bean);
String
g address = "/WEB-INF/mvc-sharing/RandomNum.jsp";
/ / g/ j p ;
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request,
p q response);
p
}
}

57
Request-Based Sharing:
Business Logic
public class RanUtils {
public static NumberBean getRandomNum(String rangeString) {
double range;
try {
range = Double.parseDouble(rangeString);
} catch(Exception e) {
range = 10.0;
}
return(new NumberBean(Math.random() * range));
}
}

58

Request-Based Sharing:
URL Pattern (web
(web.xml)
xml)
...
<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>
</servlet-mapping>
/se et app g
...

59
Request-Based Sharing:
Input Form
...
<fieldset>
<legend>Random Number</legend>
<form action="./random-number">
Range: <input type="text"
type= text name=
name="range"><br/>
range ><br/>
<input type="submit" value="Show Number">
</form>
</fieldset>
...

60

Request-Based Sharing:
Results Page

<body>
<h2>Random Number: ${randomNum.number}</h2>
</body></html>

61
Request-Based Sharing:
Results

62

Summary
• Set up Java 6, Tomcat, and Eclipse
– hhttp://www.coreservlets.com/
// l /
Apache-Tomcat-Tutorial/eclipse.html
• Give custom URLs to all servlets
– Use servlet, servlet-mapping, and url-pattern in web.xml
• Forms
–UUse relative
l ti URLs
URL for
f ACTION.
ACTION
– Read parameters with request.getParameter
• JSP Scripting
– If you use scripting, put most Java code in regular classes
• MVC
– Very widely
id l applicable
li bl approach.h
– Consider using it in many (most?) applications
63
© 2009 Marty Hall

Questions?

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
64 Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like