1
Web Programming with Java
Servlets
Huynh Huu Viet
University of Information Technology
Department of Information Systems
Email:
2008 © Department of Information Systems - University of Information Technology
2
Outline
Introduction
Overview of Servlet technology
Servlet basics
The Servlet Lifecycle
Retrieving and Sending HTML
Servlet Sessions
2008 © Department of Information Systems - University of Information Technology
3
Introduction
Java networking capabilities:
Socket-based and packet-based
communications
• Package java.net
Remote Method Invocation (RMI)
• Package java.rmi
Servlets and JavaServer Pages (JSP)
• Request-response model
• Packages javax.servlet
– javax.servlet.http
– javax.servlet.jsp
the Web tier of J2EE
2008 © Department of Information Systems - University of Information Technology
4
Introduction (cont.)
Servlets
Thin clients
Request/response mechanism
Session-tracking capabilities
redirection/forwarding control
Servlets: small Java programs that
run on a web server
Just as applets run on browser
Provide web-based applications
Extends functionality of web server
2008 © Department of Information Systems - University of Information Technology
5
Outline
Introduction
Overview of Servlet technology
Servlet basics
The Servlet Lifecycle
Retrieving and Sending HTML
Servlet Sessions
2008 © Department of Information Systems - University of Information Technology
6
A Servlet's Job
Read explicit data sent by client (form
data)
Read implicit data sent by client (request
headers)
Generate the results
Send the explicit data back to client
(HTML or binary)
Send the implicit data back to client
(status codes and response headers)
2008 © Department of Information Systems - University of Information Technology
7
Why Build Web Pages Dynamically?
The web page is based on data given
by the user
results from search engines and order
confirmation pages at on-line stores
The web page is derived from data
that changes frequently
weather report or news headlines page
The web page uses information from
databases or other server-side
sources
e-commerce site can list current price and
availability
2008 © Department of Information Systems - University of Information Technology
8
Outline
Introduction
Overview of Servlet technology
Servlet basics
The Servlet Lifecycle
Retrieving and Sending HTML
Servlet Sessions
2008 © Department of Information Systems - University of Information Technology
9
Servlet Basics
Servlet container (or Servlet engine)
Server that executes a Servlet
Web servers and application servers
Netscape iPlanet Application Server
Microsoft’s Internet Information Server (IIS)
Apache HTTP Server
BEA’s WebLogic Application Server
IBM’s WebSphere Application Server
JBoss Application Server
2008 © Department of Information Systems - University of Information Technology
10
Servlet Architecture
2008 © Department of Information Systems - University of Information Technology
11
Creating a Servlet
Need to get Servlet libraries on CLASSPATH
Part of J2EE application server
Also come with Tomcat reference implementation
For a general Servlet you must subclass
javax.servlet.GenericServlet
Seldom do this
To process HTTP requests you subclass
javax.servlet.http.HttpServlet
Override doGet() or doPost() to handle GET and
POST requests from browser
2008 © Department of Information Systems - University of Information Technology
12
Processing Requests
Typical steps:
Read values from request
• HttpServletRequest req
Process and log as required
Write response to client
• HttpServletResponse res
HttpServletResponse has getWriter()
method
Returns a PrintWriter to write data to client
Data starts with content type
Use setContentType() before writing any data
E.g. res.setContentType("text/html");
2008 © Department of Information Systems - University of Information Technology
13
Example
2008 © Department of Information Systems - University of Information Technology
14
Outline
Introduction
Overview of Servlet technology
Servlet basics
The Servlet Lifecycle
Retrieving and Sending HTML
Servlet Sessions
2008 © Department of Information Systems - University of Information Technology
15
The Servlet Lifecycle
Init
Executed once when the servlet is first loaded.
Not called for each request.
Service
Called in a new thread by server for each request.
Dispatches to doGet, doPost, etc.
Do not override this method!
doGet, doPost, doXxx
Handles GET, POST, etc. requests.
Override these to provide desired behavior.
Destroy
Called when server deletes servlet instance.
Not called after each request.
2008 © Department of Information Systems - University of Information Technology
16
Why You Should Not Override service
The service method does other things
besides just calling doGet
You can add support for other services
later by adding doPut, doTrace, etc.
You can add support for modification
dates by adding a getLastModified method
The service method gives you automatic
support for:
• HEAD requests
• OPTIONS requests
• TRACE requests
Alternative: have doPost call doGet
2008 © Department of Information Systems - University of Information Technology
17
Outline
Introduction
Overview of Servlet technology
Servlet basics
The Servlet Lifecycle
Retrieving and Sending HTML
Form Data
Request Headers
Status Codes
Response Headers
Servlet Sessions
2008 © Department of Information Systems - University of Information Technology
18
Creating Form Data: HTML Forms
<HTML>
<HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using GET</H2>
You normally use a relative URL for the ACTION. This URL is just for testing because
<FORM ACTION="SomeProgram">
<CENTER>
First name:
I am running a test server that echoes the data it receives.
<INPUT TYPE="TEXT" NAME="firstName" VALUE="J. Random"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT"> <! Press this to submit form >
</CENTER>
</FORM>
</BODY>
</HTML>
2008 © Department of Information Systems - University of Information Technology
19
Reading Parameters
out.println(
"<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("firstName") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter(“lastName") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
2008 © Department of Information Systems - University of Information Technology
20
Reading Form Data
request.getParameter("name")
Returns URL-decoded value of first occurrence of
name in query string
Works identically for GET and POST requests
Returns null if no such parameter is in query data
request.getParameterValues("name")
Returns an array of the URL-decoded values of all
occurrences of name in query string
Returns a one-element array if param not repeated
Returns null if no such parameter is in query
request.getParameterNames() or
request.getParameterMap()
Returns Enumeration or Map of request params
Usually reserved for debugging
2008 © Department of Information Systems - University of Information Technology
21
Reading All Parameters
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
2008 © Department of Information Systems - University of Information Technology
22
Checking for Missing and Malformed Data
Missing
Field missing in form
• getParameter returns null
Field blank when form submitted
• getParameter returns an empty string (or possibly a
string with whitespace in it)
Must check for null before checking for empty string
• String param = request.getParameter("someName");
• if ((param == null) || (param.trim().equals(""))) {
– doSomethingForMissingValues( );
•} else {
– doSomethingWithParameter(param);
•}
Malformed
• Value is a nonempty string in the wrong format
2008 © Department of Information Systems - University of Information Technology
23
Handling Missing and Malformed Data
Use default values
Replace missing values with application-specific
standard values
Redisplay the form
Show the form again, with missing values flagged
Previously-entered values should be preserved
Four options to implement this
• Have the same servlet present the form, process the data,
and present the results.
• Have one servlet present the form; have a second servlet
process the data and present the results.
• Have a JSP page “manually” present the form; have a servlet
or JSP page process the data and present the results.
• Have a JSP page present the form, automatically filling in the
fields with values obtained from a data object. Have a servlet
or JSP page process the data and present the results
2008 © Department of Information Systems - University of Information Technology
24
Outline
Introduction
Overview of Servlet technology
Servlet basics
The Servlet Lifecycle
Retrieving and Sending HTML
Form Data
Request Headers
Status Codes
Response Headers
Servlet Sessions
2008 © Department of Information Systems - University of Information Technology
25
A Typical HTTP Request
GET /servlet/Search?keywords=servlets+jsp
HTTP/1.1
Accept: image/gif, image/jpg, */*
Accept-Encoding: gzip
Connection: Keep-Alive
Cookie: userID=id456578
Host: www.somebookstore.com
Referer: /> User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)