Title: CCP111N Week 5 Servlets Part 1
1CCP111N Week 5 Servlets Part 1
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
2Prerequisites
- For this section you are expected to know Java
programming including - while and for loops (vital)
- if (vital)
- Passing parameters to methods (vital)
- Arrays and Strings (important)
- The Enumeration class (important)
- Threads and synchronized (useful)
- Exceptions try and catch (useful)
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
3Resources
- http//edocs.bea.com/wls/docs70/servlet/index.html
is a reasonable tutorial on servlets - Search the web for a good tutorials, there are a
lot of them... - http//java.sun.com/j2se/1.4.2/docs/api/index.html
contains the entire list of classes, methods etc
for all of Java, JSP and servlets. Use it as a
reference don't try to learn it all!
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
4Serving Static HTML
- Web servers where designed to provide web
browsers with HTML. - The HTML was read from text files by the server
and sent to the client using HTTP. The web server
does not modify the HTML. This is now termed
static HTML serving
Server Machine
Client Machine
HTML doGet or doPost
HTML
Web Browser
Web Server
Web Page on disk
HTML
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
5Static HTML the Problem
- Modern uses of web pages often require pages to
be dynamically generated. - For example a chat system would display any new
messages each time you hit refresh. This requires
the web page the browser requests to be modified
each time someone adds a new message. - Until recently there was no easy way to do this
because - web browsers were not designed to rewrite web
pages - web browsers are stateless so they process each
request in isolation without reference or memory
of what request came before it.
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
6Why not forget about generating HTML and write
custom programs in C or Java?
- Web browsers are freely available for almost any
platform and are frequently used by people
connected to the internet - People can easily understand how to navigate web
pages whereas many custom written applications
have large and complex graphical user interfaces - Network communication in C or Java requires
messing around with sockets, TCP/IP and possibly
Serialisation. - Often the speed of C and similar languages is
not required - You have to install the programming language and
libraries on the client machine - You have to have a way to distribute (and update)
and install (and uninstall) the application on
the client machine
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
7Not the Solution - Modify the web server
- We could modify the web server so that it
dynamically generates HTML in response to a
browser request. - But this requires modifying it for each
application we want to run. - We have the source code and tools to modify it.
Some web servers like Microsoft Internet
Information Server (IIS) are proprietary and we
can not modify them. - Any bugs in the modifications could crash the
entire web server - Any updates to the application require the web
server to be modified and restarted
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
8The Solution Run an external program to
generate the HTML
- A better choice is to arrange it so that when a
certain web page is accessed an external program
is run by the web server and that program
generates the HTML gt web server must know how to
run and communicate with application. - This process is transparent to the web browser.
It just receives HTML and does not know it has
been dynamically generated gt web browser does
not need to be modified - CGI Common Gateway Interface is one way for a web
server to run external applications. Servlets is
another way.
Server Machine
Client Machine
Information about the request
HTML doGet or doPost
Web Browser
Web Server
External HTML generator
HTML
HTML
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
9Servlets - a solution for dynamically generating
HTML
- Servlets are programs written in Java which run
on the web server and communicate using with the
web browser using HTTP and HTML - Servlets are compatible with all web browsers
because servlets communicate with the browser
using only HTML and HTTP - Servlets are simple to write because they are
written in standard Java - Most of the communication is done for you by the
Servlet class. No need to mess around with
Sockets, TCP/IP or Java serialisation. - Servlets run only on the server and therefore do
not need Java any other programming language to
be installed on the client - Servlets do need the servlet to be stored or
installed on the client
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
10Architecture of a Servlet
- The web browser sends a HTTP doPost or doGet
request to the web server - The web server realises the request is for a
servlet. If the servlet is not already loaded it
loads it and calls the servlet's init method - The web browser passes the HTML request to the
servlet's service method - Service method calls the corresponding doGet or
doPost method - The method can execute and generate HTML which is
passed back to the web browser - When the web browser decides to unload the
servlet it calls the destroy method
Server Machine
Servlet Java Class
Client Machine
Init
HTML doGet or doPost
Web Browser
Web Server
Service
HTML
doPost
HTML
HTML
doGet
Destroy
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
11Class Structure of a Servlet
- A servlet is a Java class which runs inside a
Java virtual machine and is controlled by the web
server. - All Servlets extend the Servlet class directly or
indirectly. - You write your own Java class to handle web
server requests and this class will extend one of
the standard servlet classes (normally
HttpServlet which itself extends Servlet) - Communication with the web server is via two
additional classes. normally HttpServletRequest
and HttpServletResponse which extend
ServletRequest and ServletResponse - There is normally no need to write your own
ServletRequest or ServletResponse
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
12Class Structure of a Servlet Program
Your Servlet Code
MyServlet Methods doGet doPost init destroy etc.
Http Servlet Layer
HttpServlet Methods Service doGet doPost init
destroy etc.
HttpServletRequest
HttpServletResponse
Basic Servlet Layer
Servlet Method service
ServletRequest
ServletResponse
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
13Jobs of the Servlet Classes
- Your servlet will extend HttpServlet and only
needs to replace the methods of HttpServlet of
any requests it will process. - The HttpServlet class extends servlet and
overrides its service method. This class has one
dummy method for each type of HTTP request. The
service method determines what the request is.
E.g. HTTP get or post and calls the appropriate
dummy method. The additional HTTP information is
passed in HttpServletRequest and
HttpServletResponse - The Servlet class service method is designed to
be called by the web server with details about
the request. (ServletRequest and ServletResponse)
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
14Writing a Servlet
- Your servlets will usually extend the HttpServlet
class. Which provides default implementations of - init, you only need to override this if you want
to do some initialisation such as open a database
connection. - destroy, you only need to override this if you
want to do some cleaning up such as closing a
database connection. - service, should not normally be overridden
because it decides which of the doX methods
should be called - doGet. HTTP Get is the default way a web browser
makes a request and this causes the doGet method
of the servlet to be invoked so you would
normally override this method - doPost. If you don't respond to a Post you don't
need to override this method.
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
15HTTP Get or Post?
- The main differences between Get and Post are
- GET data is sent as a query string client
query is completely embedded in the URL sent to
the server. The amount of query information is
usually limited to 1KB. This information is
stored in the request line. This is the default
method when you click on a href HTML link. - POST data is sent as part of the message
body. Data is not visible in the URL and large
amounts of data can be sent to the server.
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
16Servlet doGet and doPost
- doGet and doPost have identical signatures and
receive two parameters from the service method.. - public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException - public void doPut(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException - HttpServletRequest is an Object containing
information about the request from the web
browser. - Such as the login name of the user and any values
in the header field sent by the web browser. - Any parameters sent as part of the request
- Any initialisation parameters set in the
deployment descriptor - It also supplies any session and cookies (more on
these later) - HttpServletResponse is an Object which allows you
to add cookies, add header values and redirect to
a new URL, write HTTP to the web browser and send
error messages.
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
17Client-Server Interaction
- HTTP Request (Sending request message to Server
) - HTTP is a request-response protocol
- When a client sends a request, it consists of
three parts - request line
- HTTP method type (GET or POST)
- resource name (URL)
- protocol/version e.g. POST /im51p/w7.html
HTTP/1/1 - header variables contains browser information
(optional) - message body in POST method request information
is stored here (optional) - HTTP Response (Sending response message to
client) - The response sent by the server also consists of
three parts - response line (server protocol and status code)
- header variables (server and response
information) - message body (response, such as HTML)
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
18Servlet Output
Request contains any parameters, Cookies and
Sessions send by the client
Response allows you to add cookies and send data
to the client
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException
response.setContentType("text/html")
PrintWriter out response.getWriter()
out.println("ltHTMLgt") out.println("ltHEADgtltTIT
LEgtFirst Servlet programlt/TITLEgtlt/HEADgt")
out.println("ltBODYgt") out.println("ltH1gtWelcom
e to Servletslt/H1gt") out.println("lt/BODYgt")
out.println("lt/HTMLgt") out.close()
The servlet must get the communications channel
from the response Object and set the encoding
before sending anything to the client
ltHTMLgt ltHEADgtltTITLEgtFirst Servlet
Programlt/TITLEgtlt/HEADgt ltBODYgt ltH1gtWelcome to
Servletslt/H1gt lt/BODYgt lt/HTMLgt
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
19First Servlet Example
Servlets are not part of the standard SDK, they
are part of the J2EE
import java.io. import javax.servlet. import
javax.servlet.http. public class ServWelcome
extends HttpServlet public void
doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException
response.setContentType("text/html")
PrintWriter out response.getWriter()
out.println("ltHTMLgt")
out.println("ltHEADgtltTITLEgtFirst Servlet
Programlt/TITLEgtlt/HEADgt")
out.println("ltBODYgt") out.println("ltH1gtWe
lcome to Servletslt/H1gt")
out.println("lt/BODYgt")
out.println("lt/HTMLgt") out.close()
Servlets normally extend HttpServlet
The response to be sent to the client
Details of the HTTP request from the client
Set the response type to text/html (this is
normal)
This HTML text is sent to the client
Don't forget to close the connection with the
client
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
20Servlet Life Cycle Managed by the Server and
Container
Call to methods doGet(), doPost() in the user
defined servlet class
Unlike CGI a single servlet can service several
requests. In CGI, server invokes a separate
process for each request. Servlets therefore
reduce server load
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
21Scalability of Servlets
- There are several costs associated with loading
and executing user supplied code in the web
server. - Compiling and loading
- Handling sequential requests
- Handling concurrent requests
- The servlet is only recompiled by the web browser
if it has changed otherwise the already compiled
.class file is loaded gt Faster response times
because the servlet does not need to be
recompiled - The servlet can be kept in memory for a long time
to service many sequential requests gt Faster
response times because the servlet does not need
to be reloaded - Only one copy of the servlet is held in memory
even if there are multiple concurrent requests
for it gt less memory usage for concurrent
requests and no need to load another copy of the
servlet and create a new process to run it.
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
22HttpServletRequest class
Get and Post are passed an instance of the
HttpServletRequest class. It contains methods for
accessing information about the HTTP request and
about the server environment such as the names of
parameters passed by the client, the protocol
used by the client etc.
String getMethod() obtain the HTTP request is
it a GET or POST String getParameter(String name)
- get a parameter (covered later) String
getRemoteHost() - clients host name String
getRemoteAddr() - IP address of client String
getServerName() - servers name int
getServerPort() - port on which server was
initially contacted on (8080 is usually
intranet only and not accessible from
outside) String getHeader("User-Agent") - name of
clients web browser String getHeader("Referer")
- URL of page that called the servlet some more
methods ...
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
23HttpServletRequest Example
import java.io. import javax.servlet.
import javax.servlet.http. p
ublic class ServEnvData extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException response.setContentTy
pe("text/html") PrintWriter out
response.getWriter() out.println("ltHTMLgt
") out.println("ltHEADgtltTITLEgtEnvironment
Datalt/TITLEgtlt/HEADgt") out.println("ltBODY
gt") out.println("ltH1gtServlet
Environmentlt/H1gt") out.println("ltBgtMethodlt/Bgt"
request.getMethod()"ltBRgt") out.println("ltBgtClie
nt Hostlt/Bgt"request.getRemoteHost()"ltBRgt") ou
t.println("ltBgtClient's IP Addresslt/Bgt"request.ge
tRemoteAddr()"ltBRgt") out.println("ltBgtServer
Namelt/Bgt"request.getServerName()"ltBRgt") out.p
rintln("ltBgtServer Portlt/Bgt"request.getServerPort
()"ltBRgt") out.println("ltBgtClient's
Browserlt/Bgt"request.getHeader("User-Agent")"ltBR
gt") out.println("ltBgtClient's URLlt/Bgt"request.g
etHeader("Referer")"ltBRgt")
out.println("lt/BODYgt")
out.println("lt/HTMLgt") out.close()
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
24HttpServletRequest Example
Web browser sent a HTTP GET request
My machine does not have a DNS entry so the
hostname is just the IP address
My machines IP address
The server has a DNS entry
The server was contacted by the web browser on
port 8186. A temporary port is set up for all
further communications allowing another web
browser to connect to the client
I used Mozilla rather than Internet Explorer
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
25HttpServletResponse class
- The doGet and doPost methods also receive a
instance of the HttpServletResponse class which
contains methods for communicating with the
client and manipulating HTTP information. Servlet
can set the content length,status codes and MIME
types of the reply etc.
void response .addCookie(Cookie cookie) -
(covered later) void response.sendError(int
status) - standard HTTP status codes void
response.sendStatus(int status) - send HTTP
status codes that are not errors void
response.sendRedirect(String location) - sends a
redirect response to the client some more
methods ...
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
26Passing a Parameter to Servlets
- You can pass parameters to the servlet by
creating a link to the servlet and encoding one
or more parameters in the link - lta href"http//www3.unl.ac.uk8186/kingj1/servlet
/param?p1hello"gt click here for a parameter
example! lt/agt - This hardwires the value of the parameter in the
html code. - The servlet can access the parameter called p1 by
using the getParameter method in request. - String parameterrequest.getParameter("p1")
The name of the parameter
The value of the parameter
The name of the parameter
Get parameter always returns a String
The HttpServletRequest Object
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
27Passing Multiple Parameters to Servlets
- To pass more than one parameter separate each one
with a - lta href"http//www3.unl.ac.uk8186/kingj1/servlet
/param? - p1hellop2goodbye"gt click here for a parameter
example! lt/agt
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
28Getting a list of Parameters
- You can get a list of all the parameters passed
by using getParameterNames() which returns an
Enumeration Object - Enumeration prequest.getParameterNames()
- while (p.hasMoreElements())
-
- String n(String)p.nextElement()
- String vrequest.getParameter(n)
- out.println("parameter name is "n"
parameter value" v"ltbrgt") -
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
29Using forms to Pass Parameters
- The second way to pass parameters to an servlet
is to use HTML forms. - ltFORM METHOD"GET" ACTION"http//www3.unl.ac.uk8
186/kingj1/servlet/param"gt - Enter your Name ltINPUT TYPETEXT NAME"myName"gt
- ltINPUT TYPE"SUBMIT" VALUE"Send Name"gt
- lt/FORMgt
This will cause the doGet method in the servlet
to be invoked
Name of parameter value of parameter is whatever
is typed into the text box
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
30Using Choice boxes
- The choice box allows one of a set of choices to
be selected - Just like a TEXT input the result of the
selection is stored in a parameter and passed to
your application
31Using Choice boxes
- The code is a little more complex than a TEXT
field. - ltFORM METHOD"POST" ACTION"http//www3.unl.ac.uk
8186/kingj1/servlet/cw?actionsubmit"gt - ltbrgtltbrgtquestion 0 what grade do you want on this
coursework? - ltbrgt F
- ltinput type"radio" name"q0" value0 gt
- ltbrgt resit
- ltinput type"radio" name"q0" value1 gt
- ltbrgt fail
- ltinput type"radio" name"q0" value2 gt
- ltbrgt retake
- ltinput type"radio" name"q0" value3 gt
- ltINPUT TYPE"SUBMIT" VALUE"Mark"gt
- lt/formgt
All the choices associated with the same choice
box have the same name!
Each possible choice should have a different
value.
When the submit button is pressed the parameter
q0 will have the value 0 or 1 or 2 or 3
32Using Choice boxes
- You may have one than one independent choice box
in the same form. The result of each select is
passed as separate parameters.
33Using Choice boxes
- In this case one choice is called q0 and the
second q1 - ltFORM METHOD"POST" ACTION"http//www3.unl.ac.uk
8186/kingj1/servlet/cw?actionsubmit"gt - ltbrgtltbrgtquestion 0 what grade do you want on this
coursework? - ltbrgt F
- ltinput type"radio" name"q0" value0 gt
- ltbrgt resit
- ltinput type"radio" name"q0" value1 gt
- ltbrgtltbrgtquestion 0 what grade do you want on the
exam? - ltbrgt F
- ltinput type"radio" name"q1" value0 gt
- ltbrgt resit
- ltinput type"radio" name"q1" value1 gt
- ltINPUT TYPE"SUBMIT" VALUE"Mark"gt
- lt/formgt
34Thread Unsafe
- A servlet can be called concurrently several
times by different web browsers. - This has ramifications for how you write your
servlet. - If the servlet reads a global value the value may
be changed by another thread before the servlet
uses the value (which is now out of date) - The servlet on the next slide should count
sequentially from 0 each time it is called. But
if two requests are made concurrently it does not
work correctly! try it!
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
35Thread Unsafe
- import java.io.
- import javax.servlet.
- import javax.servlet.http.
- public class multi extends HttpServlet
- int count0
- public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException - response.setContentType("text/html")
- PrintWriter out response.getWriter()
- out.println("ltHTMLgt")
- out.println("ltHEADgtltTITLEgt Thread UNSAFE
example lt/TITLEgt lt/HEADgt ") - out.println("ltBODYgt")
- out.println("ltH1gt old count is
"count"lt/H1gt") - countcount1
- try Thread.sleep(4000) catch
(Exception e) - out.println("ltH1gt new count is "count"lt/H1gt")
- out.println("lt/BODYgt")
- out.println("lt/HTMLgt")
-
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
36Thread Safe
- A good way to make sure servlets are thread safe
is to have no global data. But this is not always
practical. - A partial solution is to store data on a per
client basis. But this requires sessions or
cookies. It does not work if one client machine
has two instances of the web browser accessing
the servlet concurrently - The best method is to mark the sections of code
that access global data as synchronized. This
allows the sections that do not access global
data to run concurrently
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)
37Thread Safe
- Enclose sections that use global data in
synchronized sections - import java.io.
- import javax.servlet.
- import javax.servlet.http.
- public class multi extends HttpServlet
- int count0
- Object snew Object()
- public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException - response.setContentType("text/html")
- PrintWriter out response.getWriter()
- out.println("ltHTMLgt")
- out.println("ltHEADgtltTITLEgt Thread UNSAFE
example lt/TITLEgt lt/HEADgt ") - out.println("ltBODYgt")
- synchronized (s)
- out.println("ltH1gt old count is
"count"lt/H1gt") - countcount1
- try Thread.sleep(4000) catch
(Exception e) - out.println("ltH1gt new count is "count"lt/H1gt")
- out.println("lt/BODYgt")
CCTM Course material developed by James King
(james.king_at_londonmet.ac.uk)