Please enable JavaScript.
Coggle requires JavaScript to display documents.
CHAPTER 2: SERVLETS - Coggle Diagram
CHAPTER 2: SERVLETS
What is a Servlet?
Servlets receive and respond to requests from Web clients,
usually across HTTP (Hypertext Transfer Protocol)
It acts as a middle layer between Web clients and database
A servlet is a small Java program that runs within a Web
server.
It is Java class, which can:
read HTML form data
present records from a database or another source
generate HTML dynamically and return it to web browser
make use of cookies and sessions
Java servlets are executed upon request from a web browser
All servlets execute inside a servlet container, also referred to as a
servlet server or a servlet engine.
A servlet container is a single process that runs a JVM (Java Virtual
Machine)
The JVM creates a thread to handle each servlet
All the threads share the same memory allocated to the JVM. Since
the JVM persists beyond the lifecycle of a single servlet execution, servlets can share objects already created in the JVM.
Servlet Life Cycle
Servlet container creates instance
of servlet
Servlet container loads servlet
class
Servlet container calls init()
method of servlet
executed only once
Is used to load or create some data
that will be used throughout the throughout the life cycle
The servlet container receives the
request and directs it to be processed by the appropriate
servlet
Servlet container calls service()
method to
handle request coming from client
write the formatted response back
to client
perform the actual tasks
executed multiple times
A client application sends an
HTTP request to the server
Servlet container unloads servlet by calling destroy()
method
executed only once
other threads might be accessing shared resources
The servlet returns its results to
the client – normally in the form of an HTML, XHTML, or XML
document to display in a
browser
Handling HTTP request in HttpServlet
The key method in every servlet is service, which accepts
both a ServletRequest object and a ServletResponse object
These object provide access to input and output streams
that allow the servlet to read data from and send data to the cilent
HttpServlet - enhanced processing capabilities for
services to extend a Web server’s functionality
If a problem occurs during the execution of a servlet,
either ServletExceptions or IOExceptions are thrown to indicate the problem
For HTTP method, there are corresponding HttpServlet
protected void doAAA (HttpServlet Request ,
HttpServlet Response) throws ServletException, IOException
The two most common HTTP request types (also known as
request methods) are get and post.
A
get
request retrieves information from a server. Typically, an
HTML document or image.
A
post
request sends data to a server. Typically, post requests
are used to pass user input to a data-handling process, store or update data on a server, or post a message to a news group or
discussion forum.
• Class HttpServlet defines methods doGet and doPost to
respond to GET and POST requests from a client.
Sharing the Data between Servlets
HOW?
Bank Business Processs
Make Deposit
Close Account
Open Account
Make Withdrawls
View Balance
Servlet can call other servlet using a RequestDispatcher
Data can be shared between servlets
RequestDispatcher will handle this process using the forward() or
include()
In real world applications, business processes are divided into
multiple tasks
The objects used for accessing data;
HttpSession object.
ServletContext object
ServletRequest object
Introduction to JDBC
JDBC allows the programmer to use connecting to the database, to
executing SQL statements and, to returning results from modern
database
JDBC supports four categories of drivers.
JDBC is made up of about two dozen Java classes in the package
java.sql. These classes provide access to relational data stored in a database
JDBC supports both static and dynamic SQL statements
JDBC - an application programming interface (API) for manipulating a
database
A JDBC driver is typically available from the database vendor of the
database to which you want to connect.
ResultSet
Each call to next() moves to the next record in the result set
You must call next() before you can see the first result record, and it returns false when there are no more result records
A ResultSet object is similar to a 2D array
The class ResultSet has “getter” methods getBlob(),
getBigDecimal(), getDate(), getBytes(), getInt(), getLong() getString(), getObject(), and so on, for all the Java types that
represent SQL types for a column name and column number argument
A container to store the records retrieve from database
Refer to java.sql.ResultSet for a complete listing of the methods.
Method of Servlet
getServletInfo( )
-Returns information about the servlet, such as author, version,
and copyright
init( )
-Called by the servlet container to indicate to a servlet that the
servlet is being placed into service.
getServletConfig( )
- Returns a ServletConfig object, which contains initialization
and startup parameters for this servlet.
service( )
- Called by the servlet container to allow the servlet to respond
to a request.
destroy( )
- Called by the servlet container to indicate to a servlet that the
servlet is being taken out of service.
Connecting to Database
In a 2-tier system, the clients talk directly to the database.
In a 3-tier system, the clients talk to a business logic server which in
turn talks to the database. The business logic server would also contain server-side JDBC functionality
To deal with the database, the clients are required networking
typically remote systems to communicate over TCP/IP networks.
JDBC (Java Database Connectivity) is a standard Java API for
database-independent connectivity between the Java programming language and a wide range of databases.
A database works in the classic client/server fashion. There is one
database and many clients talk to it.
Step to Access Data From Database
Creating a Statement
Executing the Query
Close the Database Connection
Loading a JDBC Driver
Establishing the Database Connection
Why Using the Servlet?
Server-side Java
the code is executed on the server side, not the client
side
a dynamically loaded module that services requests
from a Web server
Will manage web request handling.
Servlet is platform-independent because it is
written in Java.
Performance better than Common Gateway
Interface (CGI) programs.
JDBC Driver Types
JDBC- NeT Pure Java Drivers
Natuve-API, Part Java Driver
Native-protocol Pure Java Drivers
JDBC-to-JDBC Bridge Driver
Establishing the Database Connection
Typically starts with “jdbc: ” to indicate the protocol that will be used (just as “http:” indicates to a web server that you are using the hypertext transport protocol).
The JDBC library contains the class java.sql.Connection that
knows how to use this string to guide it in its search for the correct database
The Java statement to connect to a database invokes the static method getConnection(databaseURL) in the DriverManager class:
.
String url = "jdbc:mysql://localhost:3306/csf3203“;
Connection connection = DriverManager.getConnection (url, “root”,”admin”);
The second step involves the Java application requesting a connection to a database, using a string that looks like a URL as an argument
PreparedStatement Interace
The PreparedStatement interface, which extends the
Statement interface, is used to execute a precompiled SQL statement with or without IN parameters
Since the SQL statements are precompiled (using
PreparedStatement), they are faster in time execution.
Previously, the Statement interface is used to execute
static SQL statements that contain no parameters.
A PreparedStatement object is created using the
preparedStatement method in the Connection Interface
When to use the Servlet?
The server is responsible for database access. Clients connect
to the server using standard protocols available on most client platform
Servlets are the ideal solution for database-intensive
applications that communicate with thin clients
Thin clients are applications that provide presentation but do not
process data, thus requiring few computing resources
The presentation-logic code for generating dynamic content
can be written once and reside on the server for access by clients via servlet to create efficient thin clients.
Loading a JDBC Driver
If your application connects to several different types of databases, all of their respective drivers must be loaded
Class.forName(“ JDBC Driver Class “);
e.g. Class.forName(“com.mysql.jdbc.Driver“)
The first step (as illustrated in the previous slide) is to load a JDBC driver
Creating a Statement
After a Connection object is created, you can create
statements for executing SQL statements as follows:
Statement statement = connection.createStatement();
At this point, you’re ready to begin issuing SQL commands to
the database and getting back results. The table on the following page illustrates some of the methods contained in
java.sql.Connection
If the Connection object can be viewed as a cable
between your application program and the database, an object of Statement can be viewed as a cart that delivers
SQL statements for execution of query.
Requirement to Run Java Servlet
Java Servlet API
Java Servlet Development Kit (JSDK) that embedded in Web Server
– JSDK allows most standard Web server such as Netscape servers, IIS, Apache
and others to load servlets
Servlets can be created using the javax.servlet and javax.servlet.http
packages
A set of java classes.
Java-enabled Web server
There are many web server that support java virtual machine such as Java
Web server by Apache Tomcat, Jboss Enterprise, Jetty, JOnAs, Blaxiz and etc
Sending Request Via Web Browser and HTTP Methods
By default, browser use HTTP GET method UNLESS we
explicitly write in the coding as POST.
A web browser sends an HTTP request to a web server
when
User fill-out HTML form and submits.
User enter URL in browser and presses Enter
User clicks hyperlink in HTML page.