Servlets
By: Priyanka Pradhan
MJPRU
Priyanka Pradhan
 Servlet technology is used to create a web
application (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.
Priyanka Pradhan
 Servlet is an interface that must be
implemented for creating any Servlet.
 Servlet is a class that extends the
capabilities of the servers and responds to
the incoming requests. It can respond to any
requests.
 Servlet is a web component that is deployed
on the server to create a dynamic web page.
Priyanka Pradhan
Priyanka Pradhan
 A web application is an application accessible
from the web.
 A web application is composed of web
components like Servlet, JSP, Filter, etc. and
other elements such as HTML, CSS, and
JavaScript.
 The web components typically execute in
Web Server and respond to the HTTP
request.
Priyanka Pradhan
 CGI technology enables the web server to
call an external program and pass HTTP
request information to the external program
to process the request.
 For each request, it starts a new process.
Priyanka Pradhan
 If the number of clients increases, it takes
more time for sending the response.
 For each request, it starts a process, and the
web server is limited to start processes.
 It uses platform dependent language e.g. C,
C++, perl.
Priyanka Pradhan
 The web container creates threads for
handling the multiple requests to the
Servlet.
 Threads have many benefits over the
Processes such as they share a common
memory area, lightweight, cost of
communication between the threads are low.
Priyanka Pradhan
 Website: static vs dynamic
 HTTP
 HTTP Requests
 Get vs Post
 Container
Priyanka Pradhan
 The request sent by the computer to a web
server, contains all sorts of potentially
interesting information.
Priyanka Pradhan
GET
 only limited amount of data can be sent because data is sent in header.
 not secured because data is exposed in URL bar.
 can be bookmarked.
 idempotent . It means second request will be ignored until response of first request is delivered
 more efficient and used more than Post.
POST
 large amount of data can be sent because data is sent in body.
 secured because data is not exposed in URL bar.
 cannot be bookmarked.
 non-idempotent.
 less efficient and
 used less than get.
Priyanka Pradhan
 If the user wants to read the web pages as
per input then the servlet container is used
in java.
 The servlet container is the part of web
server which can be run in a separate
process.
Priyanka Pradhan
Priyanka Pradhan
 The javax.servlet and javax.servlet.http
packages represent interfaces and classes for
servlet api.
Priyanka Pradhan
 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.
Priyanka Pradhan
 The javax.servlet.http package contains
interfaces and classes that are responsible
for http requests only.
Priyanka Pradhan
 Servlet
 ServletRequest
 ServletResponse
 RequestDispatcher
 ServletConfig
 ServletContext
 SingleThreadModel
 Filter
 FilterConfig
 FilterChain
 ServletRequestListener
 ServletRequestAttributeListener
 ServletContextListener
 ServletContextAttributeListener
Priyanka Pradhan
 GenericServlet
 ServletInputStream
 ServletOutputStream
 ServletRequestWrapper
 ServletResponseWrapper
 ServletRequestEvent
 ServletContextEvent
 ServletRequestAttributeEvent
 ServletContextAttributeEvent
 ServletException
 UnavailableException
Priyanka Pradhan
 HttpServletRequest
 HttpServletResponse
 HttpSession
 HttpSessionListener
 HttpSessionAttributeListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext (deprecated now)
Priyanka Pradhan
 HttpServlet
 Cookie
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 HttpSessionEvent
 HttpSessionBindingEvent
 HttpUtils (deprecated now)
Priyanka Pradhan
import java.io.*; import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized"); }
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 simple servlet</b>"); out.print("</body>
</html>"); }
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";} }
 GenericServlet class
implements Servlet, ServletConfig and Serializa
ble 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.
 You may create a generic servlet by inheriting
the GenericServlet class and providing the
implementation of the service method.
Priyanka Pradhan
 public void init(ServletConfig config)
 public abstract void service(ServletRequest request, ServletResponse
response)
 public void destroy()
 public ServletConfig getServletConfig()
 public String getServletInfo()
 public void init()
 public ServletContext getServletContext()
 public String getInitParameter(String name)
 public Enumeration getInitParameterNames()
 public String getServletName()
 public void log(String msg)
 public void log(String msg,Throwable t)
Priyanka Pradhan
import java.io.*;
import javax.servlet.*;
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>"); } }
Priyanka Pradhan
 The HttpServlet class extends the
GenericServlet class and implements
Serializable interface.
 It provides http specific methods such as
doGet, doPost, doHead, doTrace etc.
Priyanka Pradhan
 public void service(ServletRequest req,ServletResponse res)
 protected void service(HttpServletRequest req,
HttpServletResponse res)
 protected void doGet(HttpServletRequest req,
HttpServletResponse res)
 protected void doPost(HttpServletRequest req,
HttpServletResponse res)
 protected void doHead(HttpServletRequest req,
HttpServletResponse res)
 protected void doOptions(HttpServletRequest req,
HttpServletResponse res)
 protected void doPut(HttpServletRequest req,
HttpServletResponse res)
Priyanka Pradhan
The web container maintains the life cycle of a
servlet instance.
 Servlet class is loaded.
 Servlet instance is created.
 init method is invoked.
 service method is invoked.
 destroy method is invoked.
Priyanka Pradhan
 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.
Priyanka Pradhan
 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.
Priyanka Pradhan
 The web container calls the init method only
once after creating the servlet instance.
public void init(ServletConfig config) throws
ServletException
Priyanka Pradhan
 The web container calls the service method
each time when request for the servlet is
received.
public void service(ServletRequest request, S
ervletResponse response)throws ServletExce
ption, IOException
Priyanka Pradhan
 The web container calls the destroy method
before removing the servlet instance from
the service.
public void destroy()
Priyanka Pradhan
The servlet example can be created by
three ways:
 By implementing Servlet interface,
 By inheriting GenericServlet class, (or)
 By inheriting HttpServlet class
Priyanka Pradhan
The steps are as follows:
 Create a directory structure
 Create a Servlet
 Compile the Servlet
 Create a deployment descriptor
 Start the server and deploy the project
 Access the servlet
Priyanka Pradhan
 The directory structure defines that where
to put the different types of files so that web
container may get the information and
respond to the client.
Priyanka Pradhan
Priyanka Pradhan
There are three ways to create the servlet.
 By implementing the Servlet interface
 By inheriting the GenericServlet class
 By inheriting the HttpServlet class
Priyanka Pradhan
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream }}
 For compiling the Servlet, jar file is required
to be loaded. Different Servers provide
different jar files:
 servlet-api.jar Apache Tomcat
Priyanka Pradhan
Two ways to load the jar file
 set classpath
 paste the jar file in JRE/lib/ext folder
Priyanka Pradhan
 The deployment descriptor is an xml file,
from which Web Container gets the
information about the servet to be invoked.
 The web container uses the Parser to get the
information from the web.xml file. There are
many xml parsers such as SAX, DOM.
Priyanka Pradhan
<web-app>
<servlet>
<servlet-name>jaiswal</servlet-name>
<servlet-class>Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Priyanka Pradhan
 <web-app> represents the whole application.
 <servlet> is sub element of <web-app> and represents the
servlet.
 <servlet-name> is sub element of <servlet> represents the
name of the servlet.
 <servlet-class> is sub element of <servlet> represents the
class of the servlet.
 <servlet-mapping> is sub element of <web-app>. It is used
to map the servlet.
 <url-pattern> is sub element of <servlet-mapping>. This
pattern is used at client side to invoke the servlet.
Priyanka Pradhan
To start Apache Tomcat server, double click
on the startup.bat file under apache-
tomcat/bin directory.
Priyanka Pradhan
 Go to My Computer properties ->
 Click on advanced tab then environment
variables ->
 Click on the new tab of user variable ->
 Write JAVA_HOME in variable name and paste
the path of jdk folder in variable value ->
 ok -> ok -> ok.
Priyanka Pradhan
 After setting the JAVA_HOME double click on
the startup.bat file in apache tomcat/bin.
Priyanka Pradhan
There are two types of tomcat available:
 Apache tomcat that needs to extract only (no
need to install)
 Apache tomcat that needs to install
Priyanka Pradhan
 Changing the port number is required if there
is another server running on the same system
with same port number.
 Open server.xml file in notepad. It is located
inside the apache-tomcat/conf directory .
Change the Connector port = 8080 and
replace 8080 by any four digit number
instead of 8080. Let us replace it by 9999
and save this file.
Priyanka Pradhan
 Copy the project and paste it in the webapps
folder under apache tomcat.
Priyanka Pradhan
Priyanka Pradhan
 Open broser and write
http://hostname:portno/contextroot/urlpatt
ernofservlet.
Priyanka Pradhan
The server checks if the servlet is requested for the first
time.
 If yes, web container does the following tasks:
 loads the servlet class.
 instantiates the servlet class.
 calls the init method passing the ServletConfig object
else
 calls the service method passing request and response
objects
 The web container calls the destroy method when it needs
to remove the servlet such as at time of stopping server or
undeploying the project.
Priyanka Pradhan

Servlet

  • 1.
  • 2.
     Servlet technologyis used to create a web application (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. Priyanka Pradhan
  • 3.
     Servlet isan interface that must be implemented for creating any Servlet.  Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.  Servlet is a web component that is deployed on the server to create a dynamic web page. Priyanka Pradhan
  • 4.
  • 5.
     A webapplication is an application accessible from the web.  A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript.  The web components typically execute in Web Server and respond to the HTTP request. Priyanka Pradhan
  • 6.
     CGI technologyenables the web server to call an external program and pass HTTP request information to the external program to process the request.  For each request, it starts a new process. Priyanka Pradhan
  • 7.
     If thenumber of clients increases, it takes more time for sending the response.  For each request, it starts a process, and the web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl. Priyanka Pradhan
  • 8.
     The webcontainer creates threads for handling the multiple requests to the Servlet.  Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. Priyanka Pradhan
  • 9.
     Website: staticvs dynamic  HTTP  HTTP Requests  Get vs Post  Container Priyanka Pradhan
  • 10.
     The requestsent by the computer to a web server, contains all sorts of potentially interesting information. Priyanka Pradhan
  • 11.
    GET  only limitedamount of data can be sent because data is sent in header.  not secured because data is exposed in URL bar.  can be bookmarked.  idempotent . It means second request will be ignored until response of first request is delivered  more efficient and used more than Post. POST  large amount of data can be sent because data is sent in body.  secured because data is not exposed in URL bar.  cannot be bookmarked.  non-idempotent.  less efficient and  used less than get. Priyanka Pradhan
  • 12.
     If theuser wants to read the web pages as per input then the servlet container is used in java.  The servlet container is the part of web server which can be run in a separate process. Priyanka Pradhan
  • 13.
  • 14.
     The javax.servletand javax.servlet.http packages represent interfaces and classes for servlet api. Priyanka Pradhan
  • 15.
     The javax.servletpackage contains many interfaces and classes that are used by the servlet or web container.  These are not specific to any protocol. Priyanka Pradhan
  • 16.
     The javax.servlet.httppackage contains interfaces and classes that are responsible for http requests only. Priyanka Pradhan
  • 17.
     Servlet  ServletRequest ServletResponse  RequestDispatcher  ServletConfig  ServletContext  SingleThreadModel  Filter  FilterConfig  FilterChain  ServletRequestListener  ServletRequestAttributeListener  ServletContextListener  ServletContextAttributeListener Priyanka Pradhan
  • 18.
     GenericServlet  ServletInputStream ServletOutputStream  ServletRequestWrapper  ServletResponseWrapper  ServletRequestEvent  ServletContextEvent  ServletRequestAttributeEvent  ServletContextAttributeEvent  ServletException  UnavailableException Priyanka Pradhan
  • 19.
     HttpServletRequest  HttpServletResponse HttpSession  HttpSessionListener  HttpSessionAttributeListener  HttpSessionBindingListener  HttpSessionActivationListener  HttpSessionContext (deprecated now) Priyanka Pradhan
  • 20.
     HttpServlet  Cookie HttpServletRequestWrapper  HttpServletResponseWrapper  HttpSessionEvent  HttpSessionBindingEvent  HttpUtils (deprecated now) Priyanka Pradhan
  • 21.
    import java.io.*; importjavax.servlet.*; public class First implements Servlet{ ServletConfig config=null; public void init(ServletConfig config){ this.config=config; System.out.println("servlet is initialized"); } 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 simple servlet</b>"); out.print("</body> </html>"); } public void destroy(){System.out.println("servlet is destroyed");} public ServletConfig getServletConfig(){return config;} public String getServletInfo(){return "copyright 2007-1010";} }
  • 22.
     GenericServlet class implementsServlet, ServletConfig and Serializa ble 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.  You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method. Priyanka Pradhan
  • 23.
     public voidinit(ServletConfig config)  public abstract void service(ServletRequest request, ServletResponse response)  public void destroy()  public ServletConfig getServletConfig()  public String getServletInfo()  public void init()  public ServletContext getServletContext()  public String getInitParameter(String name)  public Enumeration getInitParameterNames()  public String getServletName()  public void log(String msg)  public void log(String msg,Throwable t) Priyanka Pradhan
  • 24.
    import java.io.*; import javax.servlet.*; publicclass 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>"); } } Priyanka Pradhan
  • 25.
     The HttpServletclass extends the GenericServlet class and implements Serializable interface.  It provides http specific methods such as doGet, doPost, doHead, doTrace etc. Priyanka Pradhan
  • 26.
     public voidservice(ServletRequest req,ServletResponse res)  protected void service(HttpServletRequest req, HttpServletResponse res)  protected void doGet(HttpServletRequest req, HttpServletResponse res)  protected void doPost(HttpServletRequest req, HttpServletResponse res)  protected void doHead(HttpServletRequest req, HttpServletResponse res)  protected void doOptions(HttpServletRequest req, HttpServletResponse res)  protected void doPut(HttpServletRequest req, HttpServletResponse res) Priyanka Pradhan
  • 27.
    The web containermaintains the life cycle of a servlet instance.  Servlet class is loaded.  Servlet instance is created.  init method is invoked.  service method is invoked.  destroy method is invoked. Priyanka Pradhan
  • 28.
     The classloaderis responsible to load the servlet class.  The servlet class is loaded when the first request for the servlet is received by the web container. Priyanka Pradhan
  • 29.
     The webcontainer creates the instance of a servlet after loading the servlet class.  The servlet instance is created only once in the servlet life cycle. Priyanka Pradhan
  • 30.
     The webcontainer calls the init method only once after creating the servlet instance. public void init(ServletConfig config) throws ServletException Priyanka Pradhan
  • 31.
     The webcontainer calls the service method each time when request for the servlet is received. public void service(ServletRequest request, S ervletResponse response)throws ServletExce ption, IOException Priyanka Pradhan
  • 32.
     The webcontainer calls the destroy method before removing the servlet instance from the service. public void destroy() Priyanka Pradhan
  • 33.
    The servlet examplecan be created by three ways:  By implementing Servlet interface,  By inheriting GenericServlet class, (or)  By inheriting HttpServlet class Priyanka Pradhan
  • 34.
    The steps areas follows:  Create a directory structure  Create a Servlet  Compile the Servlet  Create a deployment descriptor  Start the server and deploy the project  Access the servlet Priyanka Pradhan
  • 35.
     The directorystructure defines that where to put the different types of files so that web container may get the information and respond to the client. Priyanka Pradhan
  • 36.
  • 37.
    There are threeways to create the servlet.  By implementing the Servlet interface  By inheriting the GenericServlet class  By inheriting the HttpServlet class Priyanka Pradhan
  • 38.
    import javax.servlet.http.*; import javax.servlet.*; importjava.io.*; public class DemoServlet extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html");//setting the content type PrintWriter pw=res.getWriter();//get the stream to write the data //writing html in the stream pw.println("<html><body>"); pw.println("Welcome to servlet"); pw.println("</body></html>"); pw.close();//closing the stream }}
  • 39.
     For compilingthe Servlet, jar file is required to be loaded. Different Servers provide different jar files:  servlet-api.jar Apache Tomcat Priyanka Pradhan
  • 40.
    Two ways toload the jar file  set classpath  paste the jar file in JRE/lib/ext folder Priyanka Pradhan
  • 41.
     The deploymentdescriptor is an xml file, from which Web Container gets the information about the servet to be invoked.  The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM. Priyanka Pradhan
  • 42.
  • 43.
     <web-app> representsthe whole application.  <servlet> is sub element of <web-app> and represents the servlet.  <servlet-name> is sub element of <servlet> represents the name of the servlet.  <servlet-class> is sub element of <servlet> represents the class of the servlet.  <servlet-mapping> is sub element of <web-app>. It is used to map the servlet.  <url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet. Priyanka Pradhan
  • 44.
    To start ApacheTomcat server, double click on the startup.bat file under apache- tomcat/bin directory. Priyanka Pradhan
  • 45.
     Go toMy Computer properties ->  Click on advanced tab then environment variables ->  Click on the new tab of user variable ->  Write JAVA_HOME in variable name and paste the path of jdk folder in variable value ->  ok -> ok -> ok. Priyanka Pradhan
  • 46.
     After settingthe JAVA_HOME double click on the startup.bat file in apache tomcat/bin. Priyanka Pradhan
  • 47.
    There are twotypes of tomcat available:  Apache tomcat that needs to extract only (no need to install)  Apache tomcat that needs to install Priyanka Pradhan
  • 48.
     Changing theport number is required if there is another server running on the same system with same port number.  Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by 9999 and save this file. Priyanka Pradhan
  • 49.
     Copy theproject and paste it in the webapps folder under apache tomcat. Priyanka Pradhan
  • 50.
  • 51.
     Open broserand write http://hostname:portno/contextroot/urlpatt ernofservlet. Priyanka Pradhan
  • 52.
    The server checksif the servlet is requested for the first time.  If yes, web container does the following tasks:  loads the servlet class.  instantiates the servlet class.  calls the init method passing the ServletConfig object else  calls the service method passing request and response objects  The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project. Priyanka Pradhan