Lesson 2 - Servlet I
Lesson 2 - Servlet I
We have learned that web server generates two types of responses: Static and
Dynamic.
However, a web server can generate static responses in the form of HTML.
To generate dynamic response, a programming language that performs dynamic operations is needed.
Servlet is a Java program that can perform dynamic operations and send to web server. The web
server then sends this response to web client.
Static Response
Every time you type https://www.google.com/ in your browser, you are directed to the Google home page.
This is called a static page as the web server displays the same HTML page every time the client requests.
Dynamic Response
When users login to their Facebook account, different pages will be generated for different users. You would see
the pages relevant to you.
This requires multiple responses from the server, called dynamic response. This uses Servlets.
Client-Server Architecture with Java Servlet
Http request
Web Server
Http response
Think Through!
Web server is a program that sends HTTP response, and Servlet is a Java Program
that deals with classes and objects.
A web container is built on top of the Java EE platform, and it implements the Servlet API and the services
required to process HTTP (and other Transmission Control/Internet Protocol [TCP/IP]) requests.
• Java Servlets are components that must exist in a web container. Web container activates the Servlet
that matches the requested URL by calling the service method on an instance of Servlet class.
• Activation of the service method for a given HTTP request is handled in a separate thread within the
web container protocol.
Client-Server Architecture with Web Container
The lifecycle of a Servlet is controlled by the web container in which the Servlet has been deployed.
Http request
User Workstation
Web Server
Browser
Http request
Http response
Web Container
Http response
request object
response object
Servlet
Advanced Java
Topic 2—Servlet API, Interface, and Methods
• Servlets API
• Servlet Interface and Classes
• Servlet API Interface
• Servlets API Hierarchy to Create Servlet
• Servlets Methods
• Generic Servlet Abstract Class
• Generic Servlet Abstract Class Methods
• HttpServlet Abstract Class Methods
Servlets API
Servlet API contains a number of classes and interfaces that describe the contracts between a servlet class and
the runtime environment provided for an instance by a conforming servlet container.
Servlet API provides the following two packages that contain its classes and interfaces:
javax.servlet.*; Classes and interfaces defines the contracts between a Servlet class and the
runtime environment provided for an instance of such a class by a conforming
Servlet container.
javax.servlet.http.*; Classes and interfaces defines the contracts between a Servlet class running
under the HTTP protocol and the runtime environment provided for an
instance of such a class by a conforming Servlet container.
Servlet Interface and Classes
Exception EventListener
ServletException interface
EventObject
ServletContextListener
UnavailableException ServletContextEvent
EventListener
interface
ServletContextAttribute Event
interface
interface ServletContextAttributeListener
ServletConfig
Servlet interface
interface
ServletRequest ServletResponse
Serializable
GenericServlet ServletRequestWrapper ServletResponseWrapper
FilterChain ServletInputStream
Servlet API Interface
javax.servlet.FilterConfig Passes information to a filter during initialization
javax.servlet.RequestDispatcher Sends request and response object to any resource (such as a Servlet, HTML file, or
JSP file) on the server
javax.servlet.Servlet Defines methods that all Servlets must implement
javax.servlet.ServletConfig A Servlet configuration object used by a Servlet container to pass information to a
Servlet during initialization
javax.servlet.ServletContext Defines a set of methods that a Servlet uses to communicate with its Servlet
container, for example, to get the MIME type of a file, dispatch requests, or write to
a log file
javax.servlet.ServletContextAttri Implementation of this interface receives notifications of changes to the attribute
buteListener list on the Servlet context of a web application
javax.servlet.ServletContextListe Implementation of this interface receive notifications about changes to the Servlet
ner context of the web application they are a part of
javax.servlet.ServletRequest Defines an object to provide client request information to a Servlet
javax.servlet.ServletRequestAttri A ServletRequestAttributeListener can be implemented by the developer interested
buteListener in being notified of request attribute changes
javax.servlet.ServletRequestListe A ServletRequestListener can be implemented by the developer interested in being
ner notified of requests coming in and out of scope in a web component
javax.servlet.ServletResponse Defines an object to assist a Servlet in sending a response to the client
Servlets API Hierarchy to Create Servlet
javax.servlet.Servlet (I) All Servlets must implement Servlet interface that defines lifecycle methods.
javax.servlet.http.Http Other way of creating a Servlet is to extend HttpServlet abstract class. HttpServlet
Servlet (C) abstract class extends GenericServlet abstract class.
1. init
2. service
3. destroy
4. getServletInfo
5. getServletConfig
Servlet Methods
init
init method is called by Servlet container to indicate to a Servlet that it is being placed into
init
service.
service It is declared as: void init (ServletConfig config)
destroy
getServletInfo
getServletConfig
Servlet Methods
service
init service method is called by the Servlet container to allow the Servlet to respond to a request.
getServletInfo
getServletConfig
Servlet Methods
destroy
init destroy() indicates that the Servlet is being taken out of service.
service
It is declared as: public void destroy()
destroy
getServletInfo
getServletConfig
Servlet Methods
getServletInfo
service
It is declared as: public java.lang.String getServletInfo()
destroy
getServletInfo
getServletConfig
Servlet Methods
getServiceConfig
init Returns a ServletConfig object, that contains initialization and start-up parameters for this
Servlet.
service
It is declared as: public ServletConfig getServletConfig()
destroy
getServletInfo
getServletConfig
Generic Servlet Abstract Class
void init(ServletConfig Called by the Servlet container to indicate to a Servlet that the Servlet is being
config) placed into service
void log(java.lang.String Writes the specified message to a Servlet log file, prepended by the Servlet's
msg) name
void log(java.lang.String
Writes an explanatory message and a stack trace for a given Throwable throwable
message, java.lang.Throwable
exception to the Servlet log file, prepended by the Servlet's name
t)
abstract void
service(ServletRequest req, Allows the Servlet to respond to a request.
ServletResponse res)
HttpServlet Abstract Class Methods
It provides an abstract class to be sub-classed to create an HTTP Servlet suitable for a website.
init and destroy Used to manage resources that are held for the life of the Servlet
When a request is mapped to a Servlet, the container performs the following steps if an instance of the
Servlet does not exist.
Called once init method (ServletConfig config) Initiates and calls init()
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
STEPS TO CREATE DYNAMIC WEB PROJECT IN ECLIPSE
Create dynamic web
project in eclipse
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
STEPS TO ADD SERVER TO PROJECT
Create dynamic web
project in eclipse
1. Click on “Windows” in menu bar
Add Server to project
2. Click on “preference”
Run Server (Apache
Tomcat) 3. Click on “Server”
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
RUN SERVER (APACHE TOMCAT)
Create dynamic web
project in eclipse
1. Run Apache with eclipse
Add Server to project
2. Click on “Window”
Run Server (Apache
Tomcat) 3. Click on “show view”
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
All web pages like html, css, and jsp should be added in the WebContent folder
Configure and Deploy Servlet
CREATE JAVA CLASS (SERVLET)
Create dynamic web
project in eclipse
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
CREATE web.xml FILE
Create dynamic web
project in eclipse
• The web.xml deployment descriptor is used by the web container to configure servlet
Add Server to project component. The Servlet definition also specifies the fully qualified class that implements the
component.
Run Server (Apache
Tomcat)
• The web container creates an instance of each Servlet definition in the deployment descriptor
Create HTML file
• There can be multiple Servlet definitions
Create Java class(
Servlet)
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
CONFIGURE A SERVLET DEFINITION
Create dynamic web
project in eclipse
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
CONFIGURE A SERVLET MAPPING
Create dynamic web
project in eclipse
Add Server to project When the user selects the home page by the way of URL
http://localhost:8080/projectname/urlpattren, the web container responds with the HTML
Run Server (Apache code for the home page.
Tomcat)
Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Advanced Java
DEMO—Configure and Deploy Servlet
Advanced Java
Topic 5—ServletsRequest, ServletResponse
• ServletRequest
• ServletRequest Interface
• Servlet Response
ServletRequest
• This object provides data including parameter name and values, attributes, and an input stream.
ServletRequest Interface
java.lang.Object
Returns the value of the named attribute as an object, or returns null if no
getAttribute(java.lang.Str
attribute of the given name exists.
ing name)
java.util.Enumeration Returns an Enumeration containing the names of the attributes available to
getAttributeNames() this request.
java.lang.String
Returns the name of the character encoding used in the body of this request.
getCharacterEncoding()
Returns the length of the request body (in bytes) and is made available by the
int getContentLength()
input stream, or -1 if the length is not known.
java.lang.String Returns the MIME type of the body of the request, or returns null if the type is
getContentType() not known.
ServletInputStream
Retrieves the body of the request as binary data using a ServletInputStream.
getInputStream()
java.util.Locale Returns the preferred Locale that the client will accept content, based on the
getLocale() Accept-Language header.
Returns an Enumeration of Locale objects indicating the locales (in decreasing
java.util.Enumeration
order starting with the preferred locale) that are acceptable to the client based
getLocales()
on the Accept-Language header.
ServletRequest Interface
Returns the host name of the Internet Protocol (IP) interface on
java.lang.String getLocalName()
which the request was received
Returns the Internet Protocol (IP) port number of the interface on
int getLocalPort()
which the request was received
java.lang.String Returns the value of a request parameter as a String, or null if the
getParameter(java.lang.String name) parameter does not exist
java.util.Map getParameterMap() Returns a java.util.Map of the parameters of this request
java.util.Enumeration Returns an Enumeration of String objects containing the names of
getParameterNames() the parameters contained in this request
java.lang.String[] Returns an array of String objects containing all of the values the
getParameterValues(java.lang.String given request parameter has, or returns null if the parameter does
name) not exist
Returns the name and version of the protocol the request uses in
java.lang.String getProtocol() the form protocol/majorVersion.minorVersion, for example,
HTTP/1.1
Retrieves the body of the request as character data using a
java.io.BufferedReader getReader()
BufferedReader
void setAttribute(java.lang.String
Stores an attribute in this request
name, java.lang.Object o)
ServletResponse
• The Servlet Container creates these objects to call Servlet's service method.
• To send binary data in a MIME body response, use the ServletOutputStream returned by
getOutputStream().
• To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data,
for example, to create a multipart response, use a ServletOutputStream and manage the character
sections manually.
Advanced Java
Topic 5—ServletConfig, ServletContext
• ServletConfig, ServletContext
• ServletConfig Methods
ServletConfig, ServletContext
ServletConfig:
1. The config object is created by the web container based on the initialization parameters specified in
the deployment descriptor
ServletContext:
java.lang.String
Returns a String containing the value of the named initialization parameter,
getInitParameter(java.lang.String
or returns null if the parameter does not exist
name)
Returns the names of the servlet's initialization parameters as an
java.util.Enumeration
Enumeration of String objects, or returns an empty Enumeration if the
getInitParameterNames()
servlet has no initialization parameters
ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing.
java.lang.String getServletName() Returns the name of this servlet instance
Defines a set of methods that a servlet uses to communicate with its servlet
public interface ServletContext container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file
java.lang.Object
Returns the servlet container attribute with the given name, or returns null
getAttribute(java.lang.String
if there is no attribute by that name
name)
ServletConfig Methods
• Servlet Attributes
• Attribute Specific Methods
Servlet Attributes
Attribute Scope
1. public void setAttribute (String name, Object object): This method is used to set the given
object in the application scope.
2. public Object getAttribute(String name): This method is used to return the attribute for the
specified name.
3. public Enumeration getInitParameterNames(): This method is used to return the names of the
context's initialization parameters as an Enumeration of String objects.
4. public void removeAttribute(String name): This method is used to remove the attribute with
the given name from the servlet context.
Advanced Java
Topic 7—Servlet Collaboration
Collaborating servlets is passing the common information that is to be shared directly by one servlet to
another servlet of html or jsp through various invocations of methods.
Servlet should know about the other servlets with which it is collaborated.
Ways of Servlet Collaboration
• RequestDispatcher interface is used to forward request and response objects to another Servlet
2. forward(-,-)
ServletOne ServletSecond
1. request
forward() method
forward() method: Syntax
RequestDispatcher rd=
request.getRequestDispatcher(“url_pattern_for_servlet or html_file_name”);
rd.forward(request,response)
include() method
2. include(-,-)
ServletOne ServletSecond
4. Final response
is generated
5. Final response is
client sent back to the client
Response Response
include() method
include() method: Syntax
rd.include(request,response);
RequestDispatcher Interface
Validate Servlet
Servlet is a Java program that can perform dynamic operations and send to web
server. The web server then sends this response to web client.
Web container is built on top of the Java SE platform and implements the Servlet
API and the services required to process HTTP (and other Transmission
Control/Internet Protocol [TCP/IP]) requests.
The lifecycle of a Servlet is controlled by the web container in which the Servlet has
been deployed.
Servlet API contains a number of classes and interfaces that defines the contracts
between a servlet class and the runtime environment provided for an instance by
a conforming servlet container.
a. javax.Servlet
b. javax.Servlet.http
d. Both
e. java.Servlet
a. init()
b. service()
c. destroy()
d. getServletInfo()
e. getServlet()
The correct answer is b
Thank You