Unit 3: Servlet API and Overview: Prepared By: Prof. Ruchita Macwan
Unit 3: Servlet API and Overview: Prepared By: Prof. Ruchita Macwan
Prepared by:
Prof. Ruchita Macwan
Contents…
1. Dynamic Content
2. Saving Data on Server
Common Gateway Interface (CGI)
• CGI (Common Gateway Interface) is used to
provide dynamic content to the user.
• CGI is used to execute a program that resides
in the server to process data or access
databases to produce the relevant dynamic
content.
• Programs that resides in server can be written
in native operating system such as C++.
Disadvantages of CGI
Servlets can link directly to the Web server CGI cannot directly link to Web server.
Session tracking and caching of previous Session tracking and caching of previous
computations can be performed computations cannot be performed
Automatic parsing and decoding of HTML form Automatic parsing and decoding of HTML form
data can be performed. data cannot be performed.
Servlets can read and Set HTTP Headers CGI cannot read and Set HTTP Headers
Servlets can handle cookies CGI cannot handle cookies
Servlets can track sessions CGI cannot track sessions
Servlets is inexpensive than CGI CGI is more expensive than Servlets
What is a Container?
• Servlets do not have a main method.
• They are under the control of another java
application called Container.
• When a web server like Apache gets a request
for a servlet it is not handed to servlet itself,
but to the Container in which servlet id
deployed.
What does container give you?
• Communication support
• Lifecycle Management
• Multithreading support
• Declarative security
• JSP support
Life Cycle of Servlet
Loading and initialization
• The container calls init() method on servlet
instance after the servlet instance is created.
• A servlet is normally created when a user invokes
a URL corresponding to the servlet for the first
time; however the servlet is loaded on the server
when a Servlet container maps user request to
the servlet.
• It is called only once in the servlet’s lifetime.
• The following code snippet shows init method
definition:
Continue…
public void init() throws ServletException
{
//Initialization Code
ServletConfig config=getServletConfig();
String param1=config.getInitParameter(“parameter1”);
}
Service() method
• Each time a server recieves a request for the
servlet, the server creates a new thread and
calls the service() method.
• The service() method verifies the HTTP
request type (GET, POST, PUT, DELETE etc.) and
accordingly calls doGet(), doPost(), doPut(),
doDelete() etc methods.
• The following code snippet explains
implementation of post() method:
Continue…
<html>
<form name=“myform” method=“post”>
<body>
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
</form>
</body>
</html>
Continue….
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
//Servlet Code
}
Destroy() method
• The destroy() method runs only once during the
lifetime of a servlet, and signals the end of the
servlet instance.
• A servlet container holds a servlet instance till the
servlet is active or its destroy() method is called.
• The following code snippet shows method signature
of destroy() method:
public void destroy()
• As soon as destroy() method is activated, the Servlet
Container releases the servlet instance.
Each Servlet runs in a separate thread
Exploring the Servlet API
• The below two packages have all the interfaces and classes,
which are required by Servlet API.
1. javax.servlet
2. javax.servlet.http
String message;
@Override
public void init()
{
message = "This is my first servlet example.";
}
Continue…
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Servlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Servlet1 at " + request.getContextPath() + "</h1>");
out.println(message);
out.println("</body>");
out.println("</html>");
}
@Override
public void destroy() {}
}
Deployment Descriptor
• When you deploy your servlet into web container, a
fairly simple XML document called the Deployment
Descriptor (DD) to tell the Container how to run
servlets and JSP’s.
• The two DD elements used for URL mapping are:
1. <servlet>
maps internal name to fully qualified class name.
2. <servlet-mapping>
maps internal name to public URL name.
Continue…
So, Deployment Descriptor is basically used for:
• Mapping URL to Servlet class.
• Initializing parameters.
• Defining Error page.
• Security roles.
• Declaring tag libraries.
Example
What does being a servlet offer you?
A Servlet Config Object
• One ServletConfig object per servlet.
• Use it to pass deploy time information to th
servlet that you don’t want to hardcore into
the servlet.
• Use it to access ServletContext.
• Parameters are configured in deployment
descriptor.
Methods of SevletConfig Interface
• getInitParameter(String)
• Enumeration getInitParameterNames()
• getServletContext()
• getServletName()
A ServletContext object
• One ServletContext per Web app.
• Used to acess the web app parameters.
• Used as a kind of application bulletin board
where you can put up messages.
• Used to get server info, including the name
and version of the container, and the version
of the API that’s supported.
Methods of SevletContext Interface
• getInitParameter(String)
• getInitParameterNames()
• getAttribute(String)
• getAttributeNames()
• setAttribute(String)
• removeAttribute()
Init Parameters
• We have already seen the request parameters that
come with doGet() or doPost() but servlets have
initialization parameters as well.
• Each registered servlet name can have specific
initialization (init) parameters associated with it.
• Init parameters are available to the servlet at any time;
they are often used in init() to set initial or default
values for a servlet or to customize the servlet’s
behavior in some way.
Example…
Context init parameters
• Context init parameters work just like servlet init
parameters, except context parameters are available
to the entire webapp, not just a single servlet.
• It means that any servlet and JSP in the web app
automatically has access tp context init parameters.
• Hence there is no need about configuring DD for
every servlet.
• And when the value of the parameter changes you
only have to change it at one place.
Example…
Continue….
Continue…
• When the Container initializes a servlet, it
makes a unique ServletConfig for the servlet.
• The Container reads the servlet init
parameters from the DD and gives them to
the ServletConfig, then passes the
ServletConfig to the servlet’s init() method.
• The servlet init parameters are read only once
when the container initializes the servlet.
Difference between the two
parameters
Attributes in Servlet
• An attribute is an object set into one of the three other
servlet API objects-ServletContext, HttpServletRequest or
HttpSession.
• It can be simply thought as a name value pair where
name is a String and the value is an object.
• An attribute is like an object pinned to a bulletin board.
Somebody stuck it on the board so that others can get it.
• The question is what is the scope of this attributes. In
other words who can see these attributes and how long
does it live.
Attributes are not parameters
Three scopes: Context, Request & Session
• Context Scope
Continue…
• Context scope or application scope starts from the point
where a web application is put into service (started) till it is
removed from service (shutdown) or the web application is
reloaded. Parameters/attributes within the application scope
will be available to all requests and sessions.
• Application scope is denoted by
javax.servlet.ServletContext interface.
• In a servlet, you can get application object by
calling getServletContext() from within the servlets code
directly (the servlet itself implements the ServletConfig
interface that contains this method) or by explicitly
calling getServletConfig().getServletContext().
• The web container provides one ServletContext object per
web application per jvm.
Session scope
Continue…
• Due to this requirement servlet container supports request dispatching within the
same context.
b. include()
When you invoke a include request, it includes the response of the requested
response in the current servlet/jsp response.
SendRedirect Method
• The sendRedirect() method of HttpServletResponse interface can be used
to redirect response to another resource, it may be servlet, jsp or html file.
• It accepts relative as well as absolute URL.
• It works at client side because it uses the url bar of the browser to make
another request.
• The SendRedirect() method causes the web container to return to the
browser indicating that a new URL should be requested.
• Since the browser issues a completely new request any object that are
stored as request attributes before the redirect occurs will be lost.
• Syntax:
response.sendRedirect(“url");
e.g.
response.sendRedirect("http://www.google.com");
Servlet Filter API
• A filter is a java class that is called for responding to
the requests for resources such as servlets and JSP.
• Filters intercept and process requests before the
requests are forwarded to servlets and process the
response after the response has been generated by
servlet.
• Filters need to be configured in order to serve client
requests.
• Filters can also be put into chain, where multiple
filters can b invoked one after the other.
Need of Filters
• Suppose a web application formats data to presented to client
in specific format say word. At a later point of time client
requires data in some other format say excel, pdf etc. then
instead of modifying the code every time a filter can be
created to transform data dynamically.
• Session validation
• Logging operations
• Authentication
• Data compression
• Encryption/Decryption
• Image conversion
The Filter API
Method Description
init() method is invoked only once. It is
public void init(FilterConfig config)
used to initialize the filter.
doFilter() method is invoked every time
public void doFilter(ServletRequest
when user request to any resource, to
request,ServletResponse response,
which the filter is mapped.It is used to
FilterChain chain)
perform filtering tasks.
This is invoked only once when filter is
public void destroy()
taken out of the service.
The FilterConfig Interface
• The javax.servlet.FilterConfig interface is an argument to the init()
method.
• The Container gives us through this interface some information about
initial parameters and access to the ServletContext as well.
Method Description
public String getFilterName() Returns the filter-name of this filter as defined
in the deployment descriptor.
public ServletContext getServletContext() Returns a reference to the ServletContext in
which the caller is executing.
public String getInitParameter(String name) Returns a String containing the value of the
named initialization parameter, or null if the
parameter does not exist.
public Enumeration getInitParameterNames() Returns the names of the filter's initialization
parameters as an Enumeration of String
objects, or an empty Enumeration if the filter
has no initialization parameters.
The FilterChain Interface
• The javax.servlet.FilterChain interface is an argument to the doFilter()
method. This interface has only one method, doFilter(), which are used by
the programnmer to causes the next filter in the chain to be invoked.
Method Description
public void doFilter(ServletRequest Causes the next filter in the chain to be
request, ServletResponse response) invoked, or if the calling filter, is the last
filter in the chain, causes the resource at
the end of the chain to be invoked.
The FilterChain Interface
Configuring a Filter
• The deployment descriptor is used to tell the container which, if any, filters in which
sequence to call for each servlet in the application.
• web.xml:-
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
Configuring a Filter
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
Understanding session and state
• The HTTP protocol uses stateless connections.
• The client browser makes a connection to the server,
sends the request, gets the response, and closes the
connection.
• In other words, the connection exists for only a single
request/response.
• Because the connections don’t persist, the Container
doesn’t recognize that the client making a second
request is the same client from previous request.
• As far as the Container is concerned each request is
from a new client
Continue…
• A session can be defined as a collection of HTTP requests
shared between a client and web server over a period of
time.
• While creating a session its lifetime is set (by default: 30
min) after which the session expires and the resources
are returned back to servlet engine.
• To check whether the request is from the same client,
the Container generates a unique session id and gives it
back to the client along with response.
• The client sends back the session id with each
subsequent request.
• The Container sees the id, finds the matching id and
associates the session with the request.
Session Tracking
• Session tracking is a process of gathering the user
information from Web pages, which can be used in an
application.
• Session tracking involves identifying the user session by
related id numbers and tying the requests to their sessions
by using the said id number.
• Following session tracking mechanisms can be used to track
session details:
1. Http session object
2. Cookies
3. Hidden form fields
4. URL Rewriting
Http Session object
• An HttpSession object can hold conversational state across multiple
requests from the same client.
• In other words, it persists for an entire session with a specific client.
• We can use it to store everything we get back from the client in all the
requests the client makes during a session.
• HttpSession object is obtained by calling the public method getSession()
of HttpServletRequest, as below:
HttpSession session = request.getSession();
or
HttpSession session = request.getSession(boolean);
where , true= request for new session
false= request for previous session
Methods of Http Session object
S.N. Method & Description
public Object getAttribute(String name)
1 This method returns the object bound with the specified name in this session, or null
if no object is bound under the name.
public Enumeration getAttributeNames()
2 This method returns an Enumeration of String objects containing the names of all the
objects bound to this session.
public long getCreationTime()
3 This method returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
public String getId()
4
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
5 This method returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.
public int getMaxInactiveInterval()
6 This method returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses.
Continue…
public void invalidate()
7
This method invalidates this session and unbinds any objects bound to it.
(2) Setting the maximum age: You use setMaxAge to specify how long (in
seconds) the cookie should be valid. Following would set up a cookie for
24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use
response.addCookie to add cookies in the HTTP response header as
follows:
response.addCookie(cookie);
Retrieving cookies in Servlet
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null )
{
out.println("<h2>Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}
else{ out.println( "<h2>No cookies founds</h2>");}
Deleting cookies in Servlet
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null )
{
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 )
{
cookie.setMaxAge(0); response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( ) + "<br/>");
}
}}
else{ out.println( "<h2>No cookies founds</h2>");}
Hidden Form Fields
• A web server can send a hidden HTML form field along with a unique
session ID as follows:
• This entry means that, when the form is submitted, the specified name
and value are automatically included in the GET or POST data.
• Each time when web browser sends request back, then session_id value
can be used to keep the track of different web browsers.
• This could be an effective way of keeping track of the session but clicking
on a regular (<A HREF...>) hypertext link does not result in a form
submission, so hidden form fields also cannot support general session
tracking.
URL Rewriting
• The javax.servlet.HttpServletResponse class includes
a method that will encode a URL with the current
session ID, in the event that the user making the
servlet request has disabled cookies.
• In fact, if you use the
HttpServletResponse.encodeURL(String url) method
to encode the URLs that are used in a servlet, this
method takes care of URL rewriting if necessary, and
you won't have to worry about whether cookies are
enabled in users' browsers.
URL Rewriting Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
super.init(config);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
URL Rewriting Example
out.println("<html>");
out.println("<head><title>URL Rewriting</title></head>");
out.println("<body>");