Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
31 views42 pages

Java Servlets: Architecture and Lifecycle

Uploaded by

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

Java Servlets: Architecture and Lifecycle

Uploaded by

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

Servlet

• Today, we all are aware of the need to


create dynamic web pages i.e. the ones that
can change the site contents according to the
time or can generate the content according to
the request received from the client
• to generate dynamic web pages and that way
is Java Servlet.
What is Java Servlet?

• Java Servlets are the Java programs that run on the


Java-enabled web server or application server.
• They are used to handle the request obtained from
the web server, process the request, produce the
response, and then send a response back to the web
server.
Properties of Java Servlet

• The properties of Servlets are as follows:


• Servlets work on the server side.
• Servlets are capable of handling complex
requests obtained from the web server.
Java Servlets Architecture
Execution of Java Servlets
• Execution of Servlets basically involves Six basic steps:
• The Clients send the request to the Web Server.
• The Web Server receives the request.
• The Web Server passes the request to the corresponding
servlet.
• The Servlet processes the request and generates the
response in the form of output.
• The Servlet sends the response back to the webserver.
• The Web Server sends the response back to the client
and the client browser displays it on the screen.
• The Servlet technology is similar to other Web
server extensions such as Common Gateway
Interface (CGI) scripts and Hypertext
Preprocessor (PHP)
• ava Servlets are more acceptable since they
solve the limitations of CGI such as low
performance and low degree scalability.
What is CGI(Common Gateway Interface)?
• CGI is actually an external application that is written by
using any of the programming languages like C or C++ and
this is responsible for processing client requests and
generating dynamic content.
• In CGI application, when a client makes a request to access
dynamic Web pages, the Web server performs the following
operations:
• It first locates the requested web page i.e the required CGI
application using URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes
the request information to the application.
• Collects the response from the CGI application.
• Destroys the process, prepares the HTTP
response, and sends it to the client.
• CGI server has to create and destroy the process
for every request.
• It’s easy to understand that this approach is
applicable for handling few clients but as the
number of clients increases, the workload on the
server increases and so the time is taken to
process requests increases.
Servlet Life Cycle
• The life cycle of a servlet is controlled by the container
in which the servlet has been deployed.
• When a request is mapped to a servlet, the container
performs the following steps.
STEPS life cycle of the servlet:

• Servlet class is loaded.


• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
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.
Steps of Servlet Life Cycle
 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.
 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.
 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.
public void init(ServletConfig config) throws Ser
vletException
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.

• public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

where
• request- is the ServletRequest object which encapsulates the connection from client to server
• response- is the ServletResponse object which encapsulates the connection from server back to
the client
Destroy method is invoked:

 The destroy() method is called only once.


• It is called at the end of the life cycle of the servlet.
• This method performs various tasks such as closing
connection with the database, releasing memory
allocated to the servlet, releasing resources that are
allocated to the servlet and other cleanup activities.
• When this method is called, the garbage collector
comes into action.

public void destroy()


Servlet Life Cycle Methods
• There are three life cycle methods of a Servlet
• init()
• service()
• destroy()
Types of Servlet
• Two main servlet types, generic and HTTP
• Generic servlets
• It extends javax.servlet.GenericServlet. It is protocol
independent servlet.
• Generic Servlet is a base class servlet from which all other
Servlets are derived.
• Generic Servlet supports for HTTP, FTP and SMTP protocols.
• It implements the Servlet and ServletConfig interface.
• It has only init() and destroy() method of ServletConfig
interface in its life cycle.
• It also implements the log method of ServletContext
interface.
HTTP servlets
• It extend javax.servlet.HttpServlet.
• HTTPServlet is HTTP dependent servlet.
• The HTTP protocol is a set of rules that allows
Web browsers and servers to communicate.
• When Web browsers and servers support the
HTTP protocol, Java-based web applications are
dependent on HTTP Servlets.
• HttpServlet is Extended by Generic Servlet. It
provides an abstract class for the developers for
extend to create there own HTTP specific servlets.
Http Request Methods
• The doGet() Method
• A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
• public void doGet(HttpServletRequest request, HttpServletResponse
response) throwsServletException,IOException
• { // Servlet code
• }
• The doPost()Method
• A POST request results from an HTML form that specifically lists POST as
the METHOD and it should be handled by doPost() method.
• public void doPost(HttpServletRequest request, HttpServletResponse
response) throwsServletException,IOException
• {
• // Servlet code
• }
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.
javax.servlet package interface
Servlet Interface
• All servlets must implement the Servlet interface.
• It declares the init( ), service( ), and destroy()
methods that are called by the server during the
life cycle of a servlet.
• A method is also provided that allows a servlet to
obtain any initialization parameters
Methods of Servlet interface

• There are 5 methods in Servlet interface.


• The init, service and destroy are the life
cycle methods of servlet.
• These are invoked by the web container.
ServletConfig Interface

• An object of ServletConfig is created by the web


container for each servlet.
• This object can be used to get configuration
information from web.xml file
• If the configuration information is modified from the
web.xml file, we don't need to change the servlet.
• So it is easier to manage the web application if any
specific content is modified from time to time.
Methods of ServletConfig interface
1. public String getInitParameter(String
name):Returns the parameter value for the specified
parameter name.
2. public Enumeration
getInitParameterNames():Returns an enumeration
of all the initialization parameter names.
3. public String getServletName():Returns the name
of the servlet.
4. public ServletContext getServletContext():Returns
an object of ServletContext.
How to get the object of ServletConfig

1. getServletConfig() method of Servlet interface returns


the object of ServletConfig.
• Syntax of getServletConfig() method
1. public ServletConfig getServletConfig();
• Example of getServletConfig() method
1. ServletConfig config=getServletConfig();
2. //
Now we can call the methods of ServletConfig interface
web.xml
• web-app>
• <servlet>
• ......

• <init-param>
• <param-name>parametername</param-name>
• <param-value>parametervalue</param-value>
• </init-param>
• ......
• </servlet>
• </web-app>
ServletContext Interface

• An object of ServletContext is created by the


web container at time of deploying the project.
• This object can be used to get configuration
information from web.xml file.
• There is only one ServletContext object per
web application.
• If any information is shared to many servlet,
• it is better to provide it from
- web.xml file using the <context-param> element.
Methods of Servlet Context
1.public String getInitParameter(String name):Returns the
parameter value for the specified parameter name.
2.public Enumeration getInitParameterNames():Returns the
names of the context's initialization parameters.
3.public void setAttribute(String name,Object object):sets the
given object in the application scope.
4.public Object getAttribute(String name):Returns the attribute
for the specified name.
5.public Enumeration getInitParameterNames():Returns the
names of the context's initialization parameters as an Enumeration
of String objects.
6.public void removeAttribute(String name):Removes the
attribute with the given name from the servlet context.
How to get the object of ServletContext interface

1. getServletContext() method of ServletConfig


interface returns the object of ServletContext.

2. getServletContext() method of GenericServlet class


returns the object of ServletContext.
• Syntax of getServletContext() method
1.public ServletContext getServletContext()

• Example of getServletContext() method


1. //We can get the ServletContext object from ServletConfig object

ServletContext application=getServletConfig().getServletContext();

//Another convenient way to get the ServletContext object

2.ServletContext application=getServletContext();
Syntax to provide the initialization parameter in Context scope

• The context-param element, subelement of


web-app, is used to define the initialization
parameter in the application scope.
• The param-name and param-value are the
sub-elements of the context-param.
• The param-name element defines parameter
name and and param-value defines its value.
Syntax in web.xml
• <web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
• </web-app>
DemoServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();

ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();

String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}}
web.xml
<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>

<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>

</web-app>
ServletResponse Interface
• The servlet container is connected to the web
server that receives Http Requests from client on
a certain port.
• When client sends a request to web server, the
servlet container creates HttpServletRequest and
HttpServletResponse objects and passes them as
an argument to the servlet service() method.
• The response object allows you to
format and send the response back to
the client.
Methods of ServletResponse Interface
index.html

<form action="mydetails" method="get">


User name: <input type="text" name="uname">
<input type="submit" value="login">
</form>
MyServletDemo.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class MyServletDemo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
String name=req.getParameter("uname");
pwriter.println("User Details Page:");
pwriter.println("Hello "+name);
pwriter.close();
}
}
web.xml

<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/mydetails</url-pattern>
</servlet-mapping>
</web-app

You might also like