Servlets
Unit Outcomes
Topics and Sub-topics
6.1 LifeCycle of Servlet
6.2 Creating Simple Servlet: The Servlet API,
javax.servlet package, Servlet Interface, ServletConfig
Interface, ServletContext Interface, ServletRequest
Interface, ServletResponse Interface, Generic Servlet Class
6.3 The javax.servlet.http package: httpServletRequest
Interface, httpServletResponse Interface, httpSession
Interface, Cookie Class, HttpServlet Class,
httpSessionEvent Class, httpSessionBindingEvent Class,
6.4 Handling HTTP Requests and Responses , Handling
HTTP GET Requests, Handling HTTP POST Request
Introduction to Servlet
Basics of how web browsers and servers cooperate to provide
content to user
Example of Static Web Page:
User enters URL in browser (https://msbte.org.in/)
Browser generates an HTTP Request to appropriate Server
(msbte server)
Web server maps this request to a specific file (index..html)
File is return in an HTTP Response (in the form of HTML) to the
browser.
Header in the response indicates type of content(html/text).
MIME (Multipurpose Internet Mail Extension) are used for this
purpose.
Introduction to Servlet
Example of Dynamic Web Page:
Online store uses database to store its
information.
The data could be price, products for sale and it
must be updated.
User access this information via web page.
The content of such pages must be dynamically
generated to reflect the latest information
Introduction to Servlet
Existing Problems:
Earlier days, server could dynamically
construct a page by creating a separate
process for each client.
That process open a connection with database.
Communication takes place via Common
Gateway Interface(CGI).
C,C++ and Perl used to create CGI programs.
Introduction to Servlet
Problems with CGI:
Serious performance problems
Expensive in terms of processor and memory
resources required to create separate process
for each client request.
Also expensive to open and close database
connection
CGI programs are not platform-independent.
Introduction to Servlet
Problems with CGI:
Serious performance problems
Expensive in terms of processor and memory
resources required to create separate process
for each client request.
Also expensive to open and close database
connection
CGI programs are not platform-independent.
Introduction to Servlet
Advantages of Servlet:
Performance better
Executes within the address space of a web server
Not necessary to create a separate process for each client
request
Platform independent as written in Java
Provide security for resources on server
Full functionality of Java class libraries is available to
Servlet
Communicate with Socket
Servlet
LIFE CYCLE OF SERVLET
Three methods are
central to the life cycle
of a servlet
1. init()
2. service()
3. destroy()
Implemented by every
servlet
Invoked at specific time.
LIFE CYCLE OF SERVLET
First Step
User enters URL in browser
Browser generates an HTTP Request to appropriate
Server
Second Step
The server received request and maps this request to a
specific Servlet.
The Servlet is dynamically retrieved and loaded into
server space.
Third Step
Server invoke init() method
init() method is invoked only when the servlet is first
loaded into memory(only once).
We can pass initialization parameters to the servlet for
their configuration
LIFE CYCLE OF SERVLET
Fouth Step
Server invoke service() method of Servlet
This method is invoked to process the HTTP request.
Servlet can read the data provided in HTTP request
Also we formulate HTTP Response for the client request
Servlet remains in address space of Server to process
any other HTTP Requests from other clients
The service() method is called for each HTTP Request.
Last Step
Server may decide to unload Servlet from its memory
At this time server calls destroy() method to relinquish
any resources such as file handles.
Requirement for Servlet
Programs
We need Servlet Container or Server
Popular Servers
Glassfish, Apache Tomcat
Apache Tomcat (Downloads:
https://tomcat.apache.org/)
Is an open source product
Maintained by Apache Software Foundation
Can be used byn NetBeans IDE
Creating Simple Servlet
Once you installed Tomcat the servlet-api.jar file contained all
the classes and interfaces needed to create servlets.
C:\Apache Software Foundation\Tomcat 9.0\lib
To make servlet-api.jar accessible, update the CLASSPATH
environment variable
CLASSPATH=C:\Apache Software Foundation\Tomcat
9.0\lib
Creating Simple Servlet
Important Directories in Tomcat Folder
webapps (main directory where we create web
application)
examples
WEB-INF
classes
o put your classfile here
web.xml (the important file where we write deployment
descriptor for Servlet)
Creating Simple Servlet
Web.xml
For a Java servlet to be accessible from a browser, you must tell the
servlet container what servlets to deploy, and what URL's to map the
servlets to.
This is done in the web.xml file of your Java web application.
First you configure the servlet. This is done using the <servlet>
element. Here you give the servlet a name, and writes the class name of
the servlet.
Second, you map the servlet to a URL or URL pattern. This is done in
the <servlet-mapping> element. In the above example, all URL's
Creating Simple Servlet
Web.xml
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
Deployment
<servlet-mapping> Descriptor
<servlet-name>Test</servlet-name>
<url-pattern>TestApp</url-pattern>
</servlet-mapping>
Creating Simple
Servlet
Respons
Client Servlet
e Request
Browse 1
r Servlet
2Server
Servlet
3
Servlet
4
Web.xm
l
First Example
import java.io.*;
import javax.servlet.*; / / Servlet API
public class First extends GenericServlet
{
public void service(ServletRequest req,ServletResponse
res) throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Example
javax.servlet
This package contains the classes and interfaces required to build servlets
First
Subclass of GenericServlet class which provides the functionality that simplifies the creation of
servlet
Don’t need to write init() and destroy() method of Servlet Lifecyle
Only service() method need to overwrite
public void service() method
This method handles the request from a client
ServletRequest argument enables to read the data that is provided in request
ServletResponse object in argument enables a servlet to formulate a response for the client
throws IOException,ServletException
res.setContentType("text/html"): set the response content type
Servlet
API
Two packages contains classes and interfaces that are
required
to build servlets.
1. javax.servlet
2. javax.servlet.http
javax.servlet
Package
Following table summarizes several key interfaces provided in
this package.
The most significant of these is Servlet interface
Servlet
Interface
All servlets must implements the Servlet interface.
It declares the init(), service() and destroy() methods that
are called by the server during the lifecycle of a servlet.
The getServletConfig() method is called by the servlet to
obtain initialization parameters.
The getServletInfo() method provide a string of useful
information about the servlet (example version info)
Servlet
Interface
ServletConfig
Interface
Allows servlet to obtain configuration data when it is
loaded
ServletContext Interface
Enables servlets to obtain information about their environment.
ServletRequest
Interface
Enables servlets to obtain information about client
request.
ServletResponse
Interface
Enables servlets to formulate a response for
client.
javax.servlet
Package
Following table summarizes several key classes provided in
this package.
GenericServlet
Class
Provides implementation of basic lifecycle methods for a
servlet.
This class implements Servlet and ServletConfig
Interfaces
In addition the following methods are used to append a
string to the server log file.
void log(String s)
void log(String s,Throwable e)
ServletInputStream
Class
Extends InputStream Class
Provides an input stream that a servlet developer can use
to read the data from a client request.
Additional methods are
int readLine(byte b[], int offset, int size) throws
IOException
ServletIOutputStream
Class
Extends OutputStream Class
Provides an input stream that a servlet developer can use
to write the data from a client response.
ServletException
Class
Javax.servlet defines two exceptions
ServletException: Indicates a servlet problem has
occurred
UnavailableException: It extends ServletException and
indicates that a servlet is unavailable
Steps to create
1. Servlet
Create and compile import
import javax.servlet.*;
java.io.*;
the Servlet Source
public class First extends
GenericServlet{ public void
code
service(ServletRequest
req,ServletResponse res)
2. Copy the class file throws IOException,ServletException{
(First.class) to proper res.setContentType("text/html");
directory PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic
C:\Apache Software servlet</b>");
}out.print("</body></html>");
Foundation\Tomcat 9.0\ }
webapps\examples\WEB-
INF\classes
Steps to create
Servlet
3. Create deployment
descriptor for servlet.To do this
update the web.xml file
Example:
Steps to create
Servlet
4. Start Tomcat
5. Start a web browser and request the
servlet
localhost:9090/examples/TestApp
The javax.servlet.http
Package
• The javax.servlet.http package contains a number of
interfaces and classes that are commonly used by servlet
developers.
• You will see that its functionality makes it easy to build
servlets that work with HTTP requests and responses.
The javax.servlet.http
Package: interfaces
HttpServletRequest Interface
Methods
HttpServletRequest Interface
Methods
The HttpServletResponse
Interface
• The HttpServletResponse interface enables a servlet to
formulate an HTTP response to a client. Several
constants are defined.
• These correspond to the different status codes that can be
assigned to an HTTP response.
• For example, SC_OK indicates that the HTTP request
succeeded, and SC_NOT_FOUND indicates that the
requested resource is not available.
HttpServletResponse Interface
Methods
HttpServletResponse Interface
Methods
The HttpSession Interface
The javax.servlet.http
Package: CLASSES
Cookie Class
• The Cookie class encapsulates a cookie. A cookie is
stored on a client and contains state information.
• Cookies are valuable for tracking user activities.
• For example, assume that auser visits an online store. A
cookie can save the user’s name, address, and other
information. The user does not need to enter this data
each time he or she visits the store.
Cookie Class
• HttpServletResponse contains a method addCookie(), which
can be used by a servlet to write a cookie to a user’s machine.
• This data for that cookie is then included in the header of the
HTTP response that is sent to the browser.
• The names and values of cookies are stored on the user’s
machine.
• Some of the information that is saved for each cookie
includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
Cookie Class: Constructor
• There is one constructor for Cookie. It has the signature
shown here:
Cookie(String name, String value)
• Here, the name and value of the cookie are supplied as
arguments to the constructor.
Cookie Class: Method
HttpServlet Class
• The HttpServlet class extends GenericServlet.
• It is commonly used when developing servlets that receive
and process HTTP requests.
HttpServlet Class
Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods that handle
the various types of HTTP requests.
A servlet developer typically overrides one of these methods.
These methods are :
doDelete( )
doGet( )
doHead( )
doOptions( )
doPost( )
doPut( ),
doTrace( ).
However, the GET and POST requests are commonly used when
handling form input.
doGet() vs doPost()
Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyHttpServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<B>This is HTTP Servlet");
pw.close();
}catch(Exception e){}
}
}
Output
Deployment Descriptor written in
web.xml
Cookie Example: 1 File
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
Cookie Example: 2 File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
Cookie Example: 3 File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}
}
Session Tracking
HTTP is a stateless protocol.
Each request is independent of the previous one.
However, in some applications, it is necessary to save state
information so that information can be collected from
several interactions between a browser and a server.
Sessions provide such a mechanism.
Session Tracking
A session can be created via the getSession() method of
HttpServletRequest. An HttpSession object is returned.
This object can store a set of bindings that associate names
with objects.
The setAttribute(), getAttribute(), getAttributeNames(), and
removeAttribute() methods of HttpSession manage these
bindings.
It is important to note that session state is shared among all
the servlets that are associated with a particular client.
Program
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
Example
The getSession( ) method gets the current session. A new
session is created if one does not already exist.
The getAttribute( ) method is called to obtain the object that
is bound to the name “date”. That object is a Date object
that encapsulates the date and time when this page was last
accessed. A Date object encapsulating the current date and
time is then created.
The setAttribute( ) method is called to bind the name “date”
to this object.
Referenc
es
Java The Complete Reference By Herbert
Schildt
Images from Internet