SlideShare a Scribd company logo
1 of 36
Servlet technology is used to create web application
(resides at server side and generates dynamic web
page).
Servlet technology is robust and scalable because of
java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was popular as a server-
side programming language. But there was many
disadvantages of this technology. We have discussed
these disadvantages below.
There are many interfaces and classes in the servlet
API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse etc.
 Servlet is a technology i.e. used to create web
application.
 Servlet is an API that provides many interfaces
and classes including documentations.
 Servlet is an interface that must be implemented
for creating any servlet.
 Servlet is a class that extend the capabilities of
the servers and respond to the incoming request.
It can respond to any type of requests.
 Servlet is a web component that is deployed on
the server to create dynamic web page.
 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 components such as HTML.
 The web components typically execute in
Web Server and respond to HTTP request.
 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.
Disadvantages of CGI
 There are many problems in CGI technology:
 If number of clients increases, it takes more
time for sending response.
 For each request, it starts a process and Web
server is limited to start processes.
 It uses platform dependent language e.g. C, C++,
perl.
 There are many advantages of servlet over CGI.
The web container creates threads for handling
the multiple requests to the servlet. Threads
have a lot of benefits over the Processes such as
they share a common memory area, lightweight,
cost of communication between the threads are
low. The basic benefits of servlet are as follows:
 better performance: because it creates a thread
for each request not process.
 Portability: because it uses java language.
 Robust: Servlets are managed by JVM so we
don't need to worry about memory leak, garbage
collection etc.
 Secure: because it uses java language..
 Servlet class is loaded.
 Servlet instance is created.
 init method is invoked.
 service method is invoked.
 destroy method is invoked.
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
of the init method is given below:
 public void init(ServletConfig config) throws ServletE
xception
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. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet
interface is given below:
 public void service(ServletRequest request, ServletRe
sponse 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. The syntax
of the destroy method of the Servlet interface is
given below:
 public void destroy()
The servlet example can be created by three
ways:
 By implementing Servlet interface,
 By inheriting GenericServlet class, (or)
 By inheriting HttpServlet class
 The mostly used approach is by extending
HttpServlet because it provides http request
specific method such as doGet(), doPost(),
doHead() etc.
Here, we are going to use apache tomcat
server in this example. 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
There are three ways to create the servlet:-
 By implementing the Servlet interface
 By inheriting the GenericServlet class
 By inheriting the HttpServlet class
 The HttpServlet class is widely used to create
the servlet because it provides methods to
handle http requests such as doGet(),
doPost, doHead() etc.In this example we are
going to create a servlet that extends the
HttpServlet class. In this example, we are
inheriting the HttpServlet class and providing
the implementation of the doGet() method.
Notice that get request is the default
request.
 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
 }}
 RequestDispacher is an interface that
provides the facility to forward a request to
another resource or include the content of
another resource. RequestDispacher provides
a way to call another resource from a
servlet. Another resource can be servlet, jsp
or html.
Methods of RequestDispacher interface:
 1. forward(ServletRequest request,ServletResponse response): This
method forwards a request from a servlet to another resource on the
server.
 Syntax:public void forward(ServletRequest request,ServletResponse
response)throws ServletException, IOException
 2. include(ServletRequest request,ServletResponse response): This
method includes the content of a resource in the response.
 Syntax: public void include(ServletRequest request,ServletResponse
response)throws ServletException, IOException
How to get an object of RequestDispacher.
 RequestDispacher object can be gets from HttpServletRequest
object.ServletRequest’s getRequestDispatcher()method is used to get
RequestDispatcher object.
 RequestDispatcher requestDispatcher =
request.getRequestDispatcher(“/another resource”);
 After creating RequestDispatcher object you call forword or include
method as per your requirement.
 requestDispatcher.forward(request, response);
or
 requestDispatcher.include(request, response);
 sendRedirect() is the method of
HttpServletResponse interface which is used
to redirect response to another resource.
 Syntax: response. sendRedirect(relative
url);
ServletAnnotationExample:
@WebServlet("/HelloWorld")
public class ServletAnnotationExample extends HttpServlet
{
private static final long serialVersionUID = 1L;
//no-argument constructor
public ServletAnnotationExample() { }
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>Hello World example using annotations.</h1>");
out.close();
}
}
Cookie:
 A cookie is a small piece of information as a text file
stored on client’s machine by a web application.
How cookie works?
 As HTTP is a stateless protocol so there is no way to
identify that it is a new user or previous user for
every new request.
 In case of cookie a text file with small piece of
information is added to the response of first request.
 They are stored on client’s machine. Now when a
new request comes cookie is by default added with
the request. With this information we can identify
that it is a new user or a previous user.
 1. Session cookies/Non-persistent
cookies: These types of cookies are session
dependent i.e. they are accessible as long as
session is open and they are lost when
session is closed by exiting from the web
application.
 2. Permanent cookies/Persistent
cookies: These types of cookies are session
independent i.e. they are not lost when
session is closed by exiting from the web
application. They are lost when they expire.
Advantages of cookies:
 1. They are stored on client side so don’t
need any server resource.
 2. and easy technique for session
management.
Disadvantages of cookies:
 1. Cookies can be disabled from the browser.
 2. Security risk is there because cookies exist
as a text file so any one can open and read
user’s information
Hidden field:
 Hidden field is an input text with hidden type. This field will not
be visible to the user.
 Syntax:<input name=”fieldName” value=”fieldValue”
type=”hidden”/>
How to get hidden field value in servlet?
 HttpServletRequest interface’s getParameter() method is used to
get hidden field value in servlet.
 Syntax: String value = request.getParameter(“fieldName”);
 Note: Hidden field only works in case of form submission so
they will not work in case of anchor tag as no form submission
is there.
Advantages of hidden field:
 1. All browsers support hidden fields.
2. Simple to use.
Disadvantages of hidden fields:
 1. Not secure.
2. Only work in case of form submission.
J2ee servlet

More Related Content

What's hot (20)

Servlet lifecycle
Servlet lifecycleServlet lifecycle
Servlet lifecycle
 
Servlet
ServletServlet
Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servlets
ServletsServlets
Servlets
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Servlets
ServletsServlets
Servlets
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Core web application development
Core web application developmentCore web application development
Core web application development
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Viewers also liked

embedding web browser in your app
embedding web browser in your appembedding web browser in your app
embedding web browser in your appSamsung
 
Testing strategies for Docker containers
Testing strategies for Docker containersTesting strategies for Docker containers
Testing strategies for Docker containersAlexei Ledenev
 

Viewers also liked (6)

embedding web browser in your app
embedding web browser in your appembedding web browser in your app
embedding web browser in your app
 
Introduction to .Net
Introduction to .NetIntroduction to .Net
Introduction to .Net
 
Asp Architecture
Asp ArchitectureAsp Architecture
Asp Architecture
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Jsp
JspJsp
Jsp
 
Testing strategies for Docker containers
Testing strategies for Docker containersTesting strategies for Docker containers
Testing strategies for Docker containers
 

Similar to J2ee servlet

Similar to J2ee servlet (20)

Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
J servlets
J servletsJ servlets
J servlets
 
Major project report
Major project reportMajor project report
Major project report
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
 
Advanced java+JDBC+Servlet
Advanced java+JDBC+ServletAdvanced java+JDBC+Servlet
Advanced java+JDBC+Servlet
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
ajava unit 1.pptx
ajava unit 1.pptxajava unit 1.pptx
ajava unit 1.pptx
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
It and ej
It and ejIt and ej
It and ej
 
Servlet and Servlet Life Cycle
Servlet and Servlet Life CycleServlet and Servlet Life Cycle
Servlet and Servlet Life Cycle
 

Recently uploaded

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Recently uploaded (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

J2ee servlet

  • 1. Servlet technology is used to create web application (resides at server side and generates dynamic web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server- side programming language. But there was many disadvantages of this technology. We have discussed these disadvantages below. There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.
  • 2.  Servlet is a technology i.e. used to create web application.  Servlet is an API that provides many interfaces and classes including documentations.  Servlet is an interface that must be implemented for creating any servlet.  Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.  Servlet is a web component that is deployed on the server to create dynamic web page.
  • 3.
  • 4.  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 components such as HTML.  The web components typically execute in Web Server and respond to HTTP request.
  • 5.  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. Disadvantages of CGI  There are many problems in CGI technology:  If number of clients increases, it takes more time for sending response.  For each request, it starts a process and Web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl.
  • 6.
  • 7.  There are many advantages of servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:  better performance: because it creates a thread for each request not process.  Portability: because it uses java language.  Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc.  Secure: because it uses java language..
  • 8.
  • 9.  Servlet class is loaded.  Servlet instance is created.  init method is invoked.  service method is invoked.  destroy method is invoked.
  • 10.
  • 11. 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 of the init method is given below:  public void init(ServletConfig config) throws ServletE xception
  • 12. 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. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:  public void service(ServletRequest request, ServletRe sponse 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. The syntax of the destroy method of the Servlet interface is given below:  public void destroy()
  • 13. The servlet example can be created by three ways:  By implementing Servlet interface,  By inheriting GenericServlet class, (or)  By inheriting HttpServlet class  The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc.
  • 14. Here, we are going to use apache tomcat server in this example. 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
  • 15.
  • 16. There are three ways to create the servlet:-  By implementing the Servlet interface  By inheriting the GenericServlet class  By inheriting the HttpServlet class  The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default request.
  • 17.  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  }}
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.  RequestDispacher is an interface that provides the facility to forward a request to another resource or include the content of another resource. RequestDispacher provides a way to call another resource from a servlet. Another resource can be servlet, jsp or html.
  • 26. Methods of RequestDispacher interface:  1. forward(ServletRequest request,ServletResponse response): This method forwards a request from a servlet to another resource on the server.  Syntax:public void forward(ServletRequest request,ServletResponse response)throws ServletException, IOException  2. include(ServletRequest request,ServletResponse response): This method includes the content of a resource in the response.  Syntax: public void include(ServletRequest request,ServletResponse response)throws ServletException, IOException How to get an object of RequestDispacher.  RequestDispacher object can be gets from HttpServletRequest object.ServletRequest’s getRequestDispatcher()method is used to get RequestDispatcher object.  RequestDispatcher requestDispatcher = request.getRequestDispatcher(“/another resource”);  After creating RequestDispatcher object you call forword or include method as per your requirement.  requestDispatcher.forward(request, response); or  requestDispatcher.include(request, response);
  • 27.  sendRedirect() is the method of HttpServletResponse interface which is used to redirect response to another resource.  Syntax: response. sendRedirect(relative url);
  • 28.
  • 29. ServletAnnotationExample: @WebServlet("/HelloWorld") public class ServletAnnotationExample extends HttpServlet { private static final long serialVersionUID = 1L; //no-argument constructor public ServletAnnotationExample() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<h1>Hello World example using annotations.</h1>"); out.close(); } }
  • 30. Cookie:  A cookie is a small piece of information as a text file stored on client’s machine by a web application. How cookie works?  As HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every new request.  In case of cookie a text file with small piece of information is added to the response of first request.  They are stored on client’s machine. Now when a new request comes cookie is by default added with the request. With this information we can identify that it is a new user or a previous user.
  • 31.  1. Session cookies/Non-persistent cookies: These types of cookies are session dependent i.e. they are accessible as long as session is open and they are lost when session is closed by exiting from the web application.  2. Permanent cookies/Persistent cookies: These types of cookies are session independent i.e. they are not lost when session is closed by exiting from the web application. They are lost when they expire.
  • 32. Advantages of cookies:  1. They are stored on client side so don’t need any server resource.  2. and easy technique for session management. Disadvantages of cookies:  1. Cookies can be disabled from the browser.  2. Security risk is there because cookies exist as a text file so any one can open and read user’s information
  • 33.
  • 34.
  • 35. Hidden field:  Hidden field is an input text with hidden type. This field will not be visible to the user.  Syntax:<input name=”fieldName” value=”fieldValue” type=”hidden”/> How to get hidden field value in servlet?  HttpServletRequest interface’s getParameter() method is used to get hidden field value in servlet.  Syntax: String value = request.getParameter(“fieldName”);  Note: Hidden field only works in case of form submission so they will not work in case of anchor tag as no form submission is there. Advantages of hidden field:  1. All browsers support hidden fields. 2. Simple to use. Disadvantages of hidden fields:  1. Not secure. 2. Only work in case of form submission.