Transcript Document

Introduction to Server-Side
Web Development
Introduction to Server-Side Web
Development using JSP and Databases
Session III: JSP and Databases
04th March 2004
Bogdan L. Vrusias
[email protected]
Introduction to Server-Side
Web Development
Session III
•
•
•
•
•
•
•
Relational Databases
Transactions
Middleware
Basic Java classes used for databases
Integrating JSP and Data
Examples
Issues
04th March 2004
Bogdan L. Vrusias © 2004
2
Introduction to Server-Side
Web Development
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 C++ or Java.
• 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.
• SQL is a simple language for accessing and updating
relational tables.
04th March 2004
Bogdan L. Vrusias © 2004
3
Introduction to Server-Side
Web Development
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.
04th March 2004
Bogdan L. Vrusias © 2004
4
Introduction to Server-Side
Web Development
Database Middleware
• There is a wide variety of middleware available which fits between
clients and database servers:
– The first component is an SQL API (Application Programmer’s
Interface). This provides programming facilities for developers
who wish, for example, to embed SQL code within procedural
languages.
– The second 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.
– The third is the protocol stack which is used for communicating
between the client and the server.
– The fourth is server software.
– A fifth category of software is that associated with remote
administration of a database.
04th March 2004
Bogdan L. Vrusias © 2004
5
Introduction to Server-Side
Web Development
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.
– 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.
– 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.
04th March 2004
Bogdan L. Vrusias © 2004
6
Introduction to Server-Side
Web Development
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.
04th March 2004
Bogdan L. Vrusias © 2004
7
Introduction to Server-Side
Web Development
Processing Steps
1.
2.
3.
4.
5.
6.
7.
Load a driver which is compatible with the database that is to be
processed.
Establish a connection to the database.
Associate an SQL statement with this connection.
Execute the SQL statement.
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.
Execute further SQL statements as above.
When the processing associated with the database is complete the
database is closed and the connection to the database is also closed.
04th March 2004
Bogdan L. Vrusias © 2004
8
Introduction to Server-Side
Web Development
Example I
try
{
// Load in the driver programmatically
Class.forName("org.gjt.mm.mysql.Driver");
}
catch (ClassNotFoundException cfn)
{
//Problem with driver, display error message
//and return to operating system with status
// value 1
System.out.println(“Problem loading driver”);
System.exit(1);
}
04th March 2004
Bogdan L. Vrusias © 2004
9
Introduction to Server-Side
Web Development
Example II
try {
Connection con = DriverManager.getConnection(
"jdbc:mysql://mysql0.ee.surrey.ac.uk:3306/webtech",
"webtech", "webtech");
Statement selectStatement = con.createStatement();
ResultSet rs = selectStatement.executeQuery("SELECT *
FROM links;");
...
while(rs.next()){
somevalue = rs.getString(1);
...}
selectStatement.close();
con.close();
rs.close();
}
catch(Exception e){ ... }
04th March 2004
Bogdan L. Vrusias © 2004
10
Introduction to Server-Side
Web Development
Using JSP with a Database
• Example of entering data:
– The process of entering data should be split across several JSP
pages
– First page will be the data input page.
– Second page will be the action page that will process the user data
entered in the input page.
NOTE: It’s a good idea to split the program logic across
several pages
04th March 2004
Bogdan L. Vrusias © 2004
11
Introduction to Server-Side
Web Development
Tips when Connecting to a Database
– Create a connection object
Connection l_dbconn = null;
NOTE 1: All functions of connecting and using a database should be enclosed
within a try-catch block.
NOTE 2: A database connection should always be closed after the code has
finished using the database.
– Load the JDBC driver and connect to the database
Class.forName(ls_dbdriver);
l_dbconn = DriverManager.getConnection(ls_dburl, [Username],
[Password]);
– Create a Statement object and execute the SQL
Statement l_statement = l_dbconn.createStatement();
l_statement.executeQuery(ls_query);
NOTE 3: Capturing exceptions is important and should not be ignored
04th March 2004
Bogdan L. Vrusias © 2004
12
Introduction to Server-Side
Web Development
Tips when Accessing the RecordSet I
– Create the SQL statement
String ls_query = "select * from links";
– Execute the SQL statement
if (statement.execute(ls_query))
– Grab the ResultSet and ResultSetMetaData
ResultSet results = statement.getResultSet();
ResultSetMetaData metadata = results.getMetaData();
– Get number of columns and build a list of column names
int li_columns = metadata.getColumnCount();
ls_result = "<tr>";
for ( int i = 1; i <= li_columns; i++){
ls_result += "<td>" + metadata.getColumnLabel(i) +
"</td>";
}
ls_result += "</tr>";
04th March 2004
Bogdan L. Vrusias © 2004
13
Introduction to Server-Side
Web Development
Tips when Accessing the RecordSet II
– Get the actual data
while(results.next()) {
results.getRow();
ls_result += "<tr>";
for ( int i = 1; i <= li_columns; i++) {
ls_result += "<td>“ +
results.getObject(i).toString() + "</td>";
}
ls_result += "</tr>";
}
– Print the results on the page
<table border="1">
<%=ls_result%>
</table>
04th March 2004
Bogdan L. Vrusias © 2004
14
Introduction to Server-Side
Web Development
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) doesn’t 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.
04th March 2004
Bogdan L. Vrusias © 2004
15
Introduction to Server-Side
Web Development
Issues II
• Testing for Scale
– Always test with realistic data sizes.
– Large final datasets will always clutter your system if you haven’t
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.
04th March 2004
Bogdan L. Vrusias © 2004
16
Introduction to Server-Side
Web Development
Session III: Closing
•
•
•
•
Questions???
Remarks???
Comments!!!
Evaluation!
04th March 2004
Bogdan L. Vrusias © 2004
17