Title: Servlets
1Servlets
2Web Containers and server side technologies
- A container is a runtime to manage application
components developed according to the API
specifications, and to provide access to the J2EE
APIs - The container which handles web component
technologies i.e. servlets and JSPs (Java Server
Pages) is tomcat - Tomcat is open source and is available from the
Jakarta site http//jakarta.apache.org/tomcat/ - Servlets and JSPs running under tomcat are
server side technologies which accept requests
from an http form and return responses in the
form of an HTML ,XHTML or XML document - Servlets and JSPs are equivalent You could
write an application just using servlets or just
using JSPs or you could mix them up, well have
a look later what is the best policy as to when
to use servlets or JSPs
3Servlet interface
- Architecturally all servlets must implement the
servlet interface - The methods of the Servlet interface are invoked
automatically by the servlet container (usually
tomcat) - The interface has five methods
- void init(ServletConfig config)
- This method is called once during the servlets
execution cycle to initialise the servlet (the
argument is supplied by the container) - ServletConfig getServletConfig()
- Returns an object reference to an object that
implements interface ServletConfig (provides
access to servlets configuration information as
well as information about its environment (the
container) - String getServiceInfo()
- Returns information such as servlets author and
version - void service(ServletRequest request,
ServletResponse response) - This method is called as a result of a client
request - void destroy()
- Clean up method called when the servlet is
destroyed by its container
4Servlets lifecycle - UML state diagram
Instantiation based on a request or at conatainer
start up
Does not exist
Instantiated
Initialisation
Initialisation failed
Initialised and/or Ready for requests
Unavailable
Back to service In case of temporary
unavailability
End of Service thread
HTTP request(s) From client(s)
Temporary or permanent failure
Service
Destroyed
Time out or container shutdown
5HttpServlet class
- Web-based servlets typically extend the
HttpServlet class - Provides an abstract class to be subclassed to
create an HTTP servlet suitable for a Web site. A
subclass of HttpServlet must override at least
one method, usually one of these - doGet, if the servlet supports HTTP GET requests
- doPost, for HTTP POST requests
- doPut, for HTTP PUT requests
- doDelete, for HTTP DELETE requests
- init and destroy, to manage resources that are
held for the life of the servlet - getServletInfo, which the servlet uses to provide
information about itself - There's almost no reason to override the service
method. service handles standard HTTP requests by
dispatching them to the handler methods for each
HTTP request type (the doXXX methods listed
above).
6doGet and doPost methods
- doGet(HttpServletRequest req, HttpServletResponse
resp) - used to retrieve the contents of a specified URL
(an HTML or XHTML or XML page) - The content can be generated dynamically from the
servlet - Can be typed into a browsers address or Location
field and can be bookmarked - doPost(HttpServletRequest req, HttpServletResponse
resp) - Used to post data from an HTML form to a server
side form handler that processes the data (saved
it in a data base or retreives data from the
database.) - Cannot be typed into a browsers address or
Location field and cannot be bookmarked - doPost() method does not have a restriction on
amount of data received. - Safer to use doPost method!
- Except if youre using a servlet to display
information without an associated html page the
use doGet method
7Simple example using doGet method
- We need an HTML client
- A servlet with a doGet method
- A web.xml which relates the name of the servlet
to the java class - Usually this is generated for you by the ide
(JBuilder in this case)
8The web client
lthtmlgt ltheadgt lttitlegt HelloServlet lt/titlegt lt/head
gt ltbodygt ltform action"/HelloWorld/helloservlet"
method"get"gt ltpgtpress Submit to invoke servlet
HelloServletlt/pgt ltpgtltinput type"submit"
name"Submit" value"Submit"gtlt/pgt lt/formgt lt/bodygt
lt/htmlgt
- Note the form tags
- The action attribute specifies that the servlets
name is referred to as helloservlet and is
running in a folder HelloWorld in tomcat
9web.xml
ltweb-appgt ltdisplay-namegtHelloWorldlt/display-name
gt ltservletgt ltservlet-namegthelloservletlt/serv
let-namegt ltservlet-classgtepda.HelloServletlt/se
rvlet-classgt lt/servletgt ltservlet-mappinggt
ltservlet-namegthelloservletlt/servlet-namegt
lturl-patterngt/helloservletlt/url-patterngt
lt/servlet-mappinggt lt/web-appgt
- Note for each servlet you need two tags
- ltservletgt
- ltservlet-mappinggt
10HelloServlet.java
package epda import javax.servlet. import
javax.servlet.http. import java.io. public
class HelloServlet extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
response.setContentType(text/html)
PrintWriter out response.getWriter()
out.println("lthtmlgt") out.println("ltheadgtlttit
legtHelloServletlt/titlegtlt/headgt")
out.println("ltbody bgcolor\"lightblue\"gt")
out.println("ltpgtHello World.lt/pgt")
out.println("lt/bodygtlt/htmlgt")
11Running in Tomcat
- You need to type the following URL in a web
browser - http//localhost8080/HelloWorld/helloservlet.html
- When you hit the submit button Hello World is
displayed and the URL becomes - http//localhost8080/HelloWorld/helloservlet?Subm
itSubmit - If you changed the doGet mrthod to a doPost
method and submit the form the URL becomes - http//localhost8080/HelloWorld/helloservlet
- You cant see the input parameters
- If you bookmark it then you cant retrieve the URL
12Adding in request parameters
- If you wanted to add in the name of the user in
the html page and display it in the servlets, we
would add in - UserIDltinput type "Text" name "requsername"
gt - in the html file
- and
- out.println("ltpgtfrom"request.getParameter("requs
ername")) - in the servlet
- Sometimes you may want to hide the request
parameter from the user (visible when you choose
view source from within the browser) - You can use a hidden parameter
- ltinput type "hidden" name "action" value
"entryform"gt - This will be hidden from the user, you can use it
in the servlet by - String action request.getParameter("action")
13Initialising Servlets
- Common in real-life servlets
- E.g. initialising database connection pools
- Use SevletConfig.getInitParameters to read
intialisation parameters - Call getServletconfig to obtain the ServletConfig
object - Set init parameters in web.xml
- It is common to use init method even when you
dont read init parameters - E.g. to set up data structures that dont change
during the life cycle of the servlet, to load
information from disk e.t.c.
14Example of Initialising parameters
ltweb-appgt ltdisplay-namegtHelloWorldlt/display-name
gt ltservletgt ltinit-paramgtltparam-namegtdefaultuser
namelt/param-namegt ltparam-valuegtHarrylt/param-valu
egt lt/init-paramgt ltservlet-namegthelloservletlt/
servlet-namegt ltservlet-classgtepda.HelloServlet
lt/servlet-classgt lt/servletgt
ltservlet-mappinggt ltservlet-namegthelloservletlt/
servlet-namegt lturl-patterngt/helloservletlt/url-
patterngt lt/servlet-mappinggt lt/web-appgt
15Example of Initialising parameters
public void doPost(HttpServletRequest
request,HttpServletResponse response) throws
ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
ServletConfig config getServletConfig()
out.println("lthtmlgt") out.println("ltheadgtlttit
legtHelloServletlt/titlegtlt/headgt")
out.println("ltbody bgcolor\"lightblue\"gt")
out.println("ltpgtHello World.lt/pgt")
out.println("ltpgtfrom "request.getParameter("requs
ername")) out.println("ltpgtand from
"config.getInitParameter("defaultusername")
"the default user") out.println("lt/bodygtlt/htm
lgt")
16Request Headers
- Every Request has headers associated with it e.g.
whether the request is a post or get request, the
protocol associated with the request e.t.c. The
request object has methods associated to display
these headers . Below is a servlet that prints
these headers out for a particular request - (from corewebprogramming.com)
public class ShowRequestHeaders extends
HttpServlet public void doGet(HttpServletReque
st request, HttpServletResponse response) throws
ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
String title "Servlet Example Showing Request
Headers"
17Request Headers
out.println( "ltheadgtlttitlegtServlet
ExampleShowing Request Headerslt/titlegtlt/headgt"
"ltbody bgcolor\"B0C4DE \"gt\n"
"lth1 aligncentergt" title "lt/h1gt\n"
"ltBgtRequest Method lt/Bgt"
request.getMethod() "ltbrgt\n"
"ltBgtRequest URI lt/Bgt"
request.getRequestURI() "ltbrgt\n"
"ltBgtRequest Protocol lt/Bgt"
request.getProtocol() "ltBRgtltBRgt\n"
"lttable border1 aligncentergt\n" "lttr
bgcolor6495ed\"gt\n" "ltthgtHeader
NameltthgtHeader Value") Enumeration
headerNames request.getHeaderNames() while
(headerNames.hasMoreElements()) String
headerName (String) headerNames.nextElement()
out.println("lttrgtlttdgt" headerName)
out.println(" lttdgt" request.getHeader(header
Name)) out.println("lt/tablegt\nlt/bodygtlt/
htmlgt")
18Request Headers
19Statelessness and Sessions
- HTTP is a stateless protocol
- Different requests from the client are treated
completely differently with no relationship
between the different requests - A protocol is stateful if the response to a given
request may depend not only on the current
request but also on t he outcome of previous
requests - Stateful is important
- On line banking you only need to register once
each request e.g. looking at your balances,
transferring money from one account to another
doesnt require you to re-register every time - On line shopping with a shopping cart.
- Session
- The server should be able to identify that a
series of requests from a single client form a
single working session - State
- The server should be able to remember information
related to previous requests in a single session
20Session Tracking with the Java Servlet API
- The javax.servlet.http.HttpSession interface
encapsulates the notion of a session - Provides the getSession() method which you can
use to access the HttpSession object associated
with the client making the request - The HttpSession object is an implicit object and
is created for each client - The web container maintains this object for the
duration of the client session - Each session consume memory on the server side,
so its unwise to keep sessions open forever - Most e-commerce sites limit this interval to
under 30 mins - You can specify the time in an a deployment
desriptor element ltsession-configgt (the web.xml
file)
21Methods for Managing State
- setAttribute() method
- public setAttribute(String name, Object
attribute) - Â Â Binds an object to this session, using the name
specified - getAttribute() method
- public Object getAttribute(String name)
- This method returns the attribute bound with the
specified name in this session, or null if no
object is bound under the name - getAttributeNames() method
- public Enumeration getAttributeNames(String name)
- Returns an Enumeration of String objects
containing the names of all the objects bound to
this session. - removeAttribute() method
- public void removeAttribute(String name)
- Removes the object bound with the specified name
from this session.
22Using the state management methods
- String un request.getParameter("username")
- request.getSession().setAttribute("user", un)
- String un(String)request.getSession().getAttribut
e("user")
23Request Dispatching
- Allows a servlet or a JSP page to dispatch a
request to another servlet or JSP page or even an
HTML page which will then be responsible for any
further processing and for generating the
response. - Has an interface called javax.servlet.RequestDispa
tcher for this purpose - Has two methods which allow delegation of the
request-response processing to another resource
after the calling servlet has finished any
preliminary processing - public void forward(ServletRequest req,
ServletResponse resp) throws ServletException,
java.io.IOException) - Allows the request to be forwarded to another
servlet or JSP page which then takes over the
responsibility of producing the response - public void include(ServletRequest req,
ServletResponse resp) throws ServletException,
java.io.IOException) - Allows the inclusion of the content produced by
another ersource in the calling sevlets response
24Examples of Request Dispatching
RequestDispatcher rd request.getRequestDispatche
r("oracleconnection") rd.include(request,
response) if ( ( (String) request.getSession().ge
tAttribute("status")). equalsIgnoreCase("O
K")) response.sendRedirect("controlservlet.htm
l") else rd request.getRequestDispatcher(
"viewerror") rd.forward(request, response)
25Examples of Request Dispatching
- oracleconnection is the name of a servlet
OracleConnection.java - Specified in web.xml
- ltservletgt
- ltservlet-namegtoracleconnectionlt/servlet-namegt
- ltservlet-classgtia.OracleConnectionlt/servlet-cl
assgt - lt/servletgt
- ltservlet-mappinggt
- ltservlet-namegtoracleconnectionlt/servlet-namegt
- lturl-patterngt/oracleconnectionlt/url-patterngt
- lt/servlet-mappinggt
- Status is the name of an attribute that
OracleConnection set to have the value OK or
fail - public void sendRedirect(java.lang.String location
) throws java.io.IOException - Sends a temporary redirect response to the client
using the specified redirect location URL. This
method can accept relative URLs the servlet
container must convert the relative URL to an
absolute URL before sending the response to the
client. If the location is relative without a
leading '/' the container interprets it as
relative to the current request URI. If the
location is relative with a leading '/' the
container interprets it as relative to the
servlet container root. (source java.sun.com) - viewerror is the name of a Servlet specified in
web.xml.