You are on page 1of 21

Server-Side Web Development

Introduction to Server-Side Web


Development using JSP and Databases
JSP and Databases

02
nd
March 2006
Bogdan L. Vrusias
b.vrusias@surrey.ac.uk
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 2
Contents
Relational Databases
Transactions
Middleware
Basic Java classes used for databases
Integrating JSP and Data
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 3
Relational Databases and SQL
A relational database consists of a series of tables and is
normally accessed using a special programming language
known as SQL (Structured Query Language) often
embedded within another language such as Java or C++.

With the exception of a few object-oriented database
products released in the late 1980s and the 1990s relational
database technology has been the overwhelmingly
dominant database technology for the last 20 years.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 4
Database Middleware
There is a wide variety of middleware available which fits between
clients and database servers:
The first most popular component is an SQL API (Application
Programmers Interface). This provides programming facilities for
developers who wish, for example, to embed SQL code within
procedural languages.
The second most popular is a database driver. This is usually a
small piece of software which takes SQL statements, formats them
and then sends them over to the server.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 5
JDBC Driver
JDBC driver is a piece of software that knows how to talk
to a database server.
Java Application
JDBC Driver Manager
JDBC-ODBC Bridge Ventor Specific
JDBC Driver
Ventor Specific
ODBC Driver
JDBC API
JDBC Driver API
Database
Database
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 6
The Basic Java Classes
The vast majority of the classes used for accessing SQL databases can
be found in the java.sql package. The functions of these classes
are:
Driver. This is a class associated with the database driver that is used to
communicate with a database. This class is not usually accessed by the
programmer.

Connection. This is the class which contains facilities for connecting to
a database. Execution of SQL statements is associated with a database
connected to a Connection object.

Statement. This class is used to create and execute SQL statements.
PreparedStatement. This class is used to develop SQL statements which
have an increased efficiency when executed a number of times with different
arguments.
CallableStatement. This class provides the programmer with the
facilities for calling stored procedures.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 7
The Basic Java Classes II
ResultSet. When an SQL statement is executed a result set is usually
returned. This result set will contain objects which are rows of the table which
has been created by the query.
ResultSetMetaData. There are a collection of classes in java.sql
which provide data about the main entities that this package manipulates. This
class provides metadata information about result sets extracted as a result of
queries.
DatabaseMetaData. This is another metadata class. In this case it provides
information about a database. For example, it enables the programmer to
discover whether the database supports stored procedures, whether the
database supports ANSI92 SQL and what the product version of the database
is.
DriverManager. This is a class that manages the drivers that are available
for connecting to a database.
DriverPropertyInfo. This class is not used by application programmers.
It contains a number of instance variables which are used by drivers in order to
connect into a relational database.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 8
Accessing a Database: Processing Steps
1. Load a driver which is compatible with the database that is to be
processed.
2. Define and establish a connection to the database.
3. Associate an SQL statement with this connection.
4. Execute the SQL statement.
5. The SQL statement which has been executed will produce a table
which is stored in a ResultSet object. This object will contain a
reference to the rows of the table that has been formed by the
execution of the SQL statement.
6. Execute further SQL statements as above.
7. When the processing associated with the database is complete the
database is closed and the connection to the database is also closed.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 9
Accessing a Database: Processing Steps Example
1. Class.forName("org.gjt.mm.mysql.Driver");

2. Connection conn = DriverManager.getConnection(
"jdbc:mysql://mysql0.ee.surrey.ac.uk:3306/webtech",
"webtech", "webtech");

3. Statement st = conn.createStatement();

4. ResultSet rs=st.executeQuery("SELECT * FROM images");

5. while(rs.next()){
anInteger = rs.getInteger(1);
aString = rs.getString(2);
}

7. st.close();
rs.close();
conn.close();
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 10
Define and Establish the Connection
Create a connection object
Connection conn = null;

Load the JDBC driver and connect to the database
Class.forName("driver...");

conn = DriverManager.getConnection("url..."
, [Username], [Password]);


NOTE: All functions of connecting and using a database should be enclosed
within a try-catch block.
NOTE: A database connection should always be closed after the code has finished
using the database.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 11
Create a Statement Object and Execute
Create a Statement object and execute the SQL

Statement st = conn.createStatement();

// for selecting records
ResultSet rs = st.executeQuery("query...");
or
// for inserting, deleting or updating records
int numRows = st.executeUpdate("query...");


NOTE: Capturing exceptions is important and should not be ignored
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 12
Process the Results
Process the ResultSetMetaData
ResultSetMetaData rm = rs.getMetaData();
rm.getColumnCount(); // Number of columns
rm.getColumnName(1); // Name of column
rm.getColumnType(1); // Data type of column

Process the ResultSet
rs.next(); // move to next record, returns boolean
rs.getXxx();
rs.getString(1); // using column id
rs.getString("name"); // using column name
rs.getInteger(2);
Rs.getObject(3);
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 13
Example: Displaying results on a Table
First (based on previous 3 slides):
Define and Establish the Connection
Create a Statement Object and Execute the SQL
Get the ResultSetMetaData and ResultSet

Then, get number of columns and build a list of column names

int columns = rm.getColumnCount();

result = "<tr>";
for ( int i = 1; i <= columns; i++){
result += "<td>" + rm.getColumnLabel(i) + "</td>";
}
result += "</tr>";
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 14
Example: Displaying results on a Table
Then, get the actual data
while(rs.next()) {
result += "<tr>";
for ( int i = 1; i <= columns; i++) {
result += "<td>" +
rs.getObject(i).toString() + "</td>";
}
result += "</tr>";
}
Close the Statement, ResultSet, and Connection
st.close();
rs.close();
conn.close();
Eventually, you print the results on a JSP page
<table border="1">
<%=result%>
</table>
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 15
Example: Advanced Catch
try { // All the database stuff here
}
catch (ClassNotFoundException e) {
result = " <tr><td>Database drive Error!";
result += " <br/>" + e.toString() + "</td></tr>";
}
catch (SQLException e) {
result = " <tr><td> Error processing the SQL!";
result += " <br/>" + e.toString()+ "</td></tr>";
}
finally { /* We always close the database connection! */
try {
if (conn != null) conn.close();
}
catch (SQLException e) {
result = "<tr><td> Closing connection Error";
result += "<br/>"+ e.toString() +"</td></tr>";
}
}
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 16
Example: Dynamic SQL Generation
search.jsp
...
<form name="form1" action="showResults.jsp">
<input type="text" name="imageID"/>
</form>
...

showResults.jsp
...
String imgID = request.getParameter("imageID");
String sql = "select * from images where id=" + imgID;
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 17
Database Transactions
A database which will be the target of a number of transactions that
will update it can be in two states.

The first is the autocommit state. In this state any change that is
required to the database occurs automatically.

The second state is often referred to as the manual commit state.
Here changes occur when the programmer explicitly issues a
commit command. What this does is to apply all those changes to a
database which have been saved up from the last commit command
or a command known as a rollback command.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 18
Issues I
Connection Pooling
Connections to a database are the most expensive operations
performed in terms of time and resources.
A method to control the database connections is called connection
pooling. This should be used to speed up database access and
reduce the number of database connections used by any Web
application.
Testing Components
Driver software (or components) doesnt always work as expected.
Nothing is bug free.
Budgeting time and resources to deal with unexpected problems
should always be considered when working with components.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 19
Issues II
Testing for Scale
Always test with realistic data sizes.
Large final datasets will always clutter your system if you havent
prepared for it.
Basic Design Concepts
JSP should be used at the presentation layer.
All reusable or modular logic should be pushed into a JavaBean or
Tag library (Business Objects).
Reusable code.
Modular and easier to update and maintain.
Never put presentation level functionality into lower-level
components such as JavaBeans.
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 20
Demo
Follow the demo and ask questions!
Server-Side Web Development
02
nd
March 2006 Bogdan L. Vrusias 2006 21
Closing

Questions???
Remarks???
Comments!!!
Evaluation!

You might also like