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.