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
Ad

More Related Content

What's hot (20)

Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Java beans
Java beansJava beans
Java beans
Rajkiran Mummadi
 
Master page in Asp.net
Master page in Asp.netMaster page in Asp.net
Master page in Asp.net
RupinderjitKaur9
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
shravs_188
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
Peter R. Egli
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Java media framework
Java media frameworkJava media framework
Java media framework
Payal Vishwakarma
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
#2 formal methods – principles of logic
#2 formal methods – principles of logic#2 formal methods – principles of logic
#2 formal methods – principles of logic
Sharif Omar Salem
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Database Language.docx
Database Language.docxDatabase Language.docx
Database Language.docx
antonymwangi31
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
Riccardo Cardin
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
Janu Jahnavi
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
VTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERS
VTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERSVTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERS
VTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERS
vtunotesbysree
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
shravs_188
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
Peter R. Egli
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
#2 formal methods – principles of logic
#2 formal methods – principles of logic#2 formal methods – principles of logic
#2 formal methods – principles of logic
Sharif Omar Salem
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Database Language.docx
Database Language.docxDatabase Language.docx
Database Language.docx
antonymwangi31
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
Riccardo Cardin
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
Janu Jahnavi
 
VTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERS
VTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERSVTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERS
VTU 3RD SEM UNIX AND SHELL PROGRAMMING SOLVED PAPERS
vtunotesbysree
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav
 

Similar to UNIT-3 Servlet (20)

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
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
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
 
Servlets
ServletsServlets
Servlets
Sasidhar Kothuru
 
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
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
vinoth ponnurangam
 
Weblogic
WeblogicWeblogic
Weblogic
Raju Sagi
 
Servlets
ServletsServlets
Servlets
Akshay Ballarpure
 
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
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
Auwal Amshi
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
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
 
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
 
Ad

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
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
 
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
 
Ad

Recently uploaded (20)

Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 

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(); } }