0% found this document useful (0 votes)
21 views96 pages

Java Chapter 7 and 8 JDBC and Servelets

Java Database Connectivity (JDBC) is an API that allows Java applications to connect and interact with various relational databases such as Oracle, MySQL, and SQL Server. It provides a uniform interface for executing SQL statements, retrieving results, and managing database connections through key interfaces like Driver, Connection, Statement, and ResultSet. JDBC supports both two-tier and three-tier architectures, enabling developers to create platform-independent database applications efficiently.

Uploaded by

amanhabtamu32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views96 pages

Java Chapter 7 and 8 JDBC and Servelets

Java Database Connectivity (JDBC) is an API that allows Java applications to connect and interact with various relational databases such as Oracle, MySQL, and SQL Server. It provides a uniform interface for executing SQL statements, retrieving results, and managing database connections through key interfaces like Driver, Connection, Statement, and ResultSet. JDBC supports both two-tier and three-tier architectures, enabling developers to create platform-independent database applications efficiently.

Uploaded by

amanhabtamu32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 96

Chapter 7 Java Database Connectivity (JDBC)

JDBC
 Java Database Connectivity (JDBC) is an Application
Programming Interface (API) used to connect Java application
with Database.
 It is used to interact with the various type of Database such as
Oracle, MS Access, My SQL and SQL Server and it can be stated
as the platform-independent interface between a relational
database and Java programming.
1
JDBC…
 JDBC is the Java API for accessing relational database.

 JDBC is the Java API for developing Java database applications.

 JDBC provides Java programmers with a uniform interface for

accessing and manipulating a wide range of relational databases.

 Using the JDBC API, applications written in the Java programming

language can execute SQL statements, retrieve results, present data


in a user-friendly interface, and propagate changes back to the
database.

 The JDBC API can also be used to interact with multiple data sources

in a distributed, heterogeneous environment.

 The JDBC API is a set of Java interfaces and classes used to write Java
2
programs for accessing and manipulating relational databases.
General Structure of JDBC

3
JDBC
Since a JDBC driver serves as the interface to facilitate
communications between JDBC and a proprietary database, JDBC
drivers are database specific and are normally provided by the
database vendors.
You need MySQL JDBC drivers to access the MySQL database, and
Oracle JDBC drivers to access the Oracle database.
For the access database, use the JDBC-ODBC bridge driver
included in the JDK.
ODBC is a technology developed by Microsoft for accessing
databases on the Windows platform. An ODBC driver is
preinstalled on Windows.
The JDBC-ODBC bridge driver allows a Java program to access any
ODBC data source.
The relationships between Java programs, JDBC API, JDBC drivers,
4
and relational databases are shown in Figure below.
JDBC
Why Java for Database Programming?
 First, Java is platform independent. You can develop platform-
independent database applications using SQL and Java for any
relational database systems.
 Second, the support for accessing database systems from Java is built
into Java API, so you can create database applications using all Java
code with a common interface.
The Architecture of JDBC

6
JDBC Architecture
Two-tier model Three-tier model
• The Java applet or application • Provides a middle tier.
talks directly to the database. • The middle tier can help
• This is a client/server model businesses maintain control of
where the application is the the database accesses.
client, and the database is the
server.

7
Developing Database Applications Using JDBC

 The JDBC API is a Java application program interface to generic SQL databases that

enables Java developers to develop DBMS-independent Java applications using a uniform

interface.

 The JDBC API consists of classes and interfaces for establishing connections with

databases, sending SQL statements to databases, processing the results of SQL statements,

and obtaining database metadata.

 Four key interfaces are needed to develop any database application using Java: Driver,

Connection, Statement, and ResultSet.

 These interfaces define a framework for generic SQL database access.

 The JDBC API defines these interfaces, and the JDBC driver vendors provide the
8
implementation for the interfaces.
Developing Database Applications Using JDBC

A JDBC application:

 loads an appropriate driver using the Driver interface,

connects to the database using the Connection interface,

creates and executes SQL statements using the Statement


interface, and
 processes the result using the ResultSet interface if the
statements return results.
9
The JDBC Interfaces
 The JDBC interfaces and classes are the building
blocks in the development of Java database
programs. A typical Java program takes the
following steps to access a database.
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet

10
Developing JDBC Programs
Loading Statement to load a driver:
drivers Class.forName("JDBCDriverClass");

Establishing A driver is a class. For example:


connections
Database Driver Class Source
Creating and
executing Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK
statements MySQL com.mysql.jdbc.Driver Website
Oracle oracle.jdbc.driver.OracleDriver Website
Processing
ResultSet The JDBC-ODBC driver for Access is bundled in JDK.
MySQL driver class is in mysqljdbc.jar
Oracle driver class is in classes12.jar

To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and
classes12.jar in the class path.

11
Developing JDBC Programs
Loading Connection connection = DriverManager.getConnection(databaseURL);
drivers
Database: URL Pattern
Establishing Access : jdbc:odbc:dataSource
connections MySQL: jdbc:mysql://hostname:port# /dbname, username, password
Oracle: jdbc:oracle:thin:@hostname:port#:oracleDBSID, username, pwd
Creating and
executing
statements Examples:
For Access:
Processing Connection connection = DriverManager.getConnection
ResultSet ("jdbc:odbc:ExampleMDBDataSource");

For MySQL:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
For Oracle:
Connection connection = DriverManager.getConnection
("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger");

12
Developing JDBC Programs
Loading Creating statement:
drivers Statement statement = connection.createStatement();

Establishing
connections
Executing statement (for update, delete, insert):
statement.executeUpdate ("create table Temp (col1 char(5), col2
Creating and char(5))");
executing
statements Executing statement (for select):
// Select the columns from the Student table
Processing
ResultSet resultSet = statement.executeQuery
ResultSet
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");

13
Developing JDBC Programs
Loading Executing statement (for select):
drivers // Select the columns from the Student table
ResultSet resultSet = stmt.executeQuery
Establishing
("select firstName, mi, lastName from Student where lastName "
connections
+ " = 'Smith'");
Creating and
executing Processing ResultSet (for select):
statements // Iterate through the result and print the student names
while (resultSet.next())
Processing
System.out.println(resultSet.getString(1) + " " + resultSet.getString(2)
ResultSet
+ ". " + resultSet.getString(3));

14
Processing SQL Statements with
JDBC
• In general, to process any SQL statement with
JDBC, you follow these steps:
1)Establish a connection.
2)Create a statement.
3)Execute the query.
4)Process the ResultSet object.
5)Close the connection.

15
Establishing a connection
• First, establish a connection with the data source you
want to use.
• A data source can be a DBMS, a legacy file system, or
some other source of data with a corresponding JDBC
driver.
• This connection is represented by a Connection object.
• java.sql.Connection interface corresponds to a session
(a connection with a specific database).
• DriverManager will create a Connection object.
Connection con = DriverManager.getConnection
"jdbc:myDriver:myDatabase",username,password);

16
Creating a statement
• A Statement is an interface that represents a SQL
statement.
• You execute Statement objects, and they generate
ResultSet objects, which is a table of data representing
a database result set.
• You need a Connection object to create a Statement
object.

Statement stmt = con.createStatement();

17
Executing Queries
• You can call the following three methods on a
Statement object to execute SQL queries/statements:
• execute - returns true if the first object that the query
returns is a ResultSet.
• This method can return multiple ResultSet objects, which can
be retrieved by repeatedly calling getResultSet on it.
• executeQuery - returns one ResultSet object.
• Used for the SELECT SQL statement.
• executeUpdate - returns an integer representing the
number of rows effected by the SQL statement.
• Used for the UPDATE, INSERT and DELETE SQL
statements.

18
Processing ResultSet Objects
• A ResultSet is returned when you execute an SQL
statement:
ResultSet rs = stmt.executeQuery("SELECT *
FROM
Employees");

• Extract rows from the ResultSet (step through rows


one at a time).
• Extract a field (column) value from the current row.
• lots of ways to get at values (as String, int, Object, etc).

19
Closing Connections
• When you are finished using a Statement, call the
method Statement.close to immediately release the
resources it is using.
• When you call this method, its ResultSet objects
are closed.
• A typical statement for closing a connection:

if (stmt != null) {
stmt.close();
}

20
Example
public void connectToAndQueryDatabase(
String username, String password) {

Connect to the
Connection con = DriverManager.getConnection database
("jdbc:myDriver:myDatabase", username, password);
Create a Statement object
Statement stmt = con.createStatement(); which will execute a query
on the database
ResultSet rs = stmt.executeQuery(
Get the results of
"SELECT * FROM Employees");
while (rs.next()) { executing that statement
as a ResultSet object
int id = rs.getInt("ID_Number");
String fName = rs.getString("First_Name"); Iterate through the
String lName = rs.getString("Last_Name"); rows in the ResultSet
}

21
Developing JDBC Programs
• The getString(1) , getString(2) , and getString(3)
methods retrieve the column values for firstName, mi ,
and lastName, respectively.

• Alternatively, you can use getString("firstName") ,


getString("mi") , and getString("lastName") to
retrieve the same three column values.

• The first execution of the next() method sets the current


row to the first row in the result set, and subsequent
invocations of the next() method set the current row to
the second row, third row, and so on, to the last row.
22
import java.sql.*;
public class SimpleJdbc { Simple JDBC Example
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:odbc:exampleMDBDataSource");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
// Iterate through the result and print the student names
while (resultSet.next())
System.out.println(resultSet.getString(1) + "\t" +
resultSet.getString(2) + "\t" + resultSet.getString(3));
connection.close();
}
23
}
Processing Statements
 Once a connection to a particular database is
established, it can be used to send SQL
statements from your program to the database.

 JDBC provides the Statement,


PreparedStatement, and CallableStatement
interfaces to facilitate sending statements to a
database for execution and receiving execution
results from the database.
24
Processing Statements Diagram

25
The execute(), executeQuery(), and executeUpdate() Methods

 The methods for executing SQL statements are


execute(), executeQuery(), and executeUpdate(),
each of which accepts a string containing a SQL
statement as an argument.

 This string is passed to the database for execution.

 The execute() method should be used if the


execution produces multiple result sets, multiple
update counts, or a combination of result sets and
update counts. 26
The execute(), executeQuery(), and executeUpdate() Methods

 The executeQuery() method should be used


if the execution produces a single result set,
such as the SQL select statement.

 The executeUpdate() method should be


used if the statement results in a single
update count or no update count, such as a
SQL INSERT, DELETE, UPDATE, or DDL
statement.
27
PreparedStatement
• PreparedStatement enables you to create parameterized SQL statements.
• Once a connection to a particular database is established, it can be used to send
SQL statements from your program to the database.

• The Statement interface is used to execute static SQL statements that don’t
contain any parameters.

• The PreparedStatement interface, extending Statement, is used to execute a


precompiled SQL statement with or without parameters.
• Since the SQL statements are precompiled, they are efficient for repeated
executions.
• A PreparedStatement object is created using the preparedStatement method in
the Connection interface.
• For example, the following code creates a PreparedStatement for an SQL insert
statement:

• Statement preparedStatement = connection.prepareStatement ("insert into


28
Student (firstName, mi, lastName) " + "values (?, ?, ?)");
PreparedStatement
• This insert statement has three question marks as placeholders for parameters

representing values for firstName, mi , and lastName in a record of the Student table.

• As a sub-interface of Statement, the PreparedStatement interface inherits all the

methods defined in Statement.

• It also provides the methods for setting parameters in the object of PreparedStatement.

• These methods are used to set the values for the parameters before executing statements or
procedures. In general, the set methods have the following name and signature:

setX(int parameterIndex, X value);

• where X is the type of the parameter, and parameterIndex is the index of the parameter in the

statement. The index starts from 1.

• For example, the method setString(int parameterIndex, String value) sets a String value to the

specified parameter. 29
PreparedStatement
• The following statements pass the parameters "Jack", "A", and "Ryan” to the placeholders

for firstName, mi , and lastName in preparedStatement:

preparedStatement.setString(1, "Jack");

preparedStatement.setString(2, "A");

preparedStatement.setString(3, "Ryan");

• After setting the parameters, you can execute the prepared statement by invoking

executeQuery() for a SELECT statement and executeUpdate() for a DDL or update statement.

• The executeQuery() and executeUpdate() methods are similar to the ones defined in the

Statement interface except that they don’t have any parameters, because the SQL statements

are already specified in the preparedStatement method when the object of

PreparedStatement is created. 30
Example: PreparedStatement to Execute Dynamic SQL Statements
import javax.swing.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class FindGradeUsingPreparedStatement extends JApplet {
private JTextField jtfSSN = new JTextField(9);
private JTextField jtfCourseId = new JTextField(5);
private JButton jbtShowGrade = new JButton("Show Grade");

// PreparedStatement for executing queries


private PreparedStatement preparedStatement;
/** Initialize the applet */
public void init() {
// Initialize database connection and create a Statement object
initializeDB();
jbtShowGrade.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jbtShowGrade_actionPerformed(e);
}
});

JPanel jPanel1 = new JPanel();


jPanel1.add(new JLabel("SSN"));
jPanel1.add(jtfSSN);
jPanel1.add(new JLabel("Course ID"));
jPanel1.add(jtfCourseId); 31
jPanel1.add(jbtShowGrade);
Example: PreparedStatement to Execute Dynamic SQL Statements
add(jPanel1, BorderLayout.NORTH);
}
private void initializeDB() {
try {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");

System.out.println("Database connected");

String queryString = "select firstName, mi, " +


"lastName, title, grade from Student, Enrollment, Course " +
"where Student.ssn = ? and Enrollment.courseId = ? " +
"and Enrollment.courseId = Course.courseId";
// Create a statement
preparedStatement = connection.prepareStatement(queryString);
}

32
Example: PreparedStatement to Execute Dynamic SQL Statements
catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbtShowGrade_actionPerformed(ActionEvent e) {
String ssn = jtfSSN.getText();
String courseId = jtfCourseId.getText();
try {
preparedStatement.setString(1, ssn);
preparedStatement.setString(2, courseId);
ResultSet rset = preparedStatement.executeQuery();
if (rset.next()) {
String lastName = rset.getString(1);
String mi = rset.getString(2);
String firstName = rset.getString(3);
String title = rset.getString(4);
String grade = rset.getString(5);

// Display result in a dialog box


JOptionPane.showMessageDialog(null , firstName + " " + mi + " " + lastName + "'s
grade on course " + title + " is " + grade);
}
else {
// Display result in a dialog box
JOptionPane.showMessageDialog(null , "Not found");
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
} 33
}
CallableStatement
• The CallableStatement interface is designed to execute SQL-stored procedures.
• The procedures may have IN, OUT or IN OUT parameters.
• An IN parameter receives a value passed to the procedure when it is called.
• An OUT parameter returns a value after the procedure is completed, but it doesn’t
contain any value when the procedure is called.
• An IN OUT parameter contains a value passed to the procedure when it is called, and
returns a value after it is completed.
• For example, the following procedure in Oracle PL/SQL has IN parameter p1, OUT
parameter p2, and IN OUT parameter p3.

• create or replace procedure sampleProcedure (p1 in varchar,


p2 out number, p3 in out integer) is
begin
/* do something */
end sampleProcedure;
34
/
Retrieving Database Metadata
• The database metadata such as database URL, username, JDBC driver name
can be obtained using the DatabaseMetaData interface and result set
metadata such as table column count, column names and column type can be
obtained using the ResultSetMetaData interface.

• Database metadata is the information that describes database itself.

• JDBC provides the DatabaseMetaData interface for obtaining database-


wide information, and the ResultSetMetaData interface for obtaining
information on the specific ResultSet.

• To obtain an instance of DatabaseMetaData for a database, use the


getMetaData method on a Connection object like this:

DatabaseMetaData dbMetaData = connection.getMetaData();


35
Example: Retrieving Database Metadata
• import java.sql.*;

public class TestDatabaseMetaData {


public static void main(String[] args)
throws SQLException, ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");

// Connect to a database
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");
System.out.println("Database connected");

DatabaseMetaData dbMetaData = onnection.getMetaData();


System.out.println("database URL: "+ dbMetaData.getURL());
System.out.println("database username: " + dbMetaData.getUserName()); 36
Example: Retrieving Database Metadata
• System.out.println("database product name: " +
dbMetaData.getDatabaseProductName());
System.out.println("database product version: " +
dbMetaData.getDatabaseProductVersion());
System.out.println("JDBC driver name: " +
dbMetaData.getDriverName());
System.out.println("JDBC driver version: " +
dbMetaData.getDriverVersion());
System.out.println("JDBC driver major version: " +
dbMetaData.getDriverMajorVersion());
System.out.println("JDBC driver minor version: " +
dbMetaData.getDriverMinorVersion());
System.out.println("Max number of connections: " +
dbMetaData.getMaxConnections());
System.out.println("MaxTableNameLength: " +
dbMetaData.getMaxTableNameLength());
System.out.println("MaxColumnsInTable: " +
dbMetaData.getMaxColumnsInTable());

// Close the connection


connection.close();
}
} 37
Obtaining Database Tables

• You can identify the tables in the database through


database metadata using the getTables
method.

• The following program displays all the user tables in the


test database on a local MySQL database.

38
Example: Obtaining Database Tables

import java.sql.*;
public class FindUserTables {
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");

// Connect to a database
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");
System.out.println("Database connected");

DatabaseMetaData dbMetaData = connection.getMetaData();

ResultSet rsTables = dbMetaData.getTables(null , null , null ,


new String[] {"TABLE"});
System.out.print("User tables: ");
while (rsTables.next())
System.out.print( rsTables.getString(“TABLE_NAME”)+ " ");

// Close the connection


connection.close();
} 39
}
Result Set Metadata

• The ResultSetMetaData interface describes information pertaining to the


result set.
• A ResultSetMetaData object can be used to find the types and properties
of the columns in a ResultSet.
• To obtain an instance of ResultSetMetaData, use the getMetaData
method on a result set like this:

• ResultSetMetaData rsMetaData = resultSet.getMetaData();

• You can use the getColumnCount() method to find the number of columns
in the result and the getColumnName(int) method to get the column
names.

• The following program displays all the column names and contents
resulting from the SQL SELECT statement select * from Enrollment.
40
Example: Result Set Metadata

import java.sql.*;
public class TestResultSetMetaData {
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
// Connect to a database
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select * from Enrollment");
ResultSetMetaData rsMetaData = resultSet.getMetaData();
for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
System.out.printf("%-12s\t", rsMetaData.getColumnName(i));
System.out.println();
// Iterate through the result and print the students' names
while (resultSet.next()) {
for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
System.out.printf("%-12s\t", resultSet.getObject(i));
System.out.println();
}
// Close the connection
connection.close();
}
41
}
DatabaseMetadata, cont.

The DatabaseMetaData interface provides more than 100


methods for getting database metadata concerning the
database as a whole.
These methods can be divided into three groups: for
retrieving general information, for finding database
capabilities, and for getting object descriptions.

42
General Information

The general information includes the URL,


username, product name, product version, driver
name, driver version, available functions, available
data types and so on.

43
DatabaseMetaData dbMetaData = connection.getMetaData();
System.out.println("database URL: " + dbMetaData.getURL());
System.out.println("database username: " +
dbMetaData.getUserName());
System.out.println("database product name: " +
dbMetaData.getDatabaseProductName()); Examples
System.out.println("database product version: " +
dbMetaData.getDatabaseProductVersion());
System.out.println("JDBC driver name: " +
dbMetaData.getDriverName());
System.out.println("JDBC driver version: " +
dbMetaData.getDriverVersion());
System.out.println("JDBC driver major version: " +
new Integer(dbMetaData.getDriverMajorVersion()));
System.out.println("JDBC driver minor version: " +
new Integer(dbMetaData.getDriverMinorVersion()));
System.out.println("Max number of connections: " +
new Integer(dbMetaData.getMaxConnections()));
System.out.println("MaxTableNameLentgh: " +
new Integer(dbMetaData.getMaxTableNameLength()));
System.out.println("MaxColumnsInTable: " +
new Integer(dbMetaData.getMaxColumnsInTable()));
connection.close();

44
Chapter 8 : Servlets
• There are different types of Web Technologies in Java, of
which the following are the most well-known
technologies.
1. Servlet
2. Java Server Page (JSP)
3. Java Server Face(JSF)

45
Objectives
• To understand the concept of servlets.
• To run servlets with Tomcat.
• To know the servlets API.
• To create simple servlets.
• To create and process HTML forms.
• To develop servlets to access databases.
• To use hidden fields, cookies, and HttpSession to
track sessions.
• To send images from servlets.

46
Introduction
• 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, JSF, etc.
and other elements such as HTML, CSS, and JavaScript.
• The web components typically execute in Web Server and respond to the HTTP
request.
• Website
• Website is a collection of related web pages that may contain text, images, audio
and video.
• The first page of a website is called home page.
• Each website has specific internet address (URL) that you need to enter in your
browser to access a website.
• Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network.
• A website is managed by its owner that can be an individual, company or an
organization.
• A website can be of two types:
• Static Website /Web Content
47
• Dynamic Website /Web Content
Static website/Web Content

• Static website is the basic type of website that is easy to create.


• You don't need the knowledge of server side programming and database design
to create a static website.
• Its web pages are coded in HTML.
• Static web contents contain fixed number of pages and format of web page is
fixed which delivers information to the client.
• Static web pages display the exact same information whenever anyone visits it.
• This works fine for static information that does not change regardless of who
requests it or when it is requested.
• Static information is stored in files.

48
Dynamic website/Web Content

• Dynamic website is a collection of dynamic web pages whose content changes dynamically.
• It accesses content from a database or Content Management System (CMS).
• Therefore, when you alter or update the content of the database, the content of the website is also altered or updated.
• Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content.
• Client side scripting generates content at the client computer on the basis of user input.
• The web browser downloads the web page from the server and processes the code within the page to render
information to the user.
• In server side scripting, the software runs on the server and processing is completed in the server then plain pages are
sent to the user. Dynamic Web pages are generated by Web servers.
• Example:
• Stock quotes are updated whenever a trade takes place.
• Election vote counts are updated constantly on Election Day.
• Weather reports are frequently updated.
• The balance in a customer’s bank account is updated whenever a transaction takes place.

49
Static vs Dynamic website

Static Website Dynamic Website


Prebuilt content is same every time the Content is generated quickly and
page is loaded. changes regularly.
It uses the HTML code for developing a It uses the server side languages such
website. as PHP, SERVLET, JSP, and
ASP.NET etc. for developing a website.
It sends exactly the same response for It may generate different HTML for
every request. each of the request.
The content is only changed when The page contains "server-side" code
someone publishes and updates the file which allows the server to generate the
(sends it to the web server). unique content when the page is loaded.
Flexibility is the main advantage of Content Management System (CMS) is
static website. the main advantage of dynamic website.

50
HTTP (Hyper Text Transfer Protocol)

• The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,


distributed, hypermedia information systems.
• It is the data communication protocol used to establish communication between client and
server.
• HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
HTTP 80.
• It provides the standardized way for computers to communicate with each other.

51
The Basic Architecture of HTTP
• HTTP is request/response protocol which is based on client/server based architecture.
• In this protocol, web browser, search engines, etc. behave as HTTP clients and the Web
server like Servlet behaves as a server
• The below diagram represents the basic architecture of web application and depicts where
HTTP stands:

52
Servlet
• Servlet technology is used to create a web application
(resides at server side and generates a dynamic web page).
• Servlet technology is robust and scalable because of java
language.
• Servlets are Java programs that run on a Web server.
• Servlets can be used to process client requests or produce
dynamic Web pages.
• JSP, JSF, and Java Web services are based on servlets.
• Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side
programming language.

53
CGI (Common Gateway Interface)

• CGI technology enables the web server to call an external program and pass HTTP
request information to the external program (CGI Program) to process the request.
• For each request, it starts a new process.
• CGI was proposed to generate dynamic Web content.
• The CGI program processes the request and generates a response at runtime.
• Disadvantages of CGI
• There are many problems in CGI technology:
• If the number of clients increases, it takes more time for sending the response.
• For each request, it starts a process, and the web server is limited to start processes.
• It uses platform dependent language e.g. C, C++, perl.

54
Advantages of Servlet

• There are many advantages of Servlet over CGI.


• The web container creates threads for handling the multiple requests to the
Servlet.
• Threads have many benefits over the Processes such as they share a common
memory area, lightweight, cost of communication between the threads are low.
• The advantages of Servlet are as follows:
• Better performance: because it creates a thread for each request, not process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.
• Secure: because it uses java language.

55
CGI vs. Servlets

• CGI provides a relatively simple approach for creating


dynamic Web applications that accept a user request,
process it on the server side, and return responses to the
Web browser.
• But CGI is very slow when handling a large number of
requests simultaneously, because the Web server spawns a
process for executing each CGI program.
• Each process has its own runtime environment that
contains and runs the CGI program.
• It is not difficult to imagine what will happen if many CGI
programs were executed simultaneously.
• System resource would be quickly exhausted,
potentially causing the server to crash.
56
CGI vs. Servlets

• Java servlets are successful technology to solve the


performance problem of CGI programs .
• Java servlets are Java programs that function like CGI
programs.
• All servlets run inside a servlet container or a servlet
server or a servlet engine.
• A servlet container is a single process that runs in a JVM.
• The JVM creates a thread to handle each servlet.
• All the threads share the same memory allocated to the
JVM.
• Servlets are much more efficient than CGI.
• As Java programs, Servlets are object oriented, portable,
and platform independent. 57
The GET and POST Methods

• The two most common HTTP requests or methods are GET


and POST.
• The Web browser issues a request using a URL or an HTML
form to trigger the Web server to execute the servlet
program.
• When issuing a request from an HTML form, either a GET
method or a POST method can be used.
• If the GET method is used, the data in the form are appended
to the request string as if it were submitted using a URL.
• If the POST method is used, the data in the form are
packaged as part of the request file.
• The server program obtains the data by reading the file.
• The POST method is more secure than the GET method.
58
Java Servlet Architecture

59
GET and POST

• The GET and POST methods both send requests to the Web
server.
• The POST method always triggers the execution of the
corresponding the servlet program.
• The GET method may not cause the servlet program to be
executed, if the previous same request is cached in the Web
browser.
• Web browsers often cache Web pages so that the same request
can be quickly responded to without contacting the Web server.
• To ensure that a new Web page is always displayed, use the
POST method.
• For example, use a POST method if the request will actually
update the database.
• If your request is not time sensitive use the GET method to
speed up performance. 60
GET vs POST
GET POST
1) In case of Get request, only limited In case of Post request, large amount of
amount of data can be sent because data data can be sent because data is sent in
is sent in header. body.

2) Get request is not secured because Post request is secured because data is
data is exposed in URL bar. not exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent. It means


second request will be ignored until Post request is non-idempotent.
response of first request is delivered

5) Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.
61
The Servlet API

• The servlet APIs are grouped into two packages:


javax.servlet and javax.servlet.http packages.
• The javax.servlet and javax.servlet.http packages
represent interfaces and classes for servlet API.
• The javax.servlet package contains many interfaces and
classes that are used by the servlet or web container. These
are not specific to any protocol.
• The javax.servlet.http package contains interfaces and
classes that are responsible for http requests only.
• Every servlet is a subclass of the HttpServlet class.
• You need to override appropriate methods in the
HttpServlet class to implement the servlet.
62
The Servlet API

63
The Servlet Interface

• The javax.servlet.Servlet interface defines the methods that all servlets must
implement. The methods are listed below:

public void init() throws ServletException;

public void service(ServletRequest request,


ServletResponse response)throws ServletException,
IOException;

public void destroy();


64
Servlet Life Cycle

• The init, service, and destroy methods are known as life-


cycle methods and are called in the following sequence :

1. The init method is called when the servlet is first created and
is not called again as long as the servlet is not destroyed.
2. The service method is invoked each time the server receives a
request for the servlet. The server spawns/produces/generates
a new thread and invokes service.

3. The destroy method is invoked after a timeout period has


passed or as the Web server is terminated. This method
releases resources for the servlet.Some methods of this step
are doGet() for GET, doPut() for PUT, doUpdate() for
UPDATE, doDelete() for DELETE

65
Servlet Life Cycle

The JVM uses the init, service, and destroy methods to control the
servlet.
66
The GenericServlet Class

• The javax.servlet.GenericServlet class defines a generic, protocol independent


servlet. This class is abstract class.

• It implements javax.servlet.Servlet and javax.servlet.ServletConfig.

• ServletConfig is an interface that defines four methods:


• getInitParameter(),
• getInitParameterNames(),
• getServletContext((), and
• getServletName()
• These methods are used for obtaining information from a Web server
during initialization.

• All the methods in Servlet and ServletConfig are implemented in


GenericServlet except service. 67
The HttpServlet Class

• The javax.servlet.http.HttpServlet class defines a servlet for the


HTTP protocol.
• It extends GenericServlet and implements the service method.
• The service method is implemented as a dispatcher of HTTP
requests.
• The HTTP requests are processed in the following methods:
• doGet is invoked to respond to a GET request.
• doPost is invoked to respond to a POST request.
• doDelete is invoked to respond to a DELETE request. Such a request is
normally used to delete a file on the server.
• doPut is invoked to respond to a PUT request. Such a request is normally
used to send a file to the server.
• doOptions is invoked to respond to an OPTIONS request. This returns
information about the server, such as which HTTP methods it supports.
• doTrace is invoked to respond to a TRACE request. Such a request
is normally used for debugging. This method returns an HTML page that 68
The HttpServlet Class

• All these methods use the follow signature:

protected void doXxx(HttpServletRequest req,


HttpServletResponse resp) throws
ServletException, java.io.IOException
• The HttpServlet class provides default implementation for these
methods.

• You need to override doGet, doPost, doDelete, and doPut if you


want the servlet to process a GET, POST, DELETE, or PUT
request.

• NOTE: GET and POST requests are often used, whereas 69


DELETE, PUT, OPTIONS, and TRACE are not.
The relationship b/n interfaces and classes

HttpServlet inherits abstract class GenericServlet,


which implements interfaces Servlet and
ServletConfig.
70
The ServletRequest Interface

• Every doXxx method in the HttpServlet class has a parameter


of the HttpServletRequest type, which is an object that
contains HTTP request information, including parameter name
and values, attributes, and an input stream.

• HttpServletRequest is a subinterface of ServletRequest.


• ServletRequest defines a more general interface to provide
information for all kinds of clients.

• The frequently used methods in these two interfaces are shown


in Figure below.

71
The ServletRequest Interface

72
The HttpServletResponse Interface

• Every doXxx method in the HttpServlet class has a parameter


of the HttpServletResponse type, which is an object that
assists a servlet in sending a response to the client.

• HttpServletResponse is a subinterface of ServletResponse.

• ServletResponse defines a more general interface for sending


output to the client.

73
The HttpServletResponse Interface

74
Creating Servlets

• To run Java servlets, you need a servlet container.


• Many servlet containers are available for free, but the two
popular ones are Tomcat and GlassFish.
• Both Tomcat and GlassFish are bundled and integrated
with NetBeans 7 (Java EE version).
• When you run a servlet from NetBeans, Tomcat or
GlassFish will be automatically started.
• You can choose to use either of them, or any other
application server.
• GlassFish has more features than Tomcat and it takes
more system resource.

75
Creating Servlets

• To write a Java servlet, you define a class that extends the


HttpServlet class.
• The servlet container runs and controls the execution of
the servlet through the methods defined in the
HttpServlet class.
• A servlet does not have a main method.
• A servlet depends on the servlet engine to call the
methods.
• Every servlet has a structure like the one shown below:

76
Creating Servlets

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {

public void init() throws ServletException {


...
}

public void doGet(HttpServletRequest request,


HttpServletResponse response) throws
ServletException, IOException {
...
}

public void doPost(HttpServletRequest request,


HttpServletResponse response) throws
ServletException, IOException {
...
}

public void destroy() {


...
}
77
}
Creating Servlets

• The servlet engine controls the servlets using init, doGet,


doPost, destroy, and other methods.
• By default, the doGet and doPost methods do nothing.
• To handle a GET request, you need to override the doGet
method; to handle a POST request, you need to override
the doPost method.
• The doGet method is invoked when the Web browser
issues a request using the GET method.
• The doGet method has two parameters, request and
response.
• Request is for obtaining data from the Web browser and
response is for sending data back to the browser.
78
Example: Creating Servlets

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CurrentTime extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<p>The current time is " + new
java.util.Date());
// Close stream
out.close();
}
}

79
HTML Forms

• HTML forms enable you to submit data to the Web server


in a convenient form.
• As shown in the following Figure, the form can contain
text fields, text area, check boxes, combo boxes, lists,
radio buttons, and buttons.

80
HTML tags to construct HTML forms

1. <form>
• <form> ... </form> defines a form body.
• The attributes for the <form> tag are action and method.
• The action attribute specifies the server program to be executed
on the Web server when the form is submitted.
• The method attribute is either get or post.
2. <label>
• <label> ... </label> simply defines a label.

81
HTML tags to construct HTML forms

3. <input>
• <input> defines an input field.
• The attributes for this tag are type, name, value, checked, size, and
maxlength.
• The type attribute specifies the input type.
• Possible types are text for a one-line text field, radio for a radio
button, and checkbox for a check box.
• The name attribute gives a formal name for the attribute. This name
attribute is used by the servlet program to retrieve its associated
value.
• The names of the radio buttons in a group must be identical.
• The value attribute specifies a default value for a text field and text
area.
• The checked attribute indicates whether a radio button or a check
box is initially checked.
• The size attribute specifies the size of a text field, and the maxlength 82
attribute specifies the maximum length of a text field.
HTML tags to construct HTML forms

4. <select>
• <select> ... </select> defines a combo box or a list.
• The attributes for this tag are name, size, and multiple.
• The size attribute specifies the number of rows visible in the
list.
• The multiple attribute specifies that multiple values can be
selected from a list.
• Set size to 1 and do not use a multiple for a combo box.

83
HTML tags to construct HTML forms

5. <option>
• <option> ... </option> defines a selection list within a
<select> ... </select> tag.
• This tag may be used with the value attribute to specify a value
for the selected option (e.g., <option value = "CS">Computer
Science).
• If no value is specified, the selected option is the value.
6. <textarea>
• <textarea> ... </textarea> defines a text area.
• The attributes are name, rows, and cols.
• The rows and cols attributes specify the number of rows and
columns in a text area.

84
HTML Forms

<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h3>Student Registration Form</h3>
<form action = "GetParameters” method = "get">
<!-- Name text fields -->
<p><label>Last Name</label>
<input type = "text" name = "lastName" size = "20" />
<label>First Name</label>
<input type = "text" name = "firstName" size = "20" />
<label>MI</label>
<input type = "text" name = "mi" size = "1" /></p>
<!-- Gender radio buttons -->
<p><label>Gender:</label>
<input type = "radio" name = "gender" value = "M" checked /> Male
<input type = "radio" name = "gender" value = "F" /> Female</p>
<!-- Major combo box -->
<p><label>Major</label>
<select name = "major" size = "1">
<option value = "CS">Computer Science</option>
<option value = "Math">Mathematics</option>
<option>English</option>
<option>Chinese</option>
</select> 85
HTML Forms

<!-- Minor list -->


<label>Minor</label>
<select name = "minor" size = "2" multiple>
<option>Computer Science</option>
<option>Mathematics</option>
<option>English</option>
<option>Chinese</option>
</select></p>
<!-- Hobby check boxes -->
<p><label>Hobby: </label>
<input type = "checkbox" name = "tennis" /> Tennis
<input type = "checkbox" name = "golf" /> Golf
<input type = "checkbox" name = "pingPong" checked />Ping Pong
</p>
<!-- Remark text area -->
<p>Remarks: </p>
<p><textarea name = "remarks" rows = "3" cols = "56">
</textarea></p>
<!-- Submit and Reset buttons -->
<p><input type = "submit" value = "Submit" />
<input type = "reset" value = "Reset" /></p>
</form>
</body>
</html> 86
Example:
.html code
<!DOCTYPE html>
<html>
<head>
<title>Insert Data</title>
</head>
<body>
<!-- Give Servlet reference to the form as an instances
GET and POST services can be according to the problem statement-->
<form action="./InsertData" method="post">
<p>ID:</p>
<!-- Create an element with mandatory name attribute,
so that data can be transfer to the servlet using getParameter() -->
<input type="text" name="id"/>
<br/>
<p>String:</p>
<input type="text" name="string"/>
<br/><br/><br/>
<input type="submit"/>
</form>
</body>
</html>
Servlet program
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// This class can be used to initialize the database connection


public class DatabaseConnection {
protected static Connection initializeDatabase()
throws SQLException, ClassNotFoundException
{
// Initialize all the information regarding
// Database Connection
String dbDriver = "com.mysql.jdbc.Driver";
String dbURL = "jdbc:mysql:// localhost:3306/";
// Database name to access
String dbName = "demoprj";
String dbUsername = "root";
String dbPassword = "root";

Class.forName(dbDriver);
Connection con = DriverManager.getConnection(dbURL + dbName,
dbUsername,
dbPassword);
return con;
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Import Database Connection Class file


import code.DatabaseConnection;

// Servlet Name
@WebServlet("/InsertData")
public class InsertData extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
try {

// Initialize the database


Connection con = DatabaseConnection.initializeDatabase();

// Create a SQL query to insert data into demo table


// demo table consists of two columns, so two '?' is used
PreparedStatement st = con
.prepareStatement("insert into demo values(?, ?)");
// For the first parameter,
// get the data using request object
// sets the data to st pointer
st.setInt(1, Integer.valueOf(request.getParameter("id")));

// Same for second parameter


st.setString(2, request.getParameter("string"));

// Execute the insert command using executeUpdate()


// to make changes in database
st.executeUpdate();
// Close all the connections
st.close();
con.close();

// Get a writer pointer


// to display the successful result
PrintWriter out = response.getWriter();
out.println("<html><body><b>Successfully Inserted"
+ "</b></body></html>");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Thank You!

96

You might also like