Vous êtes sur la page 1sur 4

Notes on Servlets

What is a Servlet? - public void init(ServerConfig sc) throws

- ServerConfig is optional
A Java program that extends the functionality of a web server, - Called once for set-up operations like opening database
generating dynamic content, and interacting with web clients connections, creating session objects, naming services, etc.
(browsers) using the request-response paradigm support provided by Stage 2: Service
the web container (standalone or embedded into a web server) in - Called after initialization for every HTTP request
which the servlet resides. - Extracts information from HTTP request, performs
In Model-View-Controller (MVC) pattern servlets fit as Controller required tasks, collate needed info and finally post response
– process HTTP request and manage application’s workflow.
In n-tier architecture, servlets sit in web tier. It receives HTTP
- Dispatches to public void
requests (who made, user-entered data, headers), extract info from it, doGet/Post/Put/Delete(HttpServletRequest req,
generates dynamic content and providing business logic and HttpServletResponse res)
delegating it through EJB, database, another servlet or JSP and sends - doGet and doPost can be chained
back formed HTTP response (text[html/plane], binary[image], - GenericServlet is an abstract class because service() is
headers, cookies etc). abstract there and is implemented in HttpServlet class
Stage3: Destruction
- Invoked when container determines that servlet should be
Need of Servlets removed from service (e.g. when server is being shutdown
or more memory is required)
- No CGI (traditional way of adding functionality to a web server) - public void destroy()
limitations like high overhead and extensive server resource - Called once to release any previously allocated resources
requirement To get information about servlet like author, company, address , use
- Solution to ISAPI/NSAPI which were fast but if buggy then can getServletInfo()  normally called by other servlets
crash web server as well. CORBA based WAI was a solution but
these all are server specific ServletContext
- Servlets are powerful, reliable, efficient (thread [and not a separate
process as in CGI] in same JVM, serves multiple requests, single
class image in memory), extensible (jsp), platform and server - Permits multiple servlets within a web application to have
independent, secure (java features), auto-reloading, support by 3rd access to shared information and resources.
parties, and improves scalability, and reusability (component based). - One instance per Web application per JVM
- With this object, a servlet can log events, set and get
attributes, and obtain URLs
Servlet API - To get ServletContext, use
ServletContext getServletContext()
Packages: - To get Context-wide attribute, use
javax.servlet getServletContext().getAttribute(String)
javax.servlet.http - To get servlet context path, use
Interface: HttpServletRequest.getContextPath()
javax.servlet.Servlet - To log, use SC.log(String) method
Classes: - Unlike System.out. log is buffered, fast, predictable and
Either implement the interface or extend following classes retrievable using built-in functions
implementing Servlet interface - To retrieve initialization parameters specified in
javax.servlet.GenericServlet: Protocol-independent derivations deployment descriptor using <context-param> tags, use
javax.servlet.HttpServlet: Extends GenericServlet class to provide public String getInitParameter(String name)
support for HTTP protocol //These are not user-entered parameters
javax.servlet.HttpSession: Maintains session-wide state information public Enumeration getInitParameterNames()
HttpServletRequest, HttpServletResponse: Extensions of
ServletRequest & ServletResponse. Objects created by the container
to be used in service() method. HTTPServletRequest Methods
javax.servlet.ServletException: General
javax.servlet.UnavailableException http://[host]:[port]/[request_path]?[query_string]
request_path =
Context: /context (root) of web app
Servlet Life Cycle Sevlet Name: /component alias
Path Information: rest of it
query_string= set of parameters and values entered by user
Stage 1: Initialization
- When servlet is loaded into server memory either at server public String getParameter(String name)
startup (pre-loading) or when they are accessed //different from getInitParameter()
(dynamically) - Configurable public Enumeration getParameterNames()
- LoadInstantiateInitialize public String[] getParameterValues(String name)
public int getContentLength() // 76, -1 if unknown

Prepared by: Syed Feroz Zainvi

Notes on Servlets
public getContentType() // app/x-www.., -1 if unknown getID() //temp primary key for uniquey identifying a session – used
public getCharacterEncoding() //null with cookies and in query strings
public getProtocol() // HTTP/1.1 getCreationTime() // when the session was created
public getRemoteAddr() // getLastAccessTime() // when the session was last accessed
public String getRemoteHost() //pross
public String getRemoteUser() //null if not authenticated Session Management
public getScheme() //http
public getServerName() //localhost
public getServerPort() //80 StateAbility to save the information – Required in e-commerce
public Cookie[] getCookies() systems – Can be stored as cookies or in database – Can last for any
public int cookies.length length of time : page, session, permanent storage
public String cookies[].getName() Scope  lifespan of state, or the length of time over
public String cookies[].getValue(); which state is maintained and can be accessed.
public Enumeration getHeaderNames() //e.g. user-agent Servlets and JSPs have 4 scopes:
public String getHeader(String) // Mozilla/4.0 i) Page: Data is available between page initialization
public Enumeration getHeaders(String) and destruction. This scope is available for JSP only.
public int getIntHeader(String) ii) Session: One interactive session between web client
public getRequestURI() and server. Exists until timeout, browser is closed, or
public setAttribute(String, Object) //for use with communication fails. Used for authentication and in
RequestDispatcher(). Some attributes are set by container itself systems like shopping cart
public HttpSession getSession() iii) Application: Relates to all servlets and JSPs in a Web
public Locale getLocale() application.
ResourceBundle getBundle(String, Locale) Transcends to individual users and used for hit-
public Boolean isSecure() //for HTTPS counters and support systems like JDBC connection
public ServerInputStream getInputStream() pool. Maintained until App Server restarts or
public java.io.BufferedReader getReader() application is redeployed.
String getAuthType()
iv) Request: Relates to request that launched the page.
boolean isUserInRole(String) //logical role
Scope may be forwarded further to other servlets and
JSPs and maintained until response object is sent back.
HTTPServletResponse Methods
A Session is a series of requests that originates from the same user at
public void setStatus(int statusCode) //100-599 or enums the same time.
public void sendError(int err_code) //--do-- HTTP, being stateless, cannot recognize that sequence of requests are
public void sendError(int err_code, String err_msg) all from same client. Following techniques can be used to remember
//Web container generates default error page. Custom error pages can state information:
also be configured through deployment descriptor 1. Hidden Form Fields
public void setHeader(String name, String val) //arbitrary header <input name=”pageid” type=”hidden” value=”5”>
public void setDateHeader(String name, long milSec) //since 1970 Servlet can access it like regular field through
public void setIntHeader(String hdr, int val) //intString getParameter()
public void addHeader, addDateHeader, addIntHeader //for Limitation: Apparently hidden (Visible in View Source)
adding new instances instead of replacing 2. URL Rewriting
public void setContentType(String) Appended to URL using ? and & as parameter-value pairs.
public void setContentLength(int) //for persistent HTTP http://myserver/servlets/srvltEmp?EMPID=1009&DID=10
public void addCookie(String) Limitation: Query string is visible and browser limits it
public void sendRedirect(String url) length as well. Alternatively, post these attributes as form
public int getLastModified() data and access through get methods
// preferably use above methods to set Content-Type, Content- 3. Persistent Cookies
Length, Set-Cookie, Location, Last-Modified Headers. Other headers A cookie is a small text file that is stored on
are Content-Encoding, Cache-Control(in 1.1) and Pragma(in 1.0) the client system. The file contains a single
public ServletOutputStream getOutputStream() // for binary name-value pair and several configuration
public PrintWriter getWriter() // for character output parameters to store user-preferences and
public encodeRedirectURL(String) //Before sendRedirect() to add client-specific information.
session id if page supports that
A persistent cookie is intended to maintain
public encodeURL(String) // except for sendRedirect()
information over more than one browser
session. E.g. storing login and password as
HTTPSession Methods cookie so that you need not enter it again
every time you visit that site
getAttribute(String name) Create cookie using new Cookie(String name,
setAttribute(String name, String val) String val)
get/setMaxInactiveInterval(int seconds) //default:1800 – for Use addCookie(cookiename), getCookies(),
destroying session objects e.g. logout if inactive cookies[].getName(), and cookies.getValue()
invalidate() // destroy session object and release resources for setting cookies and retrieving its attributes
Other methods for cookies are:
Prepared by: Syed Feroz Zainvi
Notes on Servlets
setSecure(false); //if true then sent only when It is a JAR file only with a different extension so let people treat it
HTTPS or SSL is used differently
setVersion(0); //0Original, 1 newer RFC  To create it, move to the directory containing web application
2109 objects and use following comand,
setMaxAge(60*60*24*7) // 1 week; <=0  jar –cf MyWebApp.war *
destroyed when browser is closed To list the contents of a web archive use following command,
setDomain() jar –tvf MyWebApp.war
Clients cannot reject cookies but can ignore them. In Directory Structure
subsequent requests, servlet can know this. Javascript can App Server will unbundle the WAR into a specific directory
be used to check for a cookie. hierarchy. The root of this hierarchy serves as a document root of the
To avoid overhead of creating multiple cookies, use ‘&’ application for serving files that part of this context.
to concatenate multiple values and use StringTokenizer
Cookies are insecure data storage – user can manipulate
them and secure data should not be there in cookies
 Cookies offer scalable solution if simultaneous multiple -Application’s root directory defined by user
hits but may slow down the webpage whereas Session |
attributes offer speed at the cost of server resources. |
Cookies can be used to prevent popups also.
| |
| |
4. Session Tracking API
| +----classes (servlet’s .class, utility
- Added in Servlet 2.2 API
| | classes, javabeans)
- Used through getSession(), setAttribute(), setAttribute ()
| |
methods of HTTPSession
| +----lib (.jar, .zip -tags & utility libs
| called by server side classes)
Dispatching Requests +---------web.xml (web app deployment descriptor)
Get a reference to RequestDispatcher object using +---------.tld (tag lib descriptor files used by web
ServletContext sc = this.getServletContext(); | container to validate the tags and also
RequestDispatcher rd = sc.getRequestDispatcher(“/nxtServlet”); | by JSP page development tools)
//jspfile.jsp in case of dispataching request to JSP |
getRequestDispatcher() also available under ServletRequest takes +----------Other Directories (e.g. META-INF, SRC,
relative paths as well JRE etc.)
 To forward the request to another servlet or jsp to fill out the
whole response, response to partially processed request, use
if(rd!=null) rd.forward(req,res) Deployment Descriptors
 forward can be used for servlet chaining.  It is an XML test-based file (usually web.xml) under WEB-INF
forward differs from sendDirect() as forward does not involve  Purpose is to describe the component’s deployment settings:
communication with the client who would be unaware of this  Servlets/JSP definitions
chaining at server side  Mapping requests to servlets/JSP
forwarding servlet must not call getOutputStream or getWriter so  Initialization parameters
as to allow the next servlet to write the response.
 MIME types
To include content (banner, copyright info etc.) from a resource
 Welcome and error pages
(servlet, JSP page, HTML file) in the response, use
if(rd!=null) rd.include(req,res)  Security authorization & authentication
Included web resource has full access to HTTP request but limited  In web.xml, include a header to specify version/location of the
document type definition (DTD) as:
access to HTTP response. They can only write body the response and
commit response. However, they cannot set HTTP response headers <!DOCTYPE web-app PUBLIC
“-//Sun Microsystems, Inc, //DTD Web Application 2.2/EN”
or call methods that can set response headers.
Remember to catch the Exception and print it using
e.getMessage();  Main body in enclosed between
<web-app> ......</web-app> tags
Inside the body, declare servlets (name, class file) and map them to
Packaging and Deploying a Web Application one or more URL patterns
 Also declare init and context param, error, and welcome pages
Web Application = Servlets + JSP pages + HTML files + other inside the body
resources required by web application like images and documents  Sample deployment descriptor is shown below:

Web Archive (WAR) <web-app>

A .war file defines and represents a single web application. <servlet>
It contains all the elements that make up the web application. <servlet-name>ShoppingCart</servlet-name>
Prepared by: Syed Feroz Zainvi
Notes on Servlets
<description>Lists</description> 2. SimgleThreadModel: By implementing
<display-name>ShoppingCart</display-name> javax.servlet.SingleThreadModel.
<servlet-class>com.MyJ2EE.Servlets.srvltShopCart</servlet-class>  Server will manage a pool of instances
<init-param> and guarantees one thread per instance
<param-name>listOrders</param-name>  Performance over-kill in case of multiple
<param-value>com.MyJ2EE.Act.ItemsAction</param-value> instances – synchronized block is preferred
<context-param> Invoker Servlet: Servlet that executes anonymous
<param-name>contactus</param-name> servlets that are not mentioned in web.xml
<param-value>mail@myserver.com</param-value> Used for debugging and testing purposes
</context-param> Such servlet class is provided by web container
<servlet-mapping> like Tomcat and its entry to be made in web.xml
 In Servlet API 2.4 (J2EE 1.4) following were
<welcome-page> RequestListener: This is In addition to session
<location>index.html</location> and context listener, to observe as requests are created,
</welcome-page> destroyed and attributes are added or removed from request
<error-page> Invoke Filter under RequestDispatcher
<exception-type>Exception.PageNotFound</exception-type> <locale-encoding-mapping-list> addition to
<location>/errorpage1.html</location> web.xml
</error-page> SingleThreatModel: Being confusing & does
<web-app> not the solve problem completely, this was
deprecated. Synchronized block and avoiding use
 init-param can be get using getInitParameter, of instance variables are recommended.
getInitParameterNames methods of ServletContext
 context-param are parameters that are shared constants within the
web application. References
Enhancements in Servlets
Servlet API 2.3 in (J2EE 1.3) added following: • J2EE Unleashed, Joseph J. Bambara, Paul T. Allen,
 Application Life Cycle Events: Gives greater interaction Techmedia
with ServletContext and HttpSession.
 Event notifications for state change through
session and context listerners – startup, shutdown, creation, • Sang Shin’s presentation on J2EE available at
change in attributes http://www.javapassion.com/j2ee
 Listeners must be registered in web.xml and
get/set methods are available in listener interfaces • Codenotes on J2EE, Gregory Brill, Random House

 Filtering: Filter is a reusable piece of code that can

inspect or transform the content of HTTP request or Coming Next Week
response by performing custom actions like logging,
compression, caching, authentication, access control, • A sample program for servlets demonstrating above
encryption etc. concepts

• Developing servlets in MyEclipse and Netbeans IDE

Filter can be written by implementing
javax.servlet.Filter interface [init, destroy, doFilter()] and
• Deploying servlets on J2EE Reference App Server, JBoss,
must be packaged into .war for the application.
and Tomcat
Filters can be chained and plugged-in at
deployment time
 Filters are specified in web.xml using
<filter>,<filter-name>,<filter-class>, <filter-
mapping>,<url-pattern> tags.

 Servlet Sycnchronization: Mutliple clients can invoke

service() method of a servlet. To avoid race condition and
thereby corrupted data, either of the following
synchronization technique must be used:
1. synchronized(this){} block: Guarantees only
one thread can execute within a section of

Prepared by: Syed Feroz Zainvi