Advanced Java Programming: Unit Two: Servers and Servlets
Advanced Java Programming: Unit Two: Servers and Servlets
Lee John
Morris
Kavi
Overview
• To create a simple HTTP server in Java
• To use the implementation to illustrate a
number of advanced Java features:
• TCP/IP Sockets and Server Sockets
• Interfaces
• Software components (more from John later)
• Multithreading
• To show how to create executable server
objects (using Sun’s Servlets API)
Recommended Reading
• Java Network Programming, Elliotte Rusty
Harold, O’Reilly and Associates, 1997,
ISBN 1-56592-227-1
• TCP/IP Network Administration, Second
Edition, Craig Hunt, O’Reilly and
Associates, 1997, ISBN 1-56592-322-7
• The Java Developer’s connection:
http://www.javasoft.com/jdc
• The Javadoc documentation
(Pseudo) requirements
• Server must be able to process HTTP/1.0
file transfer requests and deliver files
• Connections are to be made via TCP/IP
• Must be efficient and prompt
• Must be simple to understand and elegant
in design
HTTP protocol
• Developed by Tim Berners-Lee at CERN
• Like most Internet protocols it is described
in an RFC (Request for Comment
document): RFC1945
• May be downloaded from the Internet
Engineering Task Force’s web site:
http://www.ietf.org
Back to server example
• Some of you may have covered this in the
introductory Java course
• Servers have a listener loop
• Loop until the server is shutdown
• Wait for a client to request a connection
• Read the details of the client’s request
• Provide the requested information to the
client
• Here’s the listener loop from our example:
HttpServer
FileServer f = createFileServer();
f.dispatch(s);
}
}
How it all fits together
2037 1583
Socket s
FileServer f = createFileServer();
f.dispatch(s);
}
}
Interfaces benefit clients
• Simplifies client implementation
• Clients do not need to worry about the
implementation details
• Interfaces encapsulate state of different
subsystems ⇒ side effects reduced
• Define clear boundaries between different
teams of programmers
• Clients can substitute alternative
implementations: polymorphism
• Clients can purchase off the shelf
solutions: software components
Interfaces simplify clients
Software Component
Interface /ublic class HttpServer
Client Program
{
/**
Listens indefinitely for transfer requests and creates a server
instance for each request.
*/
public void listen()
throws IllegalAccessException, InstantiationException, IOException
{
for (;;) {
/*
Block, waiting for a request to occur then spawns a new
(anonymous) socket with which to deal with the request.
*/
System.err.println("HttpServer: waiting...");
Socket s = socket.accept();
/*
Create a file server to deal with the new socket.
*/
FileServer f = createFileServer();
f.dispatch(s);
}
}
public static void main(String[] args)
{
try {
HttpServer htts = new HttpServer("sea.server.ThreadedFileServer");
htts.listen();
}
catch (Exception e) {
System.err.println("HttpServer: failed due to exception:\n" + e);
}
}
The FileServer interface
. . . .
}
SimpleFileServer (3)
• Must get an input stream so that we can
analyse the request
• Socket provides the method
• InputStream getInputStream();
Socket s;
HTTP/1.0 200 OK
Server: SEA/1.0
MIME-version: 1.0
Content-type: text/html
time
time
interface Runnable
{
/**
This is the method that will be run when the
new thread is started.
*/
public void run();
}
java.lang.Thread (2)
• Must create a Thread object associated
with each new thread using the
constructor
• Thread(Runnable run, String threadName)
. . . .
}
ChatServer (2)
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
createDocument(response);
}
writer.println("<HR><FORM METHOD=POST>");
writer.println("Enter your name: “ +
“<INPUT TYPE=TEXT SIZE=25 NAME=name><BR>");
writer.println("Enter your message:<BR>” +
“<TEXTAREA ROWS=5 COLS=40 NAME=message>” +
“Type your message here</TEXTAREA><BR>");
writer.println(
"<INPUT TYPE=SUBMIT NAME=action VALUE=Submit>");
writer.println("<HR></FORM>");
ChatServer (4)
protected synchronized void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("name");
String message = request.getParameter("message");
if (name != null && message != null) {
Date timeStamp = new Date();
String messageString = "<B>Message " + messages.size() +
" from " + name + " at " + timeStamp +
":</B><BR>" + message + "<P>";
messages.add(messageString);
}
createDocument(response);
}
Performance (1)
• Servlets offer better performance than
most of the previous CGI like technologies
• But CGI/Servlets concentrate the load on
the server
• When designing high throughput servers
only use servlets where you really need
interactivity
• Searches/Shopping carts
• Data that is very short lived (stock quotes)
• This also applies to low throughput
servers that might need to scale later
Performance (2)
• Consider using periodic programs to
generate static documents on disk
• The cost of serving fixed documents will
always be less than the cost of server side
execution
• Disk space is cheap!
• Consider using applets when possible
• This places the load on the client machines
rather than the server
• Finally consider using SMP and/or server
farms
• Complex and very expensive
Pull versus Push transports
• How can a chat reader find out when a new
message has been posted by another
author?
• Only by repeatedly hitting the Reload button!
• HTTP (& TCP/IP services in general)
transfer documents on the user’s request
• To push updates automatically from the
server you will need to:
• Start a reverse server within each client
• Use a multicast group
• Use a remote procedure call system such as
RMI or CORBA
Servlets and JSP
• Java Server Pages is an extension to the
servlets API.
• With conventional servlets you embed the
HTML that you need inside a Java
program.
• With JSP you embed your Java program
within a HTML document (by using special
tags).
• Works rather like JavaScript but the JSP
script runs on the server before the page is
dispatched to the user’s browser.
Useful sources of information
• For information about HTML try
http://www.w3schools.com
• You can download Sun’s servlet
development kit from their web site at the
http://java.sun.com/products/servlet
• You can download apache’s Tomcat server
from http://jakarta.apache.org
• For other information about Servlet
development try http://www.servlets.com
Homework
• Read through the sample code to convince
yourself you understand what’s going on
• Sample code can be downloaded from
http://ciips.ee.uwa.edu.au/~gareth
• Read the code documentation
• If you can, run the examples to check they
work
Comments, Suggestions. . .
• How was the presentation paced?
• Was there enough (or too much) technical
content?
• Any areas of particular interest?
• Comments regarding presentation style?