SlideShare a Scribd company logo
1 of 27
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

Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3sandeep54552
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asppriya Nithya
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
ASP.NET MVC.
ASP.NET MVC.ASP.NET MVC.
ASP.NET MVC.Ni
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 

What's hot (20)

Servlets
ServletsServlets
Servlets
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Web services
Web servicesWeb services
Web services
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
ASP.NET MVC.
ASP.NET MVC.ASP.NET MVC.
ASP.NET MVC.
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Linq
LinqLinq
Linq
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 

Similar to Servlet Fundamentals: Life Cycle, API, Requests & Responses

Java Servlet
Java ServletJava Servlet
Java ServletYoga 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 responsesbharathiv53
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal 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 KuteTushar B Kute
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 
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, APIPRIYADARSINISK
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and ServletsRaghu nath
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 

Similar to Servlet Fundamentals: Life Cycle, API, Requests & Responses (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
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
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
 
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
 
Servlet
Servlet Servlet
Servlet
 
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
 

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 motivationssbd6985
 
Information Extraction
Information ExtractionInformation Extraction
Information Extractionssbd6985
 
Information Extraction
Information ExtractionInformation Extraction
Information Extractionssbd6985
 
information retrieval
information retrievalinformation retrieval
information retrievalssbd6985
 
Information Extraction
Information ExtractionInformation Extraction
Information Extractionssbd6985
 
Information Retrieval
Information RetrievalInformation Retrieval
Information Retrievalssbd6985
 
Expert System Full Details
Expert System Full DetailsExpert System Full Details
Expert System Full Detailsssbd6985
 

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

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

Servlet Fundamentals: Life Cycle, API, Requests & Responses

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