(Go: >> BACK << -|- >> HOME <<)

SlideShare a Scribd company logo
Servlet
 life cycle of a servlet.
 The Servlet API
 Handling HTTP Request
 Handling HTTP Response
 Session Tracking
 using Cookies
Intro…
– Servlets are small programs that execute on the server side of a
web connection.
– Just as applets dynamically extend the functionality of a web
browser.
– servlets dynamically extend the functionality of a web server.
Early days of the Web
– A server could dynamically construct a page by creating a separate process to
handle each client request.
– The process would open connections to one or more databases in order to
obtain the necessary information.
– It communicated with the web server via an interface known as the Common
Gateway Interface (CGI).
– CGI allowed the separate process to read data from the HTTP request and write
data to the HTTP response.
Cont.,
– A variety of different languages were used to build CGI programs. These
included C, C++, and Perl.
– CGI suffered serious performance problems.
– It was expensive in terms of processor and memory resources to create a
separate process for each client request.
– It was also expensive to open and close database connections for each
client request.
– In addition, the CGI programs were not platform-independent.
– Therefore, other techniques were introduced. Among these are servlets.
Servlets offer several advantages in
comparison with CGI
– First, performance is significantly better. Servlets execute within the address space of a
web server.
– It is not necessary to create a separate process to handle each client request.
– Second, servlets are platform-independent because they are written in Java.
– Third, the Java security manager on the server enforces a set of restrictions to protect
the resources on a server machine.
– Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
The Life Cycle of a Servlet
– Three methods are central to the life cycle of a servlet.
These are:
– init( )
– service( )
– destroy( )
User scenario to understand
when these methods are called
– First, assume that a user enters a Uniform Resource Locator (URL) to a web browser.
The browser then generates an HTTP request for this URL. This request is then sent
to the appropriate server.
– Second, this HTTP request is received by the web server. The server maps this
request to a particular servlet. The servlet is dynamically retrieved and loaded into the
address space of the server.
– Third, the server invokes the init( ) method of the servlet. This method is invoked
only when the servlet is first loaded into memory. It is possible to pass initialization
parameters to the servlet so it may configure itself.
Cont.,
– Fourth, the server invokes the service( ) method of the servlet. This method is called to
process the HTTP request. the servlet to read data that has been provided in the HTTP
request.
–
– It may also formulate an HTTP response for the client. The servlet remains in the
server’s address space and is available to process any other HTTP requests received
from clients. The service( ) method is called for each HTTP request.
– Finally, the server may decide to unload the servlet from its memory. The algorithms
by which this determination is made are specific to each server. The server calls the
destroy( ) method to relinquish any resources.
Using Tomcat for Servlet Development
– To create servlets, you will need access to a servlet
development environment.
– The one used by is Tomcat, Tomcat is an open-source product
maintained by the Jakarta Project of the Apache Software
Foundation.
– It contains the class libraries, documentation, and runtime
support that you will need to create and test servlets.
A Simple Servlet
– To become familiar with the key servlet concepts, we will begin by
building and testing a simple servlet. The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the
servlet’s class file to the proper directory, and add the servlet’s
name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Create and Compile the Servlet Source Code
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,ServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!</B>");
pw.close();
} }
Start Tomcat
– Start Tomcat as explained earlier. Tomcat must be running
before you try to execute a servlet.
– Start a Web Browser and Request the Servlet
– Start a web browser and enter the URL shown here:
http://localhost:8080/servlets-examples/servlet/HelloServlet
– Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/servlets-examples/servlet/HelloServlet
– This can be done because 127.0.0.1 is defined as the IP address
of the local machine.
The Servlet API
– Two packages contain the classes and interfaces that are required to
build servlets. These are:
– javax.servlet
– javax.servlet.http.
– They constitute the Servlet API.
– Keep in mind that these packages are not part of the Java core
packages.
– Instead, they are standard extensions provided by Tomcat.
The javax.servlet Package
– The javax.servlet package contains a number of interfaces
and classes that establish the framework in which. The
ServletRequest and ServletResponse interfaces are also
very important:
– Servlet
– ServletConfig
– ServletContext
– ServletRequest
– ServletResponse
The following summarizes the core classes that are
provided in the javax.servlet :
–GenericServlet
–ServletInputStream
–ServletOutputStream
–ServletException
–UnavailableException
<html>
<body>
<center>
<form name="Form1“ method="post“ action="http://localhost:8080/servlets-
examples/servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</form>
</body> </html>
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet {
public void service(ServletRequest request,ServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
Compile the servlet. Next, copy it to the appropriate
directory, and update the web.xml file, as previously
described.
Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text
fields.
4. Submit the web page.
After following these steps, the browser will display a
response that is dynamically generated by the servlet.
The javax.servlet.http Package
– The javax.servlet.http package contains a number of interfaces
and classes that are commonly used by servlet developers.
– You will see that its functionality makes it easy to build servlets
that work with HTTP requests and responses.
– The following table summarizes the core interfaces that are
provided in this package:
Interface Description
HttpSer vletRequest Enables ser vlets to read data from an HTTP request.
HttpSer vletResponse Enables ser vlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from a
session.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session
value, or that a session attribute changed.
 The following table summarizes the core classes that are provided in this package.
 The most important of these is HttpServlet. Servlet developers typically extend this
class in order to process HTTP requests.
 The HttpServletRequest Interface
The HttpServletRequest interface enables a servlet to obtain information about
a client request.
 The HttpServletResponse Interface
The HttpServletResponse interface enables a servlet to formulate an HTTP
response to a client. Several constants are defined. These correspond to the different
status codes that can be assigned to an HTTP response.
For example, SC_OK indicates that the HTTP request succeeded,
SC_NOT_FOUND indicates that the requested resource is not available.
 The HttpSession Interface
The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session. All of these methods throw an
IllegalStateException if the session has already been invalidated.
Handling HTTP Requests and Responses
– The HttpServlet class provides specialized methods that handle the various types of
HTTP requests.
– A servlet developer typically overrides one of these methods. These methods are:
 doDelete( )
 doGet( )
 doHead( )
 doOptions( )
 doPost( )
 doPut( )
 doTrace( )
– However, the GET and POST requests are commonly used when handling form input.
<html>
<body>
<center>
<form name="Form1“ action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: </b> ");
pw.println(color);
pw.close();
}
}
<html>
<body>
<center>
<form name="Form1“ method="post“
action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse
response) throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: </b> ");
pw.println(color);
pw.close();
}
}
Using Cookies

More Related Content

What's hot

AngularJS
AngularJS AngularJS
Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
Chetan Gadodia
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
Nitin Pande
 
Http headers
Http headersHttp headers
Http headers
Judy Ngure
 
Web Application Penetration Testing Introduction
Web Application Penetration Testing IntroductionWeb Application Penetration Testing Introduction
Web Application Penetration Testing Introduction
gbud7
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
Xss (cross site scripting)
Xss (cross site scripting)Xss (cross site scripting)
Xss (cross site scripting)
vinayh.vaghamshi _
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
servlet in java
servlet in javaservlet in java
servlet in java
sowfi
 
Build a Website Using HTML + CSS
Build a Website Using HTML + CSSBuild a Website Using HTML + CSS
Build a Website Using HTML + CSS
Anna Cook (she/her)
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Web service Introduction
Web service IntroductionWeb service Introduction
Web service Introduction
Madhukar Kumar
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
Sher Singh Bardhan
 
Introduction to Web Development
Introduction to Web DevelopmentIntroduction to Web Development
Introduction to Web Development
Parvez Mahbub
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
Jitender Singh Lodhi
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
HTML5 Tutorial
HTML5 TutorialHTML5 Tutorial
HTML5 Tutorial
Avinash Malhotra
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 

What's hot (20)

AngularJS
AngularJS AngularJS
AngularJS
 
Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
Http headers
Http headersHttp headers
Http headers
 
Web Application Penetration Testing Introduction
Web Application Penetration Testing IntroductionWeb Application Penetration Testing Introduction
Web Application Penetration Testing Introduction
 
Java servlets
Java servletsJava servlets
Java servlets
 
Xss (cross site scripting)
Xss (cross site scripting)Xss (cross site scripting)
Xss (cross site scripting)
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
servlet in java
servlet in javaservlet in java
servlet in java
 
Build a Website Using HTML + CSS
Build a Website Using HTML + CSSBuild a Website Using HTML + CSS
Build a Website Using HTML + CSS
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Web service Introduction
Web service IntroductionWeb service Introduction
Web service Introduction
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Introduction to Web Development
Introduction to Web DevelopmentIntroduction to Web Development
Introduction to Web Development
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
Servlet
Servlet Servlet
Servlet
 
HTML5 Tutorial
HTML5 TutorialHTML5 Tutorial
HTML5 Tutorial
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 

Similar to UNIT-3 Servlet

Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
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
bharathiv53
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
Praveen Yadav
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
Lokesh Singrol
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
Auwal Amshi
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
Prabu U
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
Bharat777
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
vinoth ponnurangam
 
Weblogic
WeblogicWeblogic
Weblogic
Raju Sagi
 
Servlets
ServletsServlets
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
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
tanujaparihar
 

Similar to UNIT-3 Servlet (20)

Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
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
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Weblogic
WeblogicWeblogic
Weblogic
 
Servlets
ServletsServlets
Servlets
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
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
 

More from ssbd6985

Best methods of staff selection and motivation
Best methods of staff selection and motivationBest methods of staff selection and motivation
Best methods of staff selection and motivation
ssbd6985
 
Information Extraction
Information ExtractionInformation Extraction
Information Extraction
ssbd6985
 
Information Extraction
Information ExtractionInformation Extraction
Information Extraction
ssbd6985
 
information retrieval
information retrievalinformation retrieval
information retrieval
ssbd6985
 
Information Extraction
Information ExtractionInformation Extraction
Information Extraction
ssbd6985
 
Information Retrieval
Information RetrievalInformation Retrieval
Information Retrieval
ssbd6985
 
Expert System Full Details
Expert System Full DetailsExpert System Full Details
Expert System Full Details
ssbd6985
 

More from ssbd6985 (7)

Best methods of staff selection and motivation
Best methods of staff selection and motivationBest methods of staff selection and motivation
Best methods of staff selection and motivation
 
Information Extraction
Information ExtractionInformation Extraction
Information Extraction
 
Information Extraction
Information ExtractionInformation Extraction
Information Extraction
 
information retrieval
information retrievalinformation retrieval
information retrieval
 
Information Extraction
Information ExtractionInformation Extraction
Information Extraction
 
Information Retrieval
Information RetrievalInformation Retrieval
Information Retrieval
 
Expert System Full Details
Expert System Full DetailsExpert System Full Details
Expert System Full Details
 

Recently uploaded

Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025
Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025
Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025
ALBERTHISOLER1
 
FINAL MATATAG Science CG 2023 Grades 3-10.pdf
FINAL MATATAG Science CG 2023 Grades 3-10.pdfFINAL MATATAG Science CG 2023 Grades 3-10.pdf
FINAL MATATAG Science CG 2023 Grades 3-10.pdf
maritescanete2
 
QCE – Unpacking the syllabus Implications for Senior School practices and ass...
QCE – Unpacking the syllabus Implications for Senior School practices and ass...QCE – Unpacking the syllabus Implications for Senior School practices and ass...
QCE – Unpacking the syllabus Implications for Senior School practices and ass...
mansk2
 
Node JS Interview Question PDF By ScholarHat
Node JS Interview Question PDF By ScholarHatNode JS Interview Question PDF By ScholarHat
Node JS Interview Question PDF By ScholarHat
Scholarhat
 
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...
Nguyen Thanh Tu Collection
 
7. Post Harvest Entomology and their control.pptx
7. Post Harvest Entomology and their control.pptx7. Post Harvest Entomology and their control.pptx
7. Post Harvest Entomology and their control.pptx
UmeshTimilsina1
 
Open Source and AI - ByWater Closing Keynote Presentation.pdf
Open Source and AI - ByWater Closing Keynote Presentation.pdfOpen Source and AI - ByWater Closing Keynote Presentation.pdf
Open Source and AI - ByWater Closing Keynote Presentation.pdf
Jessica Zairo
 
PRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdf
PRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdfPRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdf
PRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdf
nservice241
 
Parkinson Disease & Anti-Parkinsonian Drugs.pptx
Parkinson Disease & Anti-Parkinsonian Drugs.pptxParkinson Disease & Anti-Parkinsonian Drugs.pptx
Parkinson Disease & Anti-Parkinsonian Drugs.pptx
AnujVishwakarma34
 
5. Postharvest deterioration of fruits and vegetables.pptx
5. Postharvest deterioration of fruits and vegetables.pptx5. Postharvest deterioration of fruits and vegetables.pptx
5. Postharvest deterioration of fruits and vegetables.pptx
UmeshTimilsina1
 
Introduction to Google Productivity Tools for Office and Personal Use
Introduction to Google Productivity Tools for Office and Personal UseIntroduction to Google Productivity Tools for Office and Personal Use
Introduction to Google Productivity Tools for Office and Personal Use
Excellence Foundation for South Sudan
 
11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx
11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx
11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx
mansk2
 
INSIDE OUT - PowerPoint Presentation.pptx
INSIDE OUT - PowerPoint Presentation.pptxINSIDE OUT - PowerPoint Presentation.pptx
INSIDE OUT - PowerPoint Presentation.pptx
RODELAZARES3
 
React Interview Question PDF By ScholarHat
React Interview Question PDF By ScholarHatReact Interview Question PDF By ScholarHat
React Interview Question PDF By ScholarHat
Scholarhat
 
Introduction to Banking System in India.ppt
Introduction to Banking System in India.pptIntroduction to Banking System in India.ppt
Introduction to Banking System in India.ppt
Dr. S. Bulomine Regi
 
Open and Critical Perspectives on AI in Education
Open and Critical Perspectives on AI in EducationOpen and Critical Perspectives on AI in Education
Open and Critical Perspectives on AI in Education
Robert Farrow
 
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
ASP.NET Core Interview Questions PDF By ScholarHat.pdfASP.NET Core Interview Questions PDF By ScholarHat.pdf
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
Odoo 17 Events - Attendees List Scanning
Odoo 17 Events - Attendees List ScanningOdoo 17 Events - Attendees List Scanning
Odoo 17 Events - Attendees List Scanning
Celine George
 
slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...
slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...
slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...
MANIVALANSR
 
Java MCQ Questions and Answers PDF By ScholarHat
Java MCQ Questions and Answers PDF By ScholarHatJava MCQ Questions and Answers PDF By ScholarHat
Java MCQ Questions and Answers PDF By ScholarHat
Scholarhat
 

Recently uploaded (20)

Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025
Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025
Brigada Eskwela 2024 PowerPoint Update for SY 2024-2025
 
FINAL MATATAG Science CG 2023 Grades 3-10.pdf
FINAL MATATAG Science CG 2023 Grades 3-10.pdfFINAL MATATAG Science CG 2023 Grades 3-10.pdf
FINAL MATATAG Science CG 2023 Grades 3-10.pdf
 
QCE – Unpacking the syllabus Implications for Senior School practices and ass...
QCE – Unpacking the syllabus Implications for Senior School practices and ass...QCE – Unpacking the syllabus Implications for Senior School practices and ass...
QCE – Unpacking the syllabus Implications for Senior School practices and ass...
 
Node JS Interview Question PDF By ScholarHat
Node JS Interview Question PDF By ScholarHatNode JS Interview Question PDF By ScholarHat
Node JS Interview Question PDF By ScholarHat
 
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - ...
 
7. Post Harvest Entomology and their control.pptx
7. Post Harvest Entomology and their control.pptx7. Post Harvest Entomology and their control.pptx
7. Post Harvest Entomology and their control.pptx
 
Open Source and AI - ByWater Closing Keynote Presentation.pdf
Open Source and AI - ByWater Closing Keynote Presentation.pdfOpen Source and AI - ByWater Closing Keynote Presentation.pdf
Open Source and AI - ByWater Closing Keynote Presentation.pdf
 
PRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdf
PRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdfPRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdf
PRESS RELEASE - UNIVERSITY OF GHANA, JULY 16, 2024.pdf
 
Parkinson Disease & Anti-Parkinsonian Drugs.pptx
Parkinson Disease & Anti-Parkinsonian Drugs.pptxParkinson Disease & Anti-Parkinsonian Drugs.pptx
Parkinson Disease & Anti-Parkinsonian Drugs.pptx
 
5. Postharvest deterioration of fruits and vegetables.pptx
5. Postharvest deterioration of fruits and vegetables.pptx5. Postharvest deterioration of fruits and vegetables.pptx
5. Postharvest deterioration of fruits and vegetables.pptx
 
Introduction to Google Productivity Tools for Office and Personal Use
Introduction to Google Productivity Tools for Office and Personal UseIntroduction to Google Productivity Tools for Office and Personal Use
Introduction to Google Productivity Tools for Office and Personal Use
 
11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx
11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx
11EHS Term 3 Week 1 Unit 1 Review: Feedback and improvementpptx
 
INSIDE OUT - PowerPoint Presentation.pptx
INSIDE OUT - PowerPoint Presentation.pptxINSIDE OUT - PowerPoint Presentation.pptx
INSIDE OUT - PowerPoint Presentation.pptx
 
React Interview Question PDF By ScholarHat
React Interview Question PDF By ScholarHatReact Interview Question PDF By ScholarHat
React Interview Question PDF By ScholarHat
 
Introduction to Banking System in India.ppt
Introduction to Banking System in India.pptIntroduction to Banking System in India.ppt
Introduction to Banking System in India.ppt
 
Open and Critical Perspectives on AI in Education
Open and Critical Perspectives on AI in EducationOpen and Critical Perspectives on AI in Education
Open and Critical Perspectives on AI in Education
 
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
ASP.NET Core Interview Questions PDF By ScholarHat.pdfASP.NET Core Interview Questions PDF By ScholarHat.pdf
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
 
Odoo 17 Events - Attendees List Scanning
Odoo 17 Events - Attendees List ScanningOdoo 17 Events - Attendees List Scanning
Odoo 17 Events - Attendees List Scanning
 
slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...
slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...
slidesgo-mastering-the-art-of-listening-insights-from-robin-sharma-2024070718...
 
Java MCQ Questions and Answers PDF By ScholarHat
Java MCQ Questions and Answers PDF By ScholarHatJava MCQ Questions and Answers PDF By ScholarHat
Java MCQ Questions and Answers PDF By ScholarHat
 

UNIT-3 Servlet

  • 1. Servlet  life cycle of a servlet.  The Servlet API  Handling HTTP Request  Handling HTTP Response  Session Tracking  using Cookies
  • 2. Intro… – Servlets are small programs that execute on the server side of a web connection. – Just as applets dynamically extend the functionality of a web browser. – servlets dynamically extend the functionality of a web server.
  • 3. Early days of the Web – A server could dynamically construct a page by creating a separate process to handle each client request. – The process would open connections to one or more databases in order to obtain the necessary information. – It communicated with the web server via an interface known as the Common Gateway Interface (CGI). – CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response.
  • 4. Cont., – A variety of different languages were used to build CGI programs. These included C, C++, and Perl. – CGI suffered serious performance problems. – It was expensive in terms of processor and memory resources to create a separate process for each client request. – It was also expensive to open and close database connections for each client request. – In addition, the CGI programs were not platform-independent. – Therefore, other techniques were introduced. Among these are servlets.
  • 5. Servlets offer several advantages in comparison with CGI – First, performance is significantly better. Servlets execute within the address space of a web server. – It is not necessary to create a separate process to handle each client request. – Second, servlets are platform-independent because they are written in Java. – Third, the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. – Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
  • 6. The Life Cycle of a Servlet – Three methods are central to the life cycle of a servlet. These are: – init( ) – service( ) – destroy( )
  • 7. User scenario to understand when these methods are called – First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server. – Second, this HTTP request is received by the web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server. – Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.
  • 8. Cont., – Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. the servlet to read data that has been provided in the HTTP request. – – It may also formulate an HTTP response for the client. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request. – Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinquish any resources.
  • 9. Using Tomcat for Servlet Development – To create servlets, you will need access to a servlet development environment. – The one used by is Tomcat, Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software Foundation. – It contains the class libraries, documentation, and runtime support that you will need to create and test servlets.
  • 10. A Simple Servlet – To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. The basic steps are the following: 1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and add the servlet’s name and mappings to the proper web.xml file. 2. Start Tomcat. 3. Start a web browser and request the servlet.
  • 11. Create and Compile the Servlet Source Code import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!</B>"); pw.close(); } }
  • 12. Start Tomcat – Start Tomcat as explained earlier. Tomcat must be running before you try to execute a servlet. – Start a Web Browser and Request the Servlet – Start a web browser and enter the URL shown here: http://localhost:8080/servlets-examples/servlet/HelloServlet – Alternatively, you may enter the URL shown here: http://127.0.0.1:8080/servlets-examples/servlet/HelloServlet – This can be done because 127.0.0.1 is defined as the IP address of the local machine.
  • 13. The Servlet API – Two packages contain the classes and interfaces that are required to build servlets. These are: – javax.servlet – javax.servlet.http. – They constitute the Servlet API. – Keep in mind that these packages are not part of the Java core packages. – Instead, they are standard extensions provided by Tomcat.
  • 14. The javax.servlet Package – The javax.servlet package contains a number of interfaces and classes that establish the framework in which. The ServletRequest and ServletResponse interfaces are also very important: – Servlet – ServletConfig – ServletContext – ServletRequest – ServletResponse
  • 15. The following summarizes the core classes that are provided in the javax.servlet : –GenericServlet –ServletInputStream –ServletOutputStream –ServletException –UnavailableException
  • 16. <html> <body> <center> <form name="Form1“ method="post“ action="http://localhost:8080/servlets- examples/servlet/PostParametersServlet"> <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr> </table> <input type=submit value="Submit"> </form> </body> </html>
  • 17. import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } }
  • 18. Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml file, as previously described. Then, perform these steps to test this example: 1. Start Tomcat (if it is not already running). 2. Display the web page in a browser. 3. Enter an employee name and phone number in the text fields. 4. Submit the web page. After following these steps, the browser will display a response that is dynamically generated by the servlet.
  • 19. The javax.servlet.http Package – The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. – You will see that its functionality makes it easy to build servlets that work with HTTP requests and responses. – The following table summarizes the core interfaces that are provided in this package: Interface Description HttpSer vletRequest Enables ser vlets to read data from an HTTP request. HttpSer vletResponse Enables ser vlets to write data to an HTTP response. HttpSession Allows session data to be read and written. HttpSessionBindingListener Informs an object that it is bound to or unbound from a session.
  • 20. Class Description Cookie Allows state information to be stored on a client machine. HttpServlet Provides methods to handle HTTP requests and responses. HttpSessionEvent Encapsulates a session-changed event. HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value, or that a session attribute changed.  The following table summarizes the core classes that are provided in this package.  The most important of these is HttpServlet. Servlet developers typically extend this class in order to process HTTP requests.
  • 21.  The HttpServletRequest Interface The HttpServletRequest interface enables a servlet to obtain information about a client request.  The HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. For example, SC_OK indicates that the HTTP request succeeded, SC_NOT_FOUND indicates that the requested resource is not available.  The HttpSession Interface The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session. All of these methods throw an IllegalStateException if the session has already been invalidated.
  • 22. Handling HTTP Requests and Responses – The HttpServlet class provides specialized methods that handle the various types of HTTP requests. – A servlet developer typically overrides one of these methods. These methods are:  doDelete( )  doGet( )  doHead( )  doOptions( )  doPost( )  doPut( )  doTrace( ) – However, the GET and POST requests are commonly used when handling form input.
  • 23. <html> <body> <center> <form name="Form1“ action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html>
  • 24. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: </b> "); pw.println(color); pw.close(); } }
  • 25. <html> <body> <center> <form name="Form1“ method="post“ action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html>
  • 26. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorPostServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: </b> "); pw.println(color); pw.close(); } }