Documente Academic
Documente Profesional
Documente Cultură
Course Outline
Servlet Overview
Using Servlets
Writing Servlets
Saving State
Java Web Server Features
Appendix: CGI Tutorial
Appendix: FAQ
Inside the Exercises Handout
11/04/08 Copyright © 1997-8, Purple Technology Inc. 2
Section I
Servlet Overview
What Is A Servlet
A Java object
Plug-in for a web server
Replacement for CGI scripts
Can also be used to extend server as a plug-in
Full power of Java
Platform-independent
Database access
Fun to write
Server/Service/Servlet
server - a process running on a host
machine
Apache, Java Web Server
service - a protocol running on a port
HTTP, FTP
servlet - a module running inside a service
PhoneServlet
Servlet/Service/Server Diagram
Supported Servers
Java Web Server
Apache
Netscape
Many others (see web site)
Servlet Engines
IBM's ServletExpress
Live Software’s JRun
Servlet Security
Trusted Servlets (full access)
JWS Internal
Local (in the "servlets" directory)
Servlet Sandbox
Signed Network Servlets (full access)
Unsigned Network Servlets (limited access)
SSL in JWS
It works
Extra $$
https: supported
Digest Authentication supported
SSL 3 (client certificates) required
API Availability
Standard Java Extension API
From white paper: "This means that while it is not
part of the core Java framework which must always
be part of all products bearing the Java brand, it will
be made available with such products by their
vendors as an add-on package."
package javax.servlet.*, javax.servlet.http.*
Using Servlets
Loading Servlets
From CLASSPATH
includes <root>/classes/ on JWS
From <root>/servlets/ directory
not in classpath
servlets can be added or recompiled inside a running
server
class.initArgs file
From remote codebase
specified by URL
Remote Servlets
Three ways to configure
configure with Administration Tool
invoke inside a server-side include
configure inside a servlet chain
Loaded in a Servlet Sandbox
more later
What's In A Name
A servlet's name is its class name
if it's in the servlets directory
Or, you can assign it a name in the "Add
Servlet" admin tool
maps code word to servlet class
Name is usually a single word
possibly with a package name and dots
no other punctuation
Standard Servlets
DateServlet
echoes current date/time
EchoServlet
echoes CGI parameters (good for testing)
MailServlet
sends email in response to a CGI form
RedirectServlet
used by server to manage HTTP redirects
SessionServlet
used by server to manage sessions
Many more...
SSI Details
pass init parameters in servlet tag
pass servlet parameters in param tags
can specify codebase in servlet tag
e.g.
<servlet code=DateServlet.class
codebase=http://servlets.foo.com/
initParam1=val1 initParam2=val2>
<param name=serviceParam1 value=val3>
<param name=serviceParam2 value=val4>
</servlet>
URL invocation
Directly from browser as URL
http://www.myserver.com/servlet/MyServlet
From inside FORM tag as script
<FORM METHOD=POST
ACTION=”/servlet/MyServlet”>
...
</FORM>
From inside JHTML or JSP page
Uses “Page Compilation”
Compiles the jsp file into a servlet on the fly, then
executes it
11/04/08 Copyright © 1997-8, Purple Technology Inc. 30
Servlets and the Java Web Server
Writing Servlets
ServletRequest
passed to the service() method
contains lots of useful goodies…
Client info
URL info
Content info
Content itself
User-entered parameters
ServletRequest - Content
getInputStream()
Returns an input stream for reading binary data in
the request body.
getReader()
Returns a buffered reader for reading text in the
request body.
ServletRequest - Parameters
String getParameter(String)
Returns a string containing the lone value of the specified parameter,
or null if the parameter does not exist.
Was deprecated, but due to popular demand, it'll be undeprecated
String[ ] getParameterValues(String)
Returns the values of the specified parameter for the request as an
array of strings, or null if the named parameter does not exist.
For parameters with multiple values, like lists
Enumeration getParameterNames()
Returns the parameter names for this request as an enumeration of
strings, or an empty enumeration if there are no parameters or the
input stream is empty.
ServletResponse
Embodies the response
Basic use:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<HTML><BODY>Hello</BODY></HTML
>");
ServletResponse - Output
getWriter()
for writing text data
getOutputStream()
for writing binary data
or for writing multipart MIME
you must call setContentType() before
calling getWriter() or getOutputStream()
by default it's text/plain, which you don't want
HttpServlet methods
provides helper methods for HTTP methods
doGet (GET and HEAD)
doPost (POST)
doPut, doDelete (rare)
doTrace, doOptions (not overridden)
the service() method dispatches requests
to the do* methods
SimpleServlet (GET)
public class SimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// set header field first
res.setContentType("text/html");
// then get the writer and write the response data
PrintWriter out = res.getWriter();
out.println(
"<HEAD><TITLE> SimpleServlet
Output</TITLE></HEAD><BODY>");
out.println("<h1> SimpleServlet Output </h1>");
out.println("<P>This is output is from SimpleServlet.");
out.println("</BODY>");
out.close();
}
public String getServletInfo() { return "A simple servlet"; }
}
DateServlet
public class DateServlet extends HttpServlet {
public void service( HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
Date today = new Date();
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println(today.toString());
}
public String getServletInfo() {
return "Returns a string representation of the current
time";
}
}
11/04/08 Copyright © 1997-8, Purple Technology Inc. 52
From Java Web Server Tutorial by Sun Microsystems
Servlets and the Java Web Server
HelloHttpServlet
Reads in a parameter
Can use a form
<FORM METHOD=GET
ACTION=”/servlet/HelloHttpServlet”>
<INPUT NAME=name>
</FORM>
Can use right in a URL
http://localhost:8080/servlet/HelloHttpServlet?name=Fred
Outputs it as HTML
HelloHttpServlet
public class HelloHttpServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException
{
String name = req.getParameter("name");
if (name == null) name = "Joe";
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println("Hello, " + name + "!");
}
}
11/04/08 Copyright © 1997-8, Purple Technology Inc. 54
Servlets and the Java Web Server
HttpServletRequest
Cookie[ ] getCookies()
returns list of cookies sent by client
String getMethod()
GET, POST, etc.
String getRequestURI()
returns the URI or URL that was invoked
useful for putting inside <FORM> tag
HttpServletRequest (Cont.)
CGI Variable Methods
getServletPath(), getPathInfo(), getPathTranslated(),
getQueryString(), getRemoteUser(), getAuthType()
String getHeader(String name)
Session Management Methods
HttpSession getSession(boolean create)
More later...
HttpServletResponse
Contains HTTP status codes as constants
int HttpServletResponse.SC_NOT_FOUND = 404;
Can send Error or Status codes to client
Deals with Cookies
Deals with HTTP Headers
Can send HTTP Redirect to client
Init Details
if you fail, throw an UnavailableException
must call super.init(cfg), which saves off
cfg
if you like, you can save it yourself and override
getServletConfig, but why bother?
Can call getInitParameter(paramName) to
read from the server-side config file
Init Parameters
ServletConfig
String getInitParameter()
Enumeration getInitParameterNames()
There are convenience methods of the
same name inside GenericServlet
Init Parameters are set by the server
administrator
Servlet Parameters are set by the web page
ServletContext
call GenericServlet.getServletContext()
getServlets()
returns list of all installed Servlets
getServlet(String name)
returns the named Servlet
log()
see next slide
Logging
GenericServlet.log(String message)
Writes the name of your servlet, plus the message,
to the server log file
Location of log file is server-specific
on JWS, you can check in the Admin Tool
"If a servlet will have multiple instances (for example, if the
network service runs the servlet for multiple virtual hosts),
the servlet writer should override this method. The
specialized method should log an instance identifier, along
with the requested message." - Javadoc for GenericServlet
But usually, there is only one instance of each
servlet, called reentrantly by the web server
Servlet.getServletInfo()
You should override this method
Returns a string containing author, version,
copyright, etc.
Efficiency: KeepAlive
HTTP keepalive improves performance
Keeps connection alive across multiple HTTP
requests
Servlet must set content-length
You can write to a ByteArray or StringBuffer, then
get its length before writing it
res.setContentLength(sb.length());
out.print(sb);
KeepAlive should be enabled by default if all you
do is write short strings, then close the output
stream
but maybe not
Efficiency: getLastModified
long HttpServlet.getLastModified(
HttpServletRequest req )
Returns the time the requested entity was
last modified
difference in milliseconds between that time and
midnight, January 1, 1970
negative = unknown (or dynamic)
Improves performance on browser/proxy
caching
11/04/08 Copyright © 1997-8, Purple Technology Inc. 72
Section IV
Saving State
Hidden Fields
Save data inside the servlet, keyed to a
handle
Store a handle inside each successive
FORM
Use that handle to retrieve data each query
Of course, you could always store all the
data in hidden fields, instead
handle + “>”);
out.println( ... rest of form ... );
URL Rewriting
Change HREF and ACTION URLs on the fly
Change “/servlet/catalog” into
“/servlet/catalog?user=1234”
URL Rewriting
Pro:
Don’t need to use FORMs
Con
Lose user if he/she travels outside your web site
Need to use Servlet for all accesses -- can’t access a
raw HTML page
Database State
Session data stored in a database
You should open a connection to the
database in your init() method, and close it
in your destroy() method
You can still use the hidden field technique
When you get a handle, you pull in the user
data via a DB query
C is for Cookie
What’s A Cookie?
Client-side storage
Server can drop arbitrary data on browser
Sent back to server on EVERY successive
request
Automatically expires
Cookies should be neither large nor
numerous
Browsers should support twenty cookies per host, of
at least four kilobytes each
11/04/08 Copyright © 1997-8, Purple Technology Inc. 88
Servlets and the Java Web Server
Cookie Uses
save session data
save handle to session data
store user preferences for next session
store user login information
not very secure, but appropriate for some
applications
javax.servlet.http.Cookie
get/setName()
get/setValue()
Attributes
Comment, Domain, MaxAge, Path, Secure, Version
Cookie Example
Cookie Counter Servlet
Counter.java
Session Objects
Server-side
One per client (not one per servlet)
Preserved automatically
even in browsers that don’t support cookies
Expire after 30 minutes (by default)
Saved to disk if server dies; restored if
server restarts
“Loosely speaking, a session corresponds
to a single sitting of a single anonymous
user” - JWS Tutorial
Using Sessions
HttpSession session = request.getSession
(true);
String info =
(String)session.getValue(“foo.info”);
// assume getNewInfo defined elsewhere
String newinfo = getNewInfo();
session.putValue(“foo.info”, newinfo);
// then output page
URL Rewriting
Preserves sessions on non-cookie browsers
Changes
<a href="/store/catalog">
into
<a
href="/store/catalog;$sessionid$DA32242SSG
E2">
You must actively call res.encodeUrl(“/store/catalog”)
see next slide
Does not work if user merely disables cookies
Has to actually
11/04/08 BE a©non-cookie
Copyright browserInc.
1997-8, Purple Technology 98
Lame
Servlets and the Java Web Server
HttpServletResponse - Encoding
Has methods to process URLs to splice in the session ID if
appropriate
Not the same as URLEncode / URLDecode
the server deals with that
String encodeUrl(String url)
rewrites the given URL if necessary
if the browser supports cookies, returns URL unchanged
All URLs emitted by a session-using Servlet should be run through
this method
e.g.
out.println("<A HREF=\"" + resp.encodeUrl("next.html") + "\">");
also String encodeRedirectUrl(String url)
Session Persistence
Sessions swap to disk
When server shuts down
When memory fills up
Uses Java Serialization
Only works for Serializable or Externalizable
objects
“Note: Session persistence is intended to
be used as a means for preserving
Sessions across server restarts. It is not
meant to be used as a general long-term
session persistence mechanism.”
11/04/08 Copyright © 1997-8, Purple Technology Inc. 100
Servlets and the Java Web Server
Example
VectorSessionServlet.java
Bugs
Can’t use custom classes inside session
data
Doesn’t really detect whether client
supports cookies
Instead, detects whether browser can potentially
support cookies
Lame - they should use my CookieDetector
technique
Administration Tools
Play with Admin Tool
http://localhost:9090/
Click on a service, click “Manage” button
To shut down server, click “Shut Down”
Manage Servlets
Add
Properties
Load on Startup
Unload
Servlet Aliases
Specify a partial URL
Map it to a particular servlet
e.g.
you want http://foo.com/lunch to execute
/servlets/meal?type=lunch
set alias = /lunch
set servlet invoked = meal?type=lunch
HTML Templates
Define standard look for all (or some) pages
Template Servlet
A tag inside template page inserts section
from original page
<subst data="HEAD"></subst>
<subst data="BODY"></subst>
Specify which files are templated via
Servlet Aliases in Admin Tool
Session Tracking
See above
Servlet Beans
Using Servlets That are Beans
Changes to config file are instantly updated
Servlet itself is persistent across server restarts
instance variables, like counters or caches, are
preserved
Calling JavaBeans from Servlets
Invisible Beans
Installed inside “lib” subdirectory
Calling JavaBeans in JHTML/JSP Files
FAQ
Answers in the Exercises book
How do I develop using the servlet classes without
installing JDK1.2?
Is it the “servlets” directory or the “servlet” directory
Why doesn’t my servlet work inside a <SERVLET>
tag?
How do I support both GET and POST protocol
from the same Servlet?
How do I fully shut down the server?
My browser says “the server returned an invalid or
unrecognized response” – what gives?
11/04/08 Copyright © 1997-8, Purple Technology Inc. 112
Servlets and the Java Web Server
References
Java Server 1.1
http://java.sun.com/javastore/jserv/buy_try.html
http://java.sun.com/products/java-server/index.html
be sure to download the JWS documentation
The home for servlets and the Java Web Server.
http://jserv.javasoft.com
The Java Web Server 1.1 is available for trial or purchase.
http://java.sun.com/javastore/jserv/buy_try.html
The Java Web Server 1.1.1 upgrade pack is available for free.
http://java.sun.com/products/java-server/webserver/jws111.html
The Java Server Pages preview pack is available for free.
http://developer.javasoft.com/developer/earlyAccess/jws-
preview.html
References
RFC2045 - MIME
http://info.internet.isi.edu/in-notes/rfc/files/rfc2045.txt
RFC 2109 - Cookies
http://info.internet.isi.edu/in-notes/rfc/files/rfc2109.txt
Live Software
http://www.livesoftware.com/
JRun, many commercial servlets
ATG - Dynamo Web Application Server
http://www.atg.com/
References
Advanced Web Technologies
http://www.javatrain.com/
Purple Technology
http://www.purpletech.com/
Gamelan
http://java.developer.com/
What Is CGI?
Common Gateway Interface
Allows web pages to send parameters to
web server
Use HTML forms on client side
Can also use Java – it's just a protocol!
Use scripts on server side
Can use Servlets!
CGI Flow
Browser downloads HTML page containing
FORM tag
Browser lays out input widgets
User fills out form and clicks "Submit"
Browser takes parameters and sends them
in CGI format
INPUT TYPE=text
Specifies a text field
NAME
names parameter to be passed to script
VALUE (optional)
initial value for text
INPUT TYPE=textarea
Specifies a multi-line text area
NAME
names parameter to be passed to script
…
INPUT TYPE=checkbox
Specifies a check box (duh)
NAME
names parameter to be passed to script
ISCHECKED=true
default value on
INPUT TYPE=radio
Specifies a radio button (or grouped
checkbox)
NAME
names group of buttons
VALUE
specifies the value for the group
e.g.
<INPUT TYPE=radio NAME="gender"
VALUE="male">Male
<INPUT TYPE=radio NAME="gender"
VALUE="female">Female
INPUT TYPE=submit
A push button that submits the form
NAME
specifies name of variable
VALUE
specifies name of button
yes, "value" specifies the name
hey, I didn't write the spec
INPUT TYPE=reset
A push button that clears the form
Does not submit it