0% found this document useful (0 votes)
2 views

Unit-6-Servlets_241003_210610 (1)

Uploaded by

kalyanipawar863
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-6-Servlets_241003_210610 (1)

Uploaded by

kalyanipawar863
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

What is Servlet?

Servlet technology is used to create a web application that


resides at server side and generates a dynamic web page.
Servlet technology is robust and scalable because of java
language.
Before Servlet, CGI (Common Gateway Interface) scripting
language was common as a server-side programming language.
What is Servlet?
• Servlet is a technology which is used to create a web
application.
• Servlet is an API that provides many interfaces and classes
including documentation.
• Servlet is an interface that must be implemented for creating
any Servlet. What is a web application?
• GenericServlet is a class that extends the capabilities of the A web application is an application accessible from
the web. A web application is composed of web
servers and responds to the incoming requests. It can respond
components like Servlet, JSP, Filter, etc. and other
to any requests. elements such as HTML, CSS, and JavaScript. The
• Servlet is a web component that is deployed on the server to web components typically execute in Web Server
create a dynamic web page. and respond to the HTTP request.
Difference between Servlet & CGI

CGI (Common Gateway Interface) Servlet : The web container creates threads for handling the
CGI technology enables the web server to call an external multiple requests to the Servlet. Threads have many benefits
program and pass HTTP request information to the over the Processes such as they share a common memory
external program to process the request. area, lightweight, cost of communication between the
For each request, it starts a new process. threads are low.

Disadvantages of CGI The advantages of Servlet are as follows:


1. If the number of clients increases, it takes more time 1.Better performance: because it creates a thread for each
for sending the response. request, not process.
2. For each request, it starts a process, and the web 2.Portability: because it uses Java language.
server is limited to start processes. 3.Robust: JVM manages Servlets, so we don't need to worry
3. It uses platform dependent language e.g. C, C++, about the memory leak, garbage collection, etc.
perl. 4.Secure: because it uses java language.
Life Cycle of Servlet

The web container maintains the life cycle of a servlet


instance.

1. Servlet class is loaded.


2. Servlet instance is created.
3. init() method is invoked.
4. service() method is invoked.
5. destroy() method is invoked.

There are three states of a servlet: new, ready and end.


- The servlet is in new state if servlet instance is created.
- After invoking the init() method, Servlet comes in the
ready state. In the ready state, servlet performs all the tasks.
- When the web container invokes the destroy() method, it
shifts to the end state.
Life Cycle of Servlet

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is
received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once
in the servlet life cycle.
3) init() method is invoked
The web container calls the init() method only once after creating the servlet instance. The init method is used to initialize
the servlet. It is the life cycle method of the javax.servlet.Servlet interface.
Syntax:- public void init(ServletConfig config) throws ServletException
4) service() method is invoked
The web container calls the service() method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls
the service method. Servlet is initialized only once.
Syntax:-public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
5) destroy() method is invoked
The web container calls the destroy() method before removing the servlet instance from the service. It gives the servlet
an opportunity to clean up any resource for example memory, thread etc.
Syntax :- public void destroy()
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet API.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web container.
These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
Interfaces in javax.servlet package Classes in javax.servlet package
• Servlet • GenericServlet
• ServletRequest • ServletInputStream
• ServletResponse • ServletOutputStream
• RequestDispatcher
• ServletRequestWrapper
• ServletConfig
• ServletContext
• ServletResponseWrapper
• SingleThreadModel • ServletRequestEvent
• Filter • ServletContextEvent
• FilterConfig • ServletRequestAttributeEvent
• FilterChain • ServletContextAttributeEvent
• ServletRequestListener • ServletException
• ServletRequestAttributeListener • UnavailableException
• ServletContextListener
• ServletContextAttributeListener
Interfaces in javax.servlet.http package Classes in javax.servlet.http package
• HttpServletRequest • HttpServlet
• HttpServletResponse • Cookie
• HttpSession • HttpServletRequestWrapper
• HttpSessionListener • HttpServletResponseWrapper
• HttpSessionAttributeListener • HttpSessionEvent
• HttpSessionBindingListener • HttpSessionBindingEvent
• HttpSessionActivationListener • HttpUtils (deprecated now)
• HttpSessionContext (deprecated now)
javax.servlet package Interfaces and Classes

Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access information about their
Environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
Class Description
GenericServlet Declares life cycle methods for a servlet.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable
Servlet Interface

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle methods.

Method Description
initializes the servlet. It is the life cycle method of servlet
public void init(ServletConfig config)
and invoked by the web container only once.
public void service(ServletRequest
provides response for the incoming request. It is invoked at
request,ServletResponse response)
each request by the web container.
throws ServletException, IOException
is invoked only once and indicates that servlet is being
public void destroy()
destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
returns information about servlet such as writer, copyright,
public String getServletInfo()
version etc.
The ServletConfig Interface

The ServletConfig interface allows a servlet to obtain configuration data when it is loaded.
Method Description
ServletContext getServletContext( ) Returns the context for this servlet.
String getInitParameter(String param) Returns the value of the initialization parameter named param
Enumeration getInitParameterNames( ) Returns an enumeration of all initialization parameter
names.
String getServletName( ) Returns the name of the invoking servlet

The ServletContext interface enables servlets to obtain information about their environment.

Method Description
String getServerInfo( ) Returns information about the server
void setAttribute(String attr, Object val) Sets the attribute specified by attr to the value passed in val.
Object getAttribute(String attr) Returns the value of the server attribute named attr
void log(String s) Writes s to the servlet log.
The ServletRequest interface enables a servlet to obtain information about a client request.
Method Description
ServletInputStream getInputStream( ) Returns a ServletInputStream that can be used to read binary data from the request. An
throws IOException IllegalStateException is thrown if getReader( ) has already been invoked for this
request.
int getContentLength( ) Returns the size of the request. The value –1 is returned if the size is unavailable.
String getContentType( ) Returns the type of the request. A null value is returned if the type cannot be
determined.
Enumeration getParameterNames( ) Returns an enumeration of the parameter names for this request
String getParameter(String pname) Returns the value of the parameter named pname.
BufferedReader getReader( ) Returns a buffered reader that can be used to read text from the request. An
throws IOException IllegalStateException is thrown if getInputStream( ) has already been invoked for this
request.
String getServerName( ) Returns the name of the server.
int getServerPort( ) Returns the port number.
String getRemoteAddr( ) Returns the string equivalent of the client IP address.
String getRemoteHost( ) Returns the string equivalent of the client host name.
The ServletResponse interface enables a servlet to formulate a response for a client.

Method Description
ServletOutputStream Returns a ServletOutputStream that can be used to write
getOutputStream( ) binary data to the response. An IllegalStateException is
throws IOException thrown if getWriter( ) has already
been invoked for this request.
PrintWriter getWriter( ) throws Returns a PrintWriter that can be used to write character
IOException data to the response. An IllegalStateException is thrown if
getOutputStream( ) has already been invoked for this
request
void setContentLength(int size) Sets the content length for the response to size.
void setContentType(String type) Sets the content type for the response to type.
GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementation of all the methods of these interfaces except the service method. GenericServlet class can
handle any type of request so it is protocol-independent.

Methods of GenericServlet class :-


• public void init(ServletConfig config) - used to initialize the servlet.
• public abstract void service(ServletRequest request, ServletResponse response) - provides service for the
incoming request. It is invoked at each time when user requests for a servlet.
• public void destroy() - is invoked only once throughout the life cycle and indicates that servlet is being
destroyed.
• public ServletConfig getServletConfig() - returns the object of ServletConfig.
• public void init() - it is a convenient method for the servlet programmers, now there is no need to call
super.init(config)
• public ServletContext getServletContext() - returns the object of ServletContext.
• public String getInitParameter(String name) - returns the parameter value for the given parameter name.
• public Enumeration getInitParameterNames() - returns all the parameters defined in the web.xml file.
• public String getServletName() - returns the name of the servlet object.
• public String getServletInfo() - returns information about servlet such as writer, copyright, version etc.
HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http
specific methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class-
public void service(ServletRequest req,ServletResponse res) - dispatches the request to the protected
service method by converting the request and response object into http type.

protected void service(HttpServletRequest req, HttpServletResponse res) - receives the request from the
service method, and dispatches the request to the doXXX() method depending on the incoming http request
type.

protected void doGet(HttpServletRequest req, HttpServletResponse res) - handles the GET request. It is
invoked by the web container.

protected void doPost(HttpServletRequest req, HttpServletResponse res) - handles the POST request. It is
invoked by the web container.

protected void doHead(HttpServletRequest req, HttpServletResponse res) - handles the HEAD request. It
is invoked by the web container.
HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides
http specific methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class-
protected void doOptions(HttpServletRequest req, HttpServletResponse res) - handles the
OPTIONS request. It is invoked by the web container.

protected void doPut(HttpServletRequest req, HttpServletResponse res) - handles the PUT request.
It is invoked by the web container.

protected void doTrace(HttpServletRequest req, HttpServletResponse res) - handles the TRACE


request. It is invoked by the web container.

protected void doDelete(HttpServletRequest req, HttpServletResponse res) - handles the DELETE


request. It is invoked by the web container.

protected long getLastModified(HttpServletRequest req) - returns the time when HttpServletRequest


was last modified since midnight January 1, 1970 GMT.
The HttpServletRequest interface enables a servlet to formulate an HTTP
response to a client.

Method Description
void addCookie(Cookie cookie) Adds cookie to the HTTP response.
void sendError(int c) throws Sends the error code c to the client.
IOException
void sendError(int c, String s) Sends the error code c and message s to the client.
throws IOException
void setStatus(int code) Sets the status code for this response to code.
The HttpServletResponse interface a servlet to obtain information about a client
request.
Method Description
HttpSession getSession( ) Returns the session for this request. If a session does not exist,
one is created and then returned.
HttpSession getSession(boolean new) If new is true and no session exists, creates and returns a session
for this request. Otherwise, returns the existing session for this
request.
String getServletPath( ) Returns that part of the URL that identifies the servlet.
Cookie[ ] getCookies( ) Returns an array of the cookies in this request.
String getMethod( ) Returns the HTTP method for this request.
String getRemoteUser( ) Returns the name of the user who issued this request.
The HttpSession interface enables a servlet to read and write the state information that is associated
with an HTTP session.

Method Description
Object getAttribute(String attr) Returns the value associated with the name passed in attr. Returns
null if attr is not found.
Enumeration Returns an enumeration of the attribute names associated with the
getAttributeNames( ) session.
long getCreationTime( ) Returns the time (in milliseconds since midnight, January 1, 1970,
GMT) when this session was created.
String getId( ) Returns the session ID.
boolean isNew( ) Returns true if the server created the session and it has not yet
been accessed by the client.
void setAttribute(String attr, Associates the value passed in val with the attribute name passed
Object val) in attr.
The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are
valuable for tracking user activities. 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
Constructor:- Cookie(String name, String value)
Method Description
String getName( ) Returns the name.
String getPath( ) Returns the path.
int getMaxAge( ) Returns the maximum age (in seconds).
void setMaxAge(int secs) Sets the maximum age of the cookie to secs. This is the number of seconds after which
the cookie is deleted.
void setPath(String p) Sets the path to p.
void setValue(String v) Sets the value to v.
Reading Servlet Parameters
The ServletRequest interface includes methods that allow you to read the names
and values of parameters that are included in a client request.

You might also like