Sunteți pe pagina 1din 127

Servlets and the Java Web Server

Server-Side Programming Made Easy

Written by Alex Chaffee (alexc@purpletech.com)


Contents Copyright (c) 1998 Purple Technology, Inc.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 1


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 3


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 4


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 5


Servlets and the Java Web Server

Servlet/Service/Server Diagram

 (diagram from Java Web Server tutorial)

11/04/08 Copyright © 1997-8, Purple Technology Inc. 6


Servlets and the Java Web Server

Servlets vs. Applets


 Servlets have no GUI
 Server-side, not client-side
 Different security model
 Installed, not downloaded
 But you can download remote servlets too
 Consistent server-side VM
 Much easier to test

11/04/08 Copyright © 1997-8, Purple Technology Inc. 7


Servlets and the Java Web Server

Servlets vs. CGI


 "performance, flexibility, portability, and
security" (whitepaper)
 Faster and Leaner
 No fork-process like Perl
 No need to initialize for each request
 Only lightweight thread context switching
 Built-in multithreading

11/04/08 Copyright © 1997-8, Purple Technology Inc. 8


Servlets and the Java Web Server

Servlets vs. CGI (Cont.)


 Easy to manage state
 share data across successive requests
 share data between concurrent requests
 use hidden fields, cookies, or sessions
 Write once, run anywhere
 It's easy to write unportable Perl
 Servlets have standard API
 Supports all methods
 GET, POST, PUT, DELETE, et al.
11/04/08 Copyright © 1997-8, Purple Technology Inc. 9
Servlets and the Java Web Server

Servlets vs. FastCGI


 FastCGI sends multiple requests to a single
separate process
 requires process context switch
 Servlets send multiple requests to multiple threads
in same process
 requires lightweight thread context switch
 (Also applies to ISAPI)
 Nice diagram in White Paper
 Servlets also automatically take advantage of
multiprocessors
 if the underlying JVM does
11/04/08 Copyright © 1997-8, Purple Technology Inc. 10
Servlets and the Java Web Server

Supported Servers
 Java Web Server
 Apache
 Netscape
 Many others (see web site)
 Servlet Engines
 IBM's ServletExpress
 Live Software’s JRun

11/04/08 Copyright © 1997-8, Purple Technology Inc. 11


Servlets and the Java Web Server

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)

11/04/08 Copyright © 1997-8, Purple Technology Inc. 12


Servlets and the Java Web Server

Servlet Security: Implications


 IT managers can sign servlets for use in
their organization
 ISPs can allow users to run servlets
 less of a security hole than CGI scripts, since Java is
safe and secure (at least more so than C or Perl)
 still allows denial-of-service attacks
 Network servlets are possible
 chaining / proxying
 allows agents
 common servlet repository for multiple servers
 one place to install updates

11/04/08 Copyright © 1997-8, Purple Technology Inc. 13


Servlets and the Java Web Server

Servlet Security: Problems


 Too simplistic
 All or nothing
 Should allow ACLs for particular signers
 They claim it will in a future version
 Should get better with 1.2 security model
 Finer-grained access control

11/04/08 Copyright © 1997-8, Purple Technology Inc. 14


Servlets and the Java Web Server

Servlet Client Security


 Java Web Server
 Allows Access Control Lists for clients
 Supports HTTP authentication
 Supports Digest Authentication
 Other Web Servers
 Usually support HTTP authentication
 May have other security features

11/04/08 Copyright © 1997-8, Purple Technology Inc. 15


Servlets and the Java Web Server

SSL in JWS
 It works
 Extra $$
 https: supported
 Digest Authentication supported
 SSL 3 (client certificates) required

11/04/08 Copyright © 1997-8, Purple Technology Inc. 16


Servlets and the Java Web Server

Authenticating the user’s identity


 HTTP Authentication
 Username/password sent to server on every request
(like cookies)
 Very light encryption (uuencode)
 Digest Authentication
 Cryptographic handshaking between client and
server
 Very good encryption
 Not supported by all servers/browsers

11/04/08 Copyright © 1997-8, Purple Technology Inc. 17


Servlets and the Java Web Server

User Authentication Methods


 request.getRemoteUser()
 returns username
 request.getAuthType()
 HTTP or Digest
 request.getScheme()
 “http” or “https”

11/04/08 Copyright © 1997-8, Purple Technology Inc. 18


Servlets and the Java Web Server

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.*

11/04/08 Copyright © 1997-8, Purple Technology Inc. 19


Servlets and the Java Web Server

Servlet Architectures:Three-tier system


 Tier 1: Client
 HTML browser
 Java client
 Tier 2: Servlets
 embody business logic
 secure, robust
 Tier 3: Data Sources
 Java can talk to SQL, CORBA, OODB, File system,
etc. etc.
11/04/08 Copyright © 1997-8, Purple Technology Inc. 20
Servlets and the Java Web Server

Servlet Architectures: N-tier system


 Tier 1: HTML Browser
 Tier 2: Servlet
 User interface
 Tier 3: EJB/CORBA/RMI Objects
 Business logic
 Tier 4: Other Servers (e.g. RDBMS)
 Data storage

11/04/08 Copyright © 1997-8, Purple Technology Inc. 21


Servlets and the Java Web Server

Servlet Architectures: Web Publishing


 SSI Servlets
 JSP Servlets
 Best to keep business logic inside Java objects
 Keep the JSP light so designers don’t get scared
 Chaining servlets
 Multiple servers
 data gathering, collecting, serving, load balancing,
etc.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 22


Section II

Using Servlets

11/04/08 Copyright © 1997-8, Purple Technology Inc. 23


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 24


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 25


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 26


Servlets and the Java Web Server

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...

11/04/08 Copyright © 1997-8, Purple Technology Inc. 27


Servlets and the Java Web Server

Server-side Includes (SSI)


 Must be in a file named .shtml or .jsp
 can change this with Admin Tool
 Normal SSI
 <!--#include file="foo.txt" -->
 Servlet SSI
 <servlet code=DateServlet.class>
 </servlet>

11/04/08 Copyright © 1997-8, Purple Technology Inc. 28


Servlets and the Java Web Server

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>

11/04/08 Copyright © 1997-8, Purple Technology Inc. 29


Servlets and the Java Web Server

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

A Note on CLASSPATH and JWS


 JWS uses its own JRE
 Three ways to add classes
 Put the class files into the “classes” subdirectory
 Jar them, and put the jar files into the “lib”
subdirectory
 Start the server with the -classpath option
httpd -classpath c:\projects\utils

11/04/08 Copyright © 1997-8, Purple Technology Inc. 31


Section III

Writing Servlets

11/04/08 Copyright © 1997-8, Purple Technology Inc. 32


Servlets and the Java Web Server

The Servlet API


 Independent of
 web protocol
 server brand or platform
 whether it's local or remote
 Simple, small, easy
 Base class provides core functionality; just
extend it

11/04/08 Copyright © 1997-8, Purple Technology Inc. 33


Servlets and the Java Web Server

CGI, or not, whichever


 Fairly generic interface
 Accepts query, returns response
 Used for plugins, etc.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 34


Servlets and the Java Web Server

Servlet Architecture Overview


 Servlet Interface
 methods to manage servlet
 GenericServlet
 implements Servlet interface
 HttpServlet
 extends GenericServlet
 exposes HTTP-specific functionality

11/04/08 Copyright © 1997-8, Purple Technology Inc. 35


Servlets and the Java Web Server

Servlet Architecture Overview


 ServletRequest
 What the client says to the server
 Access to information like protocol, client IP#,
parameters, and body
 ServletResponse
 What the servlet says to the client
 HttpServletRequest, HttpServletResponse
 HTTP-specific communication and information
 State-tracking and session management

11/04/08 Copyright © 1997-8, Purple Technology Inc. 36


Servlets and the Java Web Server

Servlet Lifecycle Overview


 Server loads and instantiates servlet
 Server calls init()
 Loop
 Server receives request from client
 Server calls service()
 service() calls doGet() or doPost()
 Server calls destroy()
 More detail to come later...

11/04/08 Copyright © 1997-8, Purple Technology Inc. 37


Servlets and the Java Web Server

ServletRequest
 passed to the service() method
 contains lots of useful goodies…
 Client info
 URL info
 Content info
 Content itself
 User-entered parameters

11/04/08 Copyright © 1997-8, Purple Technology Inc. 38


Servlets and the Java Web Server

ServletRequest - Client Info


 getRemoteAddr()
 Returns the IP address of the agent that sent the request
 getRemoteHost()
 Returns the fully qualified host name of the agent that
sent the request
 getProtocol()
 Returns the protocol and version of the request as a
string of the form <protocol>/<major version>.<minor
version>.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 39


Servlets and the Java Web Server

ServletRequest - URL Info


 getScheme()
 Returns the scheme of the URL used in this request, for
example "http", "https", or "ftp".
 getServerName()
 Returns the host name of the server that received the
request
 getServerPort()
 Returns the port number on which this request was
received
 getServletPath()
 Returns the URI path that got to this script, e.g.
“/servlet/com.foo.MyServlet”
 Useful for putting in a <FORM> tag
 See also getRequestURI()
11/04/08 Copyright © 1997-8, Purple(in HttpServletRequest)
Technology Inc. 40
Servlets and the Java Web Server

ServletRequest - Content Info


 getContentLength()
 Returns the size of the request data
 getContentType()
 Returns the MIME type of the request data

11/04/08 Copyright © 1997-8, Purple Technology Inc. 41


Servlets and the Java Web Server

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.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 42


Servlets and the Java Web Server

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.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 43


Servlets and the Java Web Server

ServletResponse
 Embodies the response
 Basic use:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<HTML><BODY>Hello</BODY></HTML
>");

11/04/08 Copyright © 1997-8, Purple Technology Inc. 44


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 45


Servlets and the Java Web Server

The GenericServlet class


 implements Servlet
 also implements Serializable, ServletConfig
 implements all Servlet methods
 so you don't have to

11/04/08 Copyright © 1997-8, Purple Technology Inc. 46


Servlets and the Java Web Server

The HelloWorld Servlet


import javax.servlet.*;
import java.io.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest req,
ServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println("Hello, World!");
}
}
11/04/08 Copyright © 1997-8, Purple Technology Inc. 47
Servlets and the Java Web Server

The HttpServlet class


 extends the GenericServlet base class
 provides a framework for handling the
HTTP protocol
 has its own subclasses of ServletRequest
and ServletResponse that do HTTP things

11/04/08 Copyright © 1997-8, Purple Technology Inc. 48


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 49


Servlets and the Java Web Server

HttpServlet: Receiving Data


 getParameter / getParameterValues /
getParameterNames
 process the data and return you the parameters
 getQueryString
 for GET method
 returns a single string in url-encoded format
 getReader / getInputStream
 for POST, PUT, DELETE
 returns a stream of characters / bytes
 mutually exclusive
 use EITHER getParameter* OR one of the others (never
both)

11/04/08 Copyright © 1997-8, Purple Technology Inc. 50


Servlets and the Java Web Server

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"; }
}

11/04/08 Copyright © 1997-8, Purple Technology Inc. 51


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 53


Servlets and the Java Web Server

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

More Advanced Servlets


 See Post Servlet
 from Servlet Tutorial

11/04/08 Copyright © 1997-8, Purple Technology Inc. 55


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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 56


Servlets and the Java Web Server

HttpServletRequest (Cont.)
 CGI Variable Methods
 getServletPath(), getPathInfo(), getPathTranslated(),
getQueryString(), getRemoteUser(), getAuthType()
 String getHeader(String name)
 Session Management Methods
 HttpSession getSession(boolean create)
 More later...

11/04/08 Copyright © 1997-8, Purple Technology Inc. 57


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 58


Servlets and the Java Web Server

Servlet Lifecycle: Init()


 public void init(ServerConfig cfg)
 called once, when servlet loads
 don't worry about synchronization
 perform costly setup here, rather than once
per request
 open database connection(s)
 load in persistent data
 spawn background threads

11/04/08 Copyright © 1997-8, Purple Technology Inc. 59


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 60


Servlets and the Java Web Server

Servlet Lifecycle: Service


 public void service(ServletRequest req,
ServletResponse res)
 takes Request and Response objects
 called many times, once per request

11/04/08 Copyright © 1997-8, Purple Technology Inc. 61


Servlets and the Java Web Server

service() and Concurrency


 Might be called simultaneously in several
threads
 it is your responsibility to handle synchronized
access to shared resources
 It is possible to declare a servlet as single-
threaded
 implement SingleThreadModel (empty interface)
 performance will suffer (if there are multiple
simultaneous requests)
 You can use class-static data to share data
across successive or concurrent requests
11/04/08 Copyright © 1997-8, Purple Technology Inc. 62
Servlets and the Java Web Server

Servlet Lifecycle: Destroy


 public void destroy()
 takes no parameters
 you must clean up
 close database connections
 stop threads
 Afterwards, servlet may be garbage collected

11/04/08 Copyright © 1997-8, Purple Technology Inc. 63


Servlets and the Java Web Server

Servlet Lifecycle: Destroy Details


 The server calls destroy after all service calls have
been completed, or after a certain number of
seconds have passed, whichever comes first.
 Warning: other threads might be running service
requests, so be sure to synchronize, and/or wait
for them to quit
 Sun's Servlet Tutorial has an example of how to do this
with reference counting
 Destroy can not throw an exception, so if
something bad happens, call log() with a helpful
message (like the exception)
 See “closing a JDBC connection” example in Tutorial

11/04/08 Copyright © 1997-8, Purple Technology Inc. 64


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 65


Servlets and the Java Web Server

ServletContext
 call GenericServlet.getServletContext()
 getServlets()
 returns list of all installed Servlets
 getServlet(String name)
 returns the named Servlet
 log()
 see next slide

11/04/08 Copyright © 1997-8, Purple Technology Inc. 66


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 67


Servlets and the Java Web Server

Servlet.getServletInfo()
 You should override this method
 Returns a string containing author, version,
copyright, etc.

11/04/08 Copyright © 1997-8, Purple Technology Inc. 68


Servlets and the Java Web Server

11/04/08 Copyright © 1997-8, Purple Technology Inc. 69


Servlets and the Java Web Server

HTTP Servlet Efficiency

11/04/08 Copyright © 1997-8, Purple Technology Inc. 70


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 71


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 73


Servlets and the Java Web Server

Saving State: Why


 Shopping Cart
 User Preferences
 “Wizard” interfaces
 i.e., successive linked dialog boxes / form entry
pages

11/04/08 Copyright © 1997-8, Purple Technology Inc. 74


Servlets and the Java Web Server

Saving State: How


 Client-side storage
 Hidden fields
 URL Rewriting
 Cookies
 Server-side storage
 Instance variables
 Database Access
 JWS Session Management
 Best possible solution (but still flawed)
11/04/08 Copyright © 1997-8, Purple Technology Inc. 75
Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 76


Servlets and the Java Web Server

Hidden Fields: Example


private Dictionary cache = new Hashtable();
public void doGet(...) {
String handle = getParameter(“handle”);
UserData data;
if (handle == null) {
data = new UserData();
handle = makeNewHandle(); // defined
elsewhere
cache.put( handle, data );
}
else
11/04/08data = (UserData)cache.get(handle);
Copyright © 1997-8, Purple Technology Inc. 77
Servlets and the Java Web Server

Hidden Fields: Example


out.println(“<FORM
ACTION=/servlet/Whatever>”);
out.println(
“<INPUT TYPE=hidden NAME=handle VALUE=”
+

handle + “>”);
out.println( ... rest of form ... );

11/04/08 Copyright © 1997-8, Purple Technology Inc. 78


Servlets and the Java Web Server

Hidden Fields: Example


 Survey.java

11/04/08 Copyright © 1997-8, Purple Technology Inc. 79


Servlets and the Java Web Server

Hidden Fields: Pros and Cons


 Pros
 Well understood
 You have control
 Can use your own caching mechanism

11/04/08 Copyright © 1997-8, Purple Technology Inc. 80


Servlets and the Java Web Server

Hidden Fields: Pros and Cons


 Cons
 Need to use FORMs
 hidden fields do not persist across normal links
 Sessions are not persistent across server restarts
 unless you write code to do it
 Sessions do not expire
 unless you write code to do it

11/04/08 Copyright © 1997-8, Purple Technology Inc. 81


Servlets and the Java Web Server

URL Rewriting
 Change HREF and ACTION URLs on the fly
 Change “/servlet/catalog” into
“/servlet/catalog?user=1234”

11/04/08 Copyright © 1997-8, Purple Technology Inc. 82


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 83


Servlets and the Java Web Server

Using Instance Variables for State


 Session data stored in instance variables
 directly is bad - not valid for multiple users
 indirectly is better - in a hashtable or vector, keyed
off a unique handle
 Pro: Quick, easy
 Con: Not persistent, memory can fill up
easily

11/04/08 Copyright © 1997-8, Purple Technology Inc. 84


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 85


Servlets and the Java Web Server

Database State: Pros and Cons


 Pro:
 persistent
 high capacity
 Con:
 more complicated
 have to write more code
 still doesn’t automatically expire old sessions

11/04/08 Copyright © 1997-8, Purple Technology Inc. 86


Servlets and the Java Web Server

C is for Cookie

Cookie Monster is a trademark of


Children’s Television Workshop

11/04/08 Copyright © 1997-8, Purple Technology Inc. 87


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 89


Servlets and the Java Web Server

Cookies and Servlets


 Servlets can easily use Cookies
 HttpServletRequest.getCookies() method
 HttpServletResponse.addCookie() method
 Cookie object

11/04/08 Copyright © 1997-8, Purple Technology Inc. 90


Servlets and the Java Web Server

javax.servlet.http.Cookie
 get/setName()
 get/setValue()
 Attributes
 Comment, Domain, MaxAge, Path, Secure, Version

11/04/08 Copyright © 1997-8, Purple Technology Inc. 91


Servlets and the Java Web Server

Cookie Example
 Cookie Counter Servlet
 Counter.java

11/04/08 Copyright © 1997-8, Purple Technology Inc. 92


Servlets and the Java Web Server

Cookie Pros and Cons


 Pro:
 No server-side storage requirements
 Survive server restarts
 Automatically expire
 Con:
 Not supported by all browsers
 Bandwidth limitations
 Not good for large amount of data
 User can disable them

11/04/08 Copyright © 1997-8, Purple Technology Inc. 93


Servlets and the Java Web Server

Detecting Cookie Acceptance


 CookieDetector.java
 Drops a cookie on the client
 Sends a redirect back to CookieDetector,
with a flag saying “this is the test phase”
 The test phase detects whether
 The client accepted the cookie
 The client rejected the cookie (or the browser
doesn’t support cookies)
 Sends another redirect to appropriate page
 You can tell the user “pretty please” here
11/04/08 Copyright © 1997-8, Purple Technology Inc. 94
Servlets and the Java Web Server

JWS Session Management


 Flexible
 Lightweight
 General
 Automatic
 Uses cookies if it can, URL rewriting if it
can’t
 Based on technology from ATG

11/04/08 Copyright © 1997-8, Purple Technology Inc. 95


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 96


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 97


Servlets and the Java Web Server

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)

11/04/08 Copyright © 1997-8, Purple Technology Inc. 99


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 101


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 102


Section V

Java Web Server Features

11/04/08 Copyright © 1997-8, Purple Technology Inc. 103


Servlets and the Java Web Server

Administration Tools
 Play with Admin Tool
 http://localhost:9090/
 Click on a service, click “Manage” button
 To shut down server, click “Shut Down”

11/04/08 Copyright © 1997-8, Purple Technology Inc. 104


Servlets and the Java Web Server

Manage Servlets
 Add
 Properties
 Load on Startup
 Unload

11/04/08 Copyright © 1997-8, Purple Technology Inc. 105


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 106


Servlets and the Java Web Server

Servlet Chains (Filters)


 specify a comma-separated list of servlets
 the first servlet gets the user input
 each servlet in turn will get the previous
output
 the final servlet will return to the user
 all servlets in chain must use same ACL

11/04/08 Copyright © 1997-8, Purple Technology Inc. 107


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 108


Servlets and the Java Web Server

Page Compilation (JSP)


 Embed Java code in static HTML pages
then compile those pages into individual
Java servlets to create a dynamic web site
 Based on JHTML technology from Art
Technology Group (http://www.atg.com/)
 Product: Dynamo, a Java Web Application Server

11/04/08 Copyright © 1997-8, Purple Technology Inc. 109


Servlets and the Java Web Server

Session Tracking
 See above

11/04/08 Copyright © 1997-8, Purple Technology Inc. 110


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 111


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 113


Servlets and the Java Web Server

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/

11/04/08 Copyright © 1997-8, Purple Technology Inc. 114


Servlets and the Java Web Server

References
 Advanced Web Technologies
 http://www.javatrain.com/
 Purple Technology
 http://www.purpletech.com/
 Gamelan
 http://java.developer.com/

11/04/08 Copyright © 1997-8, Purple Technology Inc. 115


Servlets and the Java Web Server

Appendix: CGI Tutorial

11/04/08 Copyright © 1997-8, Purple Technology Inc. 116


Servlets and the Java Web Server

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!

11/04/08 Copyright © 1997-8, Purple Technology Inc. 117


Servlets and the Java Web Server

Example CGI HTML


<FORM ACTION="/servlets/GuestBook"
METHOD=POST>
Name: <INPUT TYPE=text
NAME="name"><BR>
Message: <INPUT TYPE=textarea
NAME="message"><BR>
<INPUT TYPE=submit>
</FORM>

11/04/08 Copyright © 1997-8, Purple Technology Inc. 118


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 119


Servlets and the Java Web Server

CGI Flow (Cont.)


 Server receives parameters and sends
them to CGI script
 CGI script returns MIME document
 usually it's "text/html"
 can be any MIME type
 Browser receives response document and
displays it
 If response contains FORM tag, whole thing
can happen again
11/04/08 Copyright © 1997-8, Purple Technology Inc. 120
Servlets and the Java Web Server

The FORM tag


 Opens a form
 ACTION
 the URL of the script to execute
 METHOD
 GET or POST
 Usually use POST
 closed with </FORM>

11/04/08 Copyright © 1997-8, Purple Technology Inc. 121


Servlets and the Java Web Server

INPUT TYPE=text
 Specifies a text field
 NAME
 names parameter to be passed to script
 VALUE (optional)
 initial value for text

11/04/08 Copyright © 1997-8, Purple Technology Inc. 122


Servlets and the Java Web Server

INPUT TYPE=textarea
 Specifies a multi-line text area
 NAME
 names parameter to be passed to script
…

11/04/08 Copyright © 1997-8, Purple Technology Inc. 123


Servlets and the Java Web Server

INPUT TYPE=checkbox
 Specifies a check box (duh)
 NAME
 names parameter to be passed to script
 ISCHECKED=true
 default value on

11/04/08 Copyright © 1997-8, Purple Technology Inc. 124


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 125


Servlets and the Java Web Server

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

11/04/08 Copyright © 1997-8, Purple Technology Inc. 126


Servlets and the Java Web Server

INPUT TYPE=reset
 A push button that clears the form
 Does not submit it

11/04/08 Copyright © 1997-8, Purple Technology Inc. 127

S-ar putea să vă placă și