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 (20)

Servlets
ServletsServlets
Servlets
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Servlets
ServletsServlets
Servlets
 
JSP
JSPJSP
JSP
 
Servlet
Servlet Servlet
Servlet
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Generics
GenericsGenerics
Generics
 
ASP.NET State management
ASP.NET State managementASP.NET State management
ASP.NET State management
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Python network programming
Python   network programmingPython   network programming
Python network programming
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 

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
 
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
 
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
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 

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
 
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
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Weblogic
WeblogicWeblogic
Weblogic
 
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
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Servlets
ServletsServlets
Servlets
 

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

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 

Recently uploaded (20)

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 

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