SlideShare a Scribd company logo
UNIT -4
SERVLETS
Introduction to Servlets
• Servlet is a java program that runs inside JVM
on the web server. It is used for developing
dynamic web applications.
• Dynamic web application?
• Servlet technology is robust and scalable
because of java language.
• Before Servlet, CGI (Common Gateway
Interface) scripting language was common as a
server-side programming language. However,
there were many disadvantages to this
technology.
What is a Servlet?
• Servlet can be described in many ways, depending on the context.
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes
including documentation.
• Servlet is an interface that must be implemented for creating any
Servlet.
• Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to
create a dynamic web page.
• Difference between static and dynamic web page ?
• static page as name suggests remains same for all
users however a dynamic web page changes based on
the request from client (user’s browser).
• What is a web application?
• A web application is an application accessible from
the web. A web application is composed of web
components like Servlet, JSP, Filter, etc. and other
elements such as HTML, CSS, and JavaScript. The web
components typically execute in Web Server and
respond to the HTTP request.
Common Gateway Interface (CGI)
• The common gateway interface (CGI) is a standard
way for a Web server to pass a Web user's request
to an application program and to receive data back
to forward to the user.
• CGI technology enables the web server to call an
external program and pass HTTP request
information to the external program to process the
request. For each request, it starts a new process.
• How Servlet is better than CGI
• CGI has several limitations such as performance, scalability,
reusability.
• If number of clients increases, it takes more time for sending
response.
• For each request, it starts a process and Web server is limited to
start processes.
• It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet
• The web container creates threads for handling the multiple requests to the
servlet.
• they share a common memory area and lightweight, cost of communication
between the threads are low .
• better performance: because it creates a thread for each request not process.
• Portability: because it uses java language.
• Robust: Servlets are managed by JVM so we don't need to worry about
memory leak, garbage collection etc.
• Secure: because it uses java language..
Servlets Architecture:
.
Life Cycle of a Servlet
• 1. Servlet class is loaded.
• 2. Servlet instance is created.
• 3. init method is invoked.
• 4. service method is invoked.
• 5. destroy method is invoked.
• The init() method :
•The init() method is called when the servlet is first requested by
a browser.
•It is not called again for each request.
•Used for one-time initialization.
•There are two versions of the init() method:
• Version 1: takes no arguments
• Version 2: takes a servletConfig object as an argument.
•We will focus only on the first option.
• public void init() throws ServletException {
// Initialization code...
• The init() method is a good place to put any initialization variables.
• For example, the following servlet records its Birth
Date/time…
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Birth extends HttpServlet { Date
birthDate;
// Init() is called first
public void init() throws ServletException { birthDate = new
Date();
}
• The service() method :
• The service() method checks the HTTP request type (GET,
POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete,
• Here is the signature of this method:
• public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException {
}
the signature of these two methods.
• The doGet() Method
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
The doPost() Method
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
Handle an HTTP GET Request
public void doGet(HttpServletRequest
request,HttpServletResponse response)
throws IOException, ServletException
{ response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println ("I was born on: "+birthDate);
out.close();
• The destroy() method :
• only once at the end of the life cycle of a servlet
• close database connections, halt background
threads, write cookie lists are cleanup .
• After the destroy() method is called, the servlet
object is marked for garbage collection
public void destroy() {
// Finalization code...
Architecture Diagram:
• First the HTTP requests coming to the server are delegated to the servlet
container.
• The servlet container loads the servlet before invoking the service()
method.
• Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of
the servlet.
Sample Code how a compiled servlet would be deployed in production.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}}
Servlet Deployment
By default, a servlet application is located at the path
<Tomcat-installationdirectory>/webapps/ROOT
and the class file would reside in
<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet,
then this servlet class must be located in
WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into
<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and
create following entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
The Servlet API
javax.servlet The javax.servlet package contains a number of
classes and interfaces that describe and define the
contracts between a servlet class and the runtime
environment provided for an instance of such a class
by a conforming servlet container.
javax.servlet.http The javax.servlet.http package contains a number of
classes and interfaces that describe and define the
contracts between a servlet class running under the HTTP
protocol and the runtime environment provided for an
instance of such a class by a conforming servlet
container.
Reading and
Initialization Servlet parameters
Interfaces in
javax.servlet package
Classes in
javax.servlet package
Interfaces in
javax.servlet.http
package
Classes in
javax.servlet.http
package
Servlet
ServletRequest
ServletResponse
ServletConfig
ServletContext
GenericServlet
ServletInputStream
ServletOutputStream
ServletException
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionBindingLis
tener
HttpServlet
Cookie
HttpSessionEvent
HttpSessionBindingEv
ent
Handling Http Request & Responses
• The Client make the request to the web server
using HTTP protocol.
• There HttpServlet class in which there are
some methods which can be used to handle
HTTP requests.
• doGet()
• doPost()
Session Tracking using Servlets
• In servlets,for creating the sessions
getSession() method can be used.
• This method returns the object which stores
the bindings with the names that use this
object.
• These bindings can be managed using
getAttribute(),setAttribute(),removieAttribute()
methods.
• The Session tracking two things are playing an
important roles.
• One is HttpServletRequest interface which
supports getSession() Method.
• The another class is HttpSession class which
supports the binding managing functions such as
getAttribute(),setAttribute(),removieAttribute()
and getAttributeNames().
Cookies in Servlet
• A cookie is a small piece of information that is
persisted between the multiple client
requests.
• A cookie has a name, a single value, and
optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a
version number.
How Cookie works
• By default, each request is considered as a new
request.
• In cookies technique, we add cookie with
response from the servlet.
• So cookie is stored in the cache of the browser.
• After that if request is sent by the user, cookie
is added with request by default. Thus, we
recognize the user as the old user.
Introduction to JDBC
• Java Database Connectivity(JDBC) is an Application
Programming Interface(API) used to connect Java
application with Database.
• JDBC is used to interact with various type of Database
such as Oracle, MS Access, My SQL and SQL Server.
• JDBC can also be defined as the platform-independent
interface between a relational database and Java
programming. It allows java program to execute SQL
statement and retrieve result from database.
• The JDBC API consists of classes and methods that are
used to perform various operations like: connect, read,
write and store data in the database.
How JDBC Works?
• First of all java application establishes connection
with the data source.
• Then java application invokes classes and interfaces
from jdbc drivers for sending queries to the data
source.
• The jdbc driver connects to corresponding database
and retrives the result.
• These results are based on SQL statements which are
then returned to java application.
• Java application then uses the retrieved information
for further processing.
JDBC Driver
• JDBC-ODBC bridge
• Type-1 Driver act as a bridge between JDBC and
other database connectivity mechanism(ODBC).
This driver converts JDBC calls into ODBC calls
and redirects the request to the ODBC driver.
• Native API Driver
• This type of driver make use of Java Native
Interface(JNI) call on database specific native
client API. These native client API are usually
written in C and C++.
• Network Protocol Driver
• This driver translate the JDBC calls into a database
server independent and Middleware server-specific
calls. Middleware server further translate JDBC calls
into database specific calls.
• Thin Driver
• This is Driver called Pure Java Driver because. This
driver interact directly with database. It does not
require any native database library, that is why it is
also known as Thin Driver.

More Related Content

PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PPT
PPTX
Wt unit 3
PDF
Adv java unit 4 M.Sc CS.pdf
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
PDF
Servlet and JSP
PPTX
J2ee servlet
PPT
JAVA Servlets
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Wt unit 3
Adv java unit 4 M.Sc CS.pdf
SERVLETS (2).pptxintroduction to servlet with all servlets
Servlet and JSP
J2ee servlet
JAVA Servlets

Similar to servlets sessions and cookies, jdbc connectivity (20)

PPTX
WEB TECHNOLOGY Unit-3.pptx
PPTX
UNIT - 5.pptx Servlets And Database Connectivity
PDF
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
PDF
Java Servlets.pdf
PPT
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
PPTX
Servlets
PPT
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
PDF
4_598113hhhhhhhhhhhhhhhhhhhhhhh0134529250346.pdf
PPTX
IP UNIT III PPT.pptx
PPT
Servlet (1) also contains code to create it.ppt
PPT
Servlet.ppt
PPT
Servlet.ppt
PPT
Servlet1.ppt
PPTX
Servlets-UNIT3and introduction to servlet
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
PDF
PDF
DOCX
Servlet
PPTX
AJppt.pptx
PPTX
Session 26 - Servlets Part 2
WEB TECHNOLOGY Unit-3.pptx
UNIT - 5.pptx Servlets And Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
Java Servlets.pdf
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
Servlets
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
4_598113hhhhhhhhhhhhhhhhhhhhhhh0134529250346.pdf
IP UNIT III PPT.pptx
Servlet (1) also contains code to create it.ppt
Servlet.ppt
Servlet.ppt
Servlet1.ppt
Servlets-UNIT3and introduction to servlet
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Servlet
AJppt.pptx
Session 26 - Servlets Part 2
Ad

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharma ospi slides which help in ospi learning
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Pre independence Education in Inndia.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
Microbial diseases, their pathogenesis and prophylaxis
Pharma ospi slides which help in ospi learning
Abdominal Access Techniques with Prof. Dr. R K Mishra
Final Presentation General Medicine 03-08-2024.pptx
01-Introduction-to-Information-Management.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Basic Mud Logging Guide for educational purpose
Week 4 Term 3 Study Techniques revisited.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Microbial disease of the cardiovascular and lymphatic systems
2.FourierTransform-ShortQuestionswithAnswers.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Structure & Organelles in detailed.
Anesthesia in Laparoscopic Surgery in India
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Pre independence Education in Inndia.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Ad

servlets sessions and cookies, jdbc connectivity

  • 2. Introduction to Servlets • Servlet is a java program that runs inside JVM on the web server. It is used for developing dynamic web applications. • Dynamic web application?
  • 3. • Servlet technology is robust and scalable because of java language. • Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology.
  • 4. What is a Servlet? • Servlet can be described in many ways, depending on the context. • Servlet is a technology which is used to create a web application. • Servlet is an API that provides many interfaces and classes including documentation. • Servlet is an interface that must be implemented for creating any Servlet. • Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests. • Servlet is a web component that is deployed on the server to create a dynamic web page.
  • 5. • Difference between static and dynamic web page ? • static page as name suggests remains same for all users however a dynamic web page changes based on the request from client (user’s browser). • What is a web application? • A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request.
  • 6. Common Gateway Interface (CGI) • The common gateway interface (CGI) is a standard way for a Web server to pass a Web user's request to an application program and to receive data back to forward to the user. • CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.
  • 7. • How Servlet is better than CGI • CGI has several limitations such as performance, scalability, reusability. • If number of clients increases, it takes more time for sending response. • For each request, it starts a process and Web server is limited to start processes. • It uses platform dependent language e.g. C, C++, perl.
  • 8. Advantage of Servlet • The web container creates threads for handling the multiple requests to the servlet. • they share a common memory area and lightweight, cost of communication between the threads are low . • better performance: because it creates a thread for each request not process. • Portability: because it uses java language. • Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc. • Secure: because it uses java language..
  • 10. Life Cycle of a Servlet • 1. Servlet class is loaded. • 2. Servlet instance is created. • 3. init method is invoked. • 4. service method is invoked. • 5. destroy method is invoked.
  • 11. • The init() method : •The init() method is called when the servlet is first requested by a browser. •It is not called again for each request. •Used for one-time initialization. •There are two versions of the init() method: • Version 1: takes no arguments • Version 2: takes a servletConfig object as an argument. •We will focus only on the first option. • public void init() throws ServletException { // Initialization code...
  • 12. • The init() method is a good place to put any initialization variables. • For example, the following servlet records its Birth Date/time… import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Birth extends HttpServlet { Date birthDate; // Init() is called first public void init() throws ServletException { birthDate = new Date(); }
  • 13. • The service() method : • The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, • Here is the signature of this method: • public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { }
  • 14. the signature of these two methods. • The doGet() Method public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code The doPost() Method public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code
  • 15. Handle an HTTP GET Request public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println ("I was born on: "+birthDate); out.close();
  • 16. • The destroy() method : • only once at the end of the life cycle of a servlet • close database connections, halt background threads, write cookie lists are cleanup . • After the destroy() method is called, the servlet object is marked for garbage collection public void destroy() { // Finalization code...
  • 17. Architecture Diagram: • First the HTTP requests coming to the server are delegated to the servlet container. • The servlet container loads the servlet before invoking the service() method. • Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
  • 18. Sample Code how a compiled servlet would be deployed in production. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. }}
  • 19. Servlet Deployment By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes. If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class. For now, let us copy HelloWorld.class into <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
  • 21. The Servlet API javax.servlet The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container. javax.servlet.http The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.
  • 22. Reading and Initialization Servlet parameters Interfaces in javax.servlet package Classes in javax.servlet package Interfaces in javax.servlet.http package Classes in javax.servlet.http package Servlet ServletRequest ServletResponse ServletConfig ServletContext GenericServlet ServletInputStream ServletOutputStream ServletException HttpServletRequest HttpServletResponse HttpSession HttpSessionListener HttpSessionBindingLis tener HttpServlet Cookie HttpSessionEvent HttpSessionBindingEv ent
  • 23. Handling Http Request & Responses • The Client make the request to the web server using HTTP protocol. • There HttpServlet class in which there are some methods which can be used to handle HTTP requests. • doGet() • doPost()
  • 24. Session Tracking using Servlets • In servlets,for creating the sessions getSession() method can be used. • This method returns the object which stores the bindings with the names that use this object. • These bindings can be managed using getAttribute(),setAttribute(),removieAttribute() methods.
  • 25. • The Session tracking two things are playing an important roles. • One is HttpServletRequest interface which supports getSession() Method. • The another class is HttpSession class which supports the binding managing functions such as getAttribute(),setAttribute(),removieAttribute() and getAttributeNames().
  • 26. Cookies in Servlet • A cookie is a small piece of information that is persisted between the multiple client requests. • A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
  • 27. How Cookie works • By default, each request is considered as a new request. • In cookies technique, we add cookie with response from the servlet. • So cookie is stored in the cache of the browser. • After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
  • 28. Introduction to JDBC • Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect Java application with Database. • JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. • JDBC can also be defined as the platform-independent interface between a relational database and Java programming. It allows java program to execute SQL statement and retrieve result from database. • The JDBC API consists of classes and methods that are used to perform various operations like: connect, read, write and store data in the database.
  • 29. How JDBC Works? • First of all java application establishes connection with the data source. • Then java application invokes classes and interfaces from jdbc drivers for sending queries to the data source. • The jdbc driver connects to corresponding database and retrives the result. • These results are based on SQL statements which are then returned to java application. • Java application then uses the retrieved information for further processing.
  • 30. JDBC Driver • JDBC-ODBC bridge • Type-1 Driver act as a bridge between JDBC and other database connectivity mechanism(ODBC). This driver converts JDBC calls into ODBC calls and redirects the request to the ODBC driver. • Native API Driver • This type of driver make use of Java Native Interface(JNI) call on database specific native client API. These native client API are usually written in C and C++.
  • 31. • Network Protocol Driver • This driver translate the JDBC calls into a database server independent and Middleware server-specific calls. Middleware server further translate JDBC calls into database specific calls. • Thin Driver • This is Driver called Pure Java Driver because. This driver interact directly with database. It does not require any native database library, that is why it is also known as Thin Driver.