JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary...

117
JDBC Some introductory database terminology Basic JDBC Servlets JDBC and servlets Gary Alperson helped developed these slides.
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    229
  • download

    1

Transcript of JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary...

Page 1: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

JDBC

1 Some introductory database terminology2 Basic JDBC3 Servlets 4 JDBC and servlets

Gary Alperson helped developed these slides.

Page 2: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Database Terminology

• Database: A shared collection of logically related data (and a description of this data) designed to meet the information needs of an organization

• Relation: A table with columns and rows

• Attribute: A named column of a relation

• Tuple: A row in a relation

Definitions from Database Systemsby Connolly, Begg, and Strachan

Page 3: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Sample Table

brokerb_id lname fname

1 Smith John2 Jones Hannah3 Reynolds Leon4 Chang Donna5 Smith Deborah6 Thompson Daniel7 Frendun Laura

Page 4: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

brokerb_id lname fname

1 Smith John2 Jones Hannah3 Reynolds Leon4 Chang Donna5 Smith Deborah6 Thompson Daniel7 Frendun Laura

Attribute

Page 5: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

brokerb_id lname fname

1 Smith John2 Jones Hannah3 Reynolds Leon4 Chang Donna5 Smith Deborah6 Thompson Daniel7 Frendun Laura

Tuple

Page 6: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

SQL

• Data Definition Language (DDL)– Create tables– Modify tables– Delete (drop) tables

• Data Manipulation Language (DML)– Insert data– Update data– Select data

Page 7: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Select Statement

brokerb_id lname fname

1 Smith John2 Jones Hannah3 Reynolds Leon4 Chang Donna5 Smith Deborah6 Thompson Daniel7 Frendun Laura

We will use this data for our examples

Page 8: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

From the broker table, select the contents of the last name attribute

Query

SELECT lname

FROM broker;

ResultslnameSmithJonesReynoldsChangSmithThompsonFrendun

SQL is not case sensitive. Key SQL words are capitalized and line breaks are inserted by convention.

Page 9: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

From the broker table, select all attributes

Query

SELECT *

FROM broker;

Results

* Acts as a wildcard

brokerb_id lname fname

1 Smith John2 Jones Hannah3 Reynolds Leon4 Chang Donna5 Smith Deborah6 Thompson Daniel7 Frendun Laura

Page 10: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

From the broker table, select all attributes where the last name is Smith

Query

SELECT *

FROM broker

WHERE lname = ‘Smith’;

Results

•Note that the string is enclosed by single quotes•The contents of a string are case sensitive

brokerb_id lname fname

1 Smith John5 Smith Deborah

Page 11: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Use AND or OR to connect multiple where clauses

Query

SELECT *FROM brokerWHERE lname = ‘Smith’AND fname = ‘John’;

Results

b_id lname fname1 Smith John

Page 12: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Example with two Tables

One-to-many relationship•Each broker may have many customers•Each customer is only affiliated with one broker•The b_id joins both tables by identifying the unique broker that each customer is associated with

broker customerb_id lname fname

1 Smith John2 Jones Hannah3 Reynolds Leon4 Chang Donna5 Smith Deborah6 Thompson Daniel7 Frendun Laura

customerid b_id lname fname

1 1 LeParc Wilson2 1 AnstinceDevon3 2 Tabor Mark4 2 Lenks Sandy5 2 PhillipsonRichard6 3 Kini Raghu7 4 Kim David

Page 13: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Cartesian Productbroker.b_id

broker.lname

broker.fname

id customer.b_id

broker.lname

broker.fname

1 Smith John 1 1 LeParc Wilson1 Smith John 2 1 Anstince Devon1 Smith John 3 2 Tabor Mark1 Smith John 4 2 Lenks Sandy1 Smith John 5 2 Phillipson Richard1 Smith John 6 3 Kini Raghu1 Smith John 7 4 Kim David2 Jones Hannah 1 1 LeParc Wilson2 Jones Hannah 2 1 Anstince Devon2 Jones Hannah 3 2 Tabor Mark2 Jones Hannah 4 2 Lenks Sandy2 Jones Hannah 5 2 Phillipson Richard2 Jones Hannah 6 3 Kini Raghu2 Jones Hannah 7 4 Kim David3 Reynolds Leon 1 1 LeParc Wilson3 Reynolds Leon 2 1 Anstince Devon3 Reynolds Leon 3 2 Tabor Mark3 Reynolds Leon 4 2 Lenks Sandy3 Reynolds Leon 5 2 Phillipson Richard3 Reynolds Leon 6 3 Kini Raghu3 Reynolds Leon 7 4 Kim David4 Chang Donna 1 1 LeParc Wilson4 Chang Donna 2 1 Anstince Devon4 Chang Donna 3 2 Tabor Mark4 Chang Donna 4 2 Lenks Sandy4 Chang Donna 5 2 Phillipson Richard4 Chang Donna 6 3 Kini Raghu4 Chang Donna 7 4 Kim David

When you do a query on multiple tables, SQL begins by creating the Cartesian product, which combines each tuple from one relation from every tuple of the other relation.(Actual SQL implementationsare free to compute the resulting table efficiently,i.e., the actual Cartesian product may not be generated at all.)

Page 14: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Query

SELECT *

FROM customer, broker

WHERE broker.b_id = 1;

SQL does not realize that the b_id in the customer table is the same as the b_id in the broker table unless you join them in the

where clause.

broker.b_id

broker.lname

broker.fname

id customer.b_id

broker.lname

broker.fname

1 Smith John 1 1 LeParc Wilson1 Smith John 2 1 Anstince Devon1 Smith John 3 2 Tabor Mark1 Smith John 4 2 Lenks Sandy1 Smith John 5 2 Phillipson Richard1 Smith John 6 3 Kini Raghu1 Smith John 7 4 Kim David

Results

Page 15: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Cartesian ProductQuery

SELECT *

FROM customer, broker

WHERE broker.b_id = 1

AND broker.b_id = customer.b_id;

Resultsbroker.b_id

broker.lname

broker.fname

id customer.b_id

broker.lname

broker.fname

1 Smith John 1 1 LeParc Wilson1 Smith John 2 1 Anstince Devon

Page 16: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Java’s JDBC

• Allows access to any ANSI SQL-2 DBMS• Does its work in terms of SQL• The JDBC has classes that represent: database connections SQL Statements Result sets database metadata• Can be connected to ODBC• Many drivers exists

Page 17: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Basic Steps in using JDBC

1. Create a driver object.2. The driver object will inform the Driver Manager that it is available3. Create a database URL. This needs to point to the database to which you want to connect.4. Ask the DriverManager for a Connection object. The manager must be told what driver you need and the URL in 3.5. Get a Statement object from the Connection.6. Execute a query or an update on the Statement.7. Handle results.8. Close the connection.

Page 18: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Create the driver

Example:

Class.forName(“oracle.jdbc.driver.OracleDriver”).newInstance();

When a new instance of the driver is created it will informthe DriverManager class of its existence.

Page 19: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Create the database URL

The exact format depends on the particular driver.

Examples:

String host = “dbhost.yourcompany.com”; String dbName = “somename”; int port = 1234; String oracleURL = “jdbc:oracle:thin@” + host + “:” + port + “:” + dbName;

Page 20: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Build a Connection object

• java.sql.Connection is an interface

• Within the context of a Connection, SQL statements are executed and results are returned.

• A Connection object is able to provide information describing the database as a whole through its getMetaData method(). • The default Connection automatically commits changes after executing each statement. If auto commit has been disabled, an explicit commit must be done or database changes will not be saved.

Page 21: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Build a Connection object

Connection c = DriverManager.getConnection( oracleURL, “mm6”, “seseme”);

Page 22: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Get a Statement from the Connection

The Statement interface has two subinterfaces

• PreparedStatement extends Statement This is an object that represents a precompiled SQL statement. • CallableStatement extends PreparedStatement The interface used to execute SQL stored procedures.

Page 23: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Get a Statement from the Connection

c.setAutoCommit(false);Statement s = con.createStatement();

s.executeUpdate(command1);s.executeUpdate(command2);e.executeUpdate(command3);

// Now we are free toc.commit();// or..c.rollback();

Page 24: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

The Statement Object may produce a ResultSet

ResultSet rs = s.executeQuery(“SELECT * FROM Broker”);

while (rs.next()) {

// examine each row of the result set String n = rs.getString(columnNumber); double f = rs.getDouble(“SomeColumnName”); }

// each get method tries to make a reasonable type conversion// get may be used with integer column numbers starting // at 1 or a column name

Page 25: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

The Statement Object may return an int

int rowsChanged = s.executeUpdate(“CREATE TABLE” + … );

Executes an SQL INSERT, UPDATE or DELETE statement. In addition, SQL statements that return nothing, such as SQL DDL statements, can be executed.

Returns: either the row count for INSERT, UPDATE or DELETE or 0 for SQL statements that return nothing

Throws: SQLException - if a database access error occurs

Page 26: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

An Example

The SQL

SELECT customer.lname

FROM customer, broker

WHERE broker.lname = ‘Smith’

AND broker.b_id <> 1

AND broker.b_id = customer.b_id;

From both tables select the last names of all customers whose broker’s last name is Smith but whose broker ID is not 1.

Page 27: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Executing a query in Java

// Statement aStatement = statement got from connection

String last = “Smith”;

int nonID = 1;

String q = “SELECT customer.lname FROM customer, broker” + “WHERE broker.lname = \’” + last + “\’ AND broker.b_id” + “<>” + nonID + “AND broker.b_id = customer.b_id;”);ResultSet rs = aStatement.executeQuery(q);

•The slash (\) is the escape character. It precedes the single quote to tell Java to include that quote in the String•The String last is outside of the double quotes, because it must be concatonated with the String sent to the database, but it falls within the single quotes so that SQL treats it as a string•nonID does not go within single quotes since it is numeric•Since the String is an SQL statement, it uses = and <> rather than == and !=

Page 28: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Java Servlets

• Part I Server and servlet basics• Part II Session Tracking and Servlet

Collaboration• Part III Connecting to database

Page 29: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Part I : Server and Servlet Basics

• NetworkServer.java and EchoServer.java

• PostForm.html

• GetForm.html

• More HTML form examples

Page 30: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

NetworkServer.java// NetworkServer.java Adapted from "Core Servlets// and Java Server Pages" // by Marty Hall

import java.net.*;import java.io.*;

public class NetworkServer {

private int port; private int maxConnections;

No Tomcat server.Just this code.

Page 31: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

protected void setPort(int port) { this.port = port; }

public int getPort() { return port; }

protected void setMaxConnections(int max) { maxConnections = max; }

public int getMaxConnections() { return maxConnections; }

public NetworkServer(int port, int maxConnections) { setPort(port); setMaxConnections(maxConnections); }

Page 32: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

// Wait for a connections until maxConnections.// On each connection call handleConnection() passing// the socket. If maxConnections == 0 loop forever

public void listen() { int i = 0; try { ServerSocket listener = new ServerSocket(port); Socket server ; while((i++ < maxConnections) || (maxConnections == 0)) { server = listener.accept(); // wait for connection handleConnection(server); } } catch (IOException ioe) { System.out.println("IOException : " + ioe); ioe.printStackTrace(); } }

Page 33: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

// Open readers and writers to socket.// Display client's host name to console.// Read a line from the client and display it on the console.// Send "Generic network server" to the client.// Override this method.

protected void handleConnection(Socket server) throws IOException {

BufferedReader in = new BufferedReader( new InputStreamReader( server.getInputStream() ));

PrintWriter out = new PrintWriter( server.getOutputStream(),true);

Flush bufferon println

InputStream forreading bytes

Readers and Writersto work with characters

Page 34: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

System.out.println("Generic network server: got connection from "+ server.getInetAddress().getHostName() + "\n" + "with first line '" + in.readLine() + "'"); out.println("Generic network server"); server.close(); }

public static void main(String args[]) { NetworkServer test = new NetworkServer(6502, 5); test.listen(); }}

To server’sconsole.

To client.

Page 35: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Compile, Run and Visit

C:\McCarthy\www\46-928\examples\networking>java NetworkServerGeneric network server: got connection from localhostwith first line 'GET / HTTP/1.0'

Client

Server

Page 36: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

EchoServer.java/* From Core Servlets, Marty Hall

An HTTP Request header example Notes

GET /path/file.html HTTP/1.0 The whitespace is required.Accept: text/html Accept header fieldsAccept: audio/x tell the server MIME typesUser-agent: MacWeb (Multipurpose Internet

Mail Extension) that are handled by the browser.

Still no TomcatHTTP defines dozens of possible headers.

Request terminated by two returns

Page 37: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

EchoServer.javaAn HTTP Response header example

HTTP 1.0 200 OKServer: NCSA/1.4.2MIME-version: 1.0Content-type: text/htmlContent-length: 107

<html>::</html>

Blank line

MIME type

The client must interpretthis MIME encoded data.

Response code

Page 38: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

HTTP General form

<method> <resource identifier> <HTTP Version> <crlf>[<Header> : <value>] <crlf> : : :[<Header> : <value>] <crlf> a blank line[entity body]

The resource identifier field specifies the name of the targetresource; it's the URL stripped of the protocol and the serverdomain name. When using the GET method, this field will alsocontain a series of name=value pairs separated by ‘&’. When usinga POST method, the entity body contains these pairs.

The HTTP version identifies the protocol used by the client.*/

Page 39: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

// Adapted from Core Servlets and JavaServerPages// by Marty Hall, chapter 16

import java.net.*;import java.io.*;import java.util.StringTokenizer;

public class EchoServer extends NetworkServer {

protected int maxRequestLines = 50; // Post data is brought in // as a single string. protected String serverName = "EchoServer";

public static void main(String a[]) {

int port = 6502; new EchoServer(port,0); // loop forever }

Page 40: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public EchoServer(int port, int maxConnections) { super(port,maxConnections); // call base class constructor listen(); // call base class listen() } // listen calls handleConnection() // Overrides base class handleConection and is called by listen() public void handleConnection(Socket server) throws IOException {

// Assign readers and writers to the socket BufferedReader in = new BufferedReader( new InputStreamReader( server.getInputStream() )); PrintWriter out = new PrintWriter(server.getOutputStream(),true); // Announce connection to console System.out.println(serverName + " got connection from "+ server.getInetAddress().getHostName() + "\n");

Page 41: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

String inputLines[] = new String[maxRequestLines]; int i; for(i = 0; i < maxRequestLines; i++) { inputLines[i] = in.readLine(); if(inputLines[i] == null) break; // client closed connection if(inputLines[i].length() == 0) { // blank line // maybe done or maybe post if(usingPost(inputLines)) { // readPostData reads into a single string // at location i+1 readPostData(inputLines,i,in); // i was not changed in the procedure so // bump it one past the post data string i = i + 2; } break; // we’re done either way } }

Page 42: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

printHeader(out); for(int j = 0; j < i; j++) { out.println(inputLines[j]); }

printTrailer(out); server.close(); }

//Request Data

// HTTP + HTML

// Closing HTML

Page 43: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

private void printHeader(PrintWriter out) { out.println( "HTTP/1.0 200 OK\r\n" + "Server: " + serverName + "\r\n" + "Content-Type: text/html\r\n" + “\r\n” + "<!DOCTYPE HTML PUBLIC " + "\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" + "<HTML>\n" + "<HEAD>\n" + " <TITLE>" + serverName + " Results</TITLE>\n" + "</HEAD>\n" + "\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + serverName + " Results</H1>\n" + "Here is your request line and request headers\n" + "sent by your browser:\n" + "<PRE>“ ); // honors whitespace }

HTTP Responseheaders plus HTML.

Page 44: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

private void printTrailer(PrintWriter out) {

out.println("</PRE>\n" + "</BODY>\n" + "</HTML>\n"); }

private boolean usingPost(String[] inputs) { return (inputs[0].toUpperCase().startsWith("POST")); }

// Close HTML

// Checks if post

Page 45: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

// Read the post data as a single array of char and place it all// in one string. private void readPostData (String inputs[], int i, BufferedReader in) throws IOException {

int contentLength = contentLength(inputs); char postData[] = new char[contentLength]; in.read(postData, 0, contentLength); // All of the post data is converted to a single string inputs[++i] = new String(postData,0,contentLength); }

Page 46: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

// The header fields may arrive in any order.// Search for and return the CONTENT-LENGTH. private int contentLength(String inputs[]) { String input; for(int i = 0; i < inputs.length; i++) { if(inputs[i].length() == 0) break; input = inputs[i].toUpperCase(); if(input.startsWith("CONTENT-LENGTH")) return (getLength(input)); } return (0); } // Return the integer associated with the second token. private int getLength(String length) { StringTokenizer tok = new StringTokenizer(length); tok.nextToken(); return (Integer.parseInt(tok.nextToken())); }}

Page 47: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

PostForm.html<!-- PostForm.html --><html><head><title>Post Form</title></head><body> <form method="post" action="http://localhost:6502"> Hi, what is your name? <input type="text" name = "name"> <p> What is your age? <input type="text" name = "age"> <p> <input type = "submit"> </form></body></html>

Visit the port

Page 48: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

PostForm.html Browser

Page 49: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

EchoServer Response Using POST

POST data

Size of

Name value pairswith spaces as ‘+’etc.

Page 50: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

GetForm.html<!-- GetForm.html --><html><head><title>Get Form</title></head><body> <form method="get" action="http://localhost:6502"> Hi, what is your name? <input type="text" name = "name"> <p> What is your age? <input type="text" name = "age"> <p> <input type = "submit"> </form></body></html>

Page 51: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

GetForm.html Browser

Page 52: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

EchoServer Response Using GET

GET data

Page 53: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

A Form With Checkboxes<!-- CheckBox.html --><html><head><title>CheckBoxes</title></head><body BGCOLOR="WHITE"> <form action="http://localhost:6502"> <dl> <dt> Select Pizza Toppings </dt> <dd><Input type = "CheckBox" name = "Pepperoni"> Pepperoni <dd><Input type = "CheckBox" name = "Sausage"> Sausage <dd><Input type = "CheckBox" name = "Extra Cheese"> Extra Cheese <dd><Input type = "CheckBox" name = "Mushrooms"> Mushrooms <p> <input type = "submit"> </dl> </form></body></html>

Page 54: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

CheckBoxes Browser

Page 55: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

CheckBox Response

Data from client

Page 56: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

RadioBoxes HTML<!-- Radio.html --><html><head><title>Radio Buttons</title></head><body BGCOLOR="WHITE"> <form action="http://localhost:6502"> <dl> <!– Definition list --> <dt> Please Vote </dt> <!- The term to be defined left margin--> <!-- Item definitions indented and below --> <dd><Input type = "Radio" name = "president" value= "Bush"> <b>George W. Bush</b> <dd><Input type = "Radio" name = "president" value = "Gore"> Al Gore <dd><Input type = "Radio" name = "president" value = "Buchanan"> Pat Buchanan <dd><Input type = "Radio" name = "president" value = "Nader"> Ralph Nader <p> <input type = "submit"> </dl> </form></body></html>

Page 57: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

RadioBoxes Browser

Page 58: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

EchoServer Response

Page 59: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Reading Form Data With Servlets Under Tomcat

// QueryData.java -- Handle the voting form in radio.htmlimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class QueryData extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { doGet(req, response); }

We have lesswork to do.

Page 60: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { String newPresident = req.getParameter("president");

response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"//W3C//DTD” + “HTML 4.0 "; docType += "Transitional//EN\">\n";

Page 61: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Presidential Servlet" + "</TITLE>” + “</HEAD>\n" + "<BODY>\n" + "<H1>The new president is "+ newPresident + "</H1>\n" + "</BODY></HTML>"); }}

Page 62: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

<!-- Radio.html (Modified for servlets)--><html><head><title>Radio Buttons</title></head><body BGCOLOR="WHITE"> <form action="http://localhost:8080/servlet/QueryData"> <dl> <dt> Please Vote </dt> <dd><Input type = "Radio" name = "president" value= "Bush"> <b>George W. Bush</b> <dd><Input type = "Radio" name = "president" value = "Gore"> Al Gore <dd><Input type = "Radio" name = "president" value = "Buchanan"> Pat Buchanan <dd><Input type = "Radio" name = "president" value = "Nader"> Ralph Nader <p> <input type = "submit"> </dl> </form></body></html>

servletTomcat’s port

Page 63: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Radio HTML in the browser

Page 64: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

The Servlet’s Response

Page 65: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Handling CheckBoxes<!-- CheckBox.html --><html><head><title>CheckBoxes</title></head><body BGCOLOR="WHITE"> <form action="http://localhost:8080/servlet/PizzaData"> <dl> <dt> Select Pizza Toppings </dt> <dd><Input type = "CheckBox" name = "Pepperoni"> Pepperoni <dd><Input type = "CheckBox" name = "Sausage"> Sausage <dd><Input type = "CheckBox" name = "Extra Cheese"> Extra Cheese <dd><Input type = "CheckBox" name = "Mushrooms"> Mushrooms <p> <input type = "submit"> </dl> </form></body></html>

servlet

Page 66: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Pizza Toppings

Page 67: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Servlet Response

Page 68: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

PizzaData Servlet// PizzaData.java -- Handle the toppings selection from pizza.htmlimport java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

public class PizzaData extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

doGet(req, response); }

Page 69: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String finalString = "";

Enumeration paramNames = req.getParameterNames();

while(paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); finalString += paramName + ":" ;

finalString += req.getParameter(paramName) + "<p>"; }

Enumerate over theinput.

Page 70: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

String docType = "<!DOCTYPE HTML PUBLIC \"//W3C//DTD” + “ HTML 4.0 "; docType += "Transitional//EN\">\n";

out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Pizza Selections" + "</TITLE>” + “</HEAD>\n" + "<BODY>\n" + "<H1>" + finalString + "</H1>\n" + "</BODY></HTML>"); }

}

Page 71: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Part II Session Tracking and Servlet Collaboration

• First we will use a shared object

• Then we’ll use the new Session Tracking API

Page 72: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Session Tracking with Servlets

HTTP is a stateless protocol.

We must have each user introduce themselves in some way.

We’ll look at traditional session tracking and then look at theSession Tracking API.

Page 73: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Traditional Session Tracking

• User Authorization

• Hidden Form fields

• URL Rewriting

• Persistent cookies

We’ll look at the first and last.

Page 74: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

User Authorization

• The web server requests the user name and password. The information is available to any servlet that needs it.

• The browser resends the name and password with each subsequent request.

• Data about the user and the user’s state can be saved in a shared object.

Page 75: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Shared Objects

• A convenient way to store data associated with a user. •There are likely to be many servlets running.• They can collaborate through a shared object.• Only one instance of the shared object should exist.• It has to be available (in the classpath) of the servlets that needs it.• It will be used by several threads and therefore should protect itself against simultaneous access.• We’ll look at a shared object and two servlets that use it.

Page 76: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

VisitTracker.java

// Servlet collaboration can be done through a shared object.// Any servlet has access to this object and it only has one// instance.// It maintains a hash table of names and dates.

// Sections of code that must not be executed simultaneously// are called critical sections. Java provides the synchronized // keyword to protect these critical sections. For a synchronized// instance method, Java obtains an exclusive lock on the class// instance.

import java.util.*;

Page 77: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public class VisitTracker {

private Map nameDatePairs; private static VisitTracker instance = new VisitTracker(); private VisitTracker() { // private constructor nameDatePairs = new HashMap(); }

public static VisitTracker getInstance() { return instance; }

synchronized public void addVisit(String userName) {

nameDatePairs.put(userName, new Date()); }

Page 78: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

synchronized public Date lastVisit(String name) {

Date d = (Date)nameDatePairs.get(name); return d;

} }

Page 79: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

User Authorization

• Administered by the web server – Tomcat• Edit Tomcat’s deployment descriptor• From within the servlet use String name = req.getRemoteUser(); to access the user name.• We have to assign user names and passwords. tomcat-users.xml

• The following will keep track of the date of the last visit.

<tomcat-users> <user name="tomcat" password="tomcat" roles="tomcat" /> <user name="role1" password="tomcat" roles="role1" /> <user name="both" password="tomcat" roles="tomcat,role1" /> <user name="mike" password="tomcat" roles="student" /></tomcat-users>

Page 80: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

// UserAuthorizationDemo.java// This servlet reads from Tomcat and finds the name of the// authorized user. It then adds it to a hash table storing// the time of this visit. It makes use of VisitTracker.

import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

public class UserAuthorizationDemo extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

Page 81: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

res.setContentType("text/plain"); PrintWriter out = res.getWriter(); String name = req.getRemoteUser(); // ask the server if(name == null) { System.out.println("The system administrator should protect" + " this page."); } else { out.println("This user was authorized by the server:" + name); VisitTracker visit = VisitTracker.getInstance(); Date last = visit.lastVisit(name); if(last == null) out.println("Welcome, you were never here before"); else out.println("Your last visit was on " + last); visit.addVisit(name); } }}

Page 82: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Cookies• A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser.

• The server can take that bit of information and use it as a key to recover information about prior visits. This information may be in a database or a shared object.

• Cookies are read from the request object by calling getCookies() on the request object.

• Cookies are placed in the browser by calling addCookie() on the response object.

Page 83: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Using Cookies// CookieDemo.java

// This servlet uses a cookie to determine when the// last visit by this browser occurred. It makes use of // the VisitTracker object.

// Cookies normally expire as soon as the browser exits.// We want the cookie to last one year and so we use// setMaxAge(seconds) on the cookie.

import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

Page 84: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public class CookieDemo extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/plain"); PrintWriter out = res.getWriter();

Cookie[] c = req.getCookies(); // If this person has been here before then we should have // a cookiedemouser field assigned to a unique id. String id = null;

Page 85: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

if (c!=null) { // we may have the cookie we are after

for (int i=0;i<c.length;i++) {

if (c[i].getName().equals("cookiedemouser")) {

id = c[i].getValue(); } break; } }

Page 86: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

if (id == null) { // They have not been here before and need a // cookie. We get a unique string (with respect // to this host)and make sure it is of the 'query string' form. // It uses the clock. Don’t turn the clock back! String uid = new java.rmi.server.UID().toString(); id = java.net.URLEncoder.encode(uid); Cookie oreo = new Cookie("cookiedemouser",id); oreo.setMaxAge(60*60*24*365); res.addCookie(oreo); } VisitTracker visit = VisitTracker.getInstance(); Date last = visit.lastVisit(id); if(last == null) out.println("Welcome, you were never here before"); else out.println("Your last visit was on " + last); visit.addVisit(id); }}

Page 87: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

The New Session Tracking API

• Support may vary depending on the server.• Implemented with cookies or with URL rewriting if cookies fail (URL rewriting requires help from the servlet).• Every user of the site is associated with a javax.servlet.http.HttpSession object• The session object can hold any arbitrary set of Java objects.• Servlets collaborate by accessing the session object.• The following example abstracts away shared object concerns.• All valid sessions are grouped together in a HttpSessionContext object

Page 88: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

The Session Tracking API// SessionDemo.java// The session object associated with this user/browser is available// to other servlets.

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

public class SessionDemo extends HttpServlet {

Page 89: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/plain"); PrintWriter out = res.getWriter();

// Get the current session object. Create one if none exists. HttpSession session = req.getSession(true);

// Get the Date associated with this session Date d = (Date)session.getAttribute("dateofvisit");

if(d == null) out.println("Your first time, welcome!"); else out.println("Your last visit was on " + d);

session.setAttribute("dateofvisit", new Date()); } }

Page 90: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Part III Connecting to the database

Per-Transaction Connections

Dedicated Connections

Session Connections

Notes taken from “Java Programming with Oracle JDBC”By Donald Bales

Page 91: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Per-Transaction Connection

Servlet

init() { load the driver and inform the DriverManager } doxxx() { get a connection : operate on statements, result sets… : close connection }

Each visit gets its own connection.

Page 92: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Per-Transacation Connection

// Form Oracle JDBC by Balesimport java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;

public class TransactionConnectionServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException { super.init(config); try { // load the driver Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); }

Page 93: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

catch (ClassNotFoundException e) { throw new UnavailableException( "TransactionConnection.init() ClassNotFoundException: " + e.getMessage()); } catch (IllegalAccessException e) { throw new UnavailableException( "TransactionConnection.init() IllegalAccessException: " + e.getMessage()); } catch (InstantiationException e) { throw new UnavailableException( "TransactionConnection.init() InstantiationException: " + e.getMessage()); } }

Page 94: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>A Per Transaction Connection</title>"); out.println("</head>"); out.println("<body>"); Connection connection = null; try { // establish a connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger"); } catch (SQLException e) { throw new UnavailableException( "TransactionConnection.init() SQLException: " + e.getMessage()); }

Page 95: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

Statement statement = null; ResultSet resultSet = null; String userName = null; try { // test the connection statement = connection.createStatement(); resultSet = statement.executeQuery( "select initcap(user) from sys.dual"); if (resultSet.next()) userName = resultSet.getString(1); } catch (SQLException e) { out.println( "TransactionConnection.doGet() SQLException: " + e.getMessage() + "<p>"); }

Page 96: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) { } if (statement != null) try { statement.close(); } catch (SQLException ignore) { } } if (connection != null) { // close the connection try { connection.close(); } catch (SQLException ignore) { } } out.println("Hello " + userName + "!<p>"); out.println("You're using a per transaction connection!<p>"); out.println("</body>"); out.println("</html>"); }

public void doPost( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }}

Page 97: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

A Dedicated ConnectionServlet

init() { load driver and inform manager open connection } doxxx() { use connection commit transaction } destroy { when servlet container is brought down close the connection }

Page 98: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

A Dedicated Connection

One connection per servletOpen during life of servletAll users of this servlet use the same connectionOracle’s connection class’s methods are thread safeUnder this approach, servlets do not share connections

Page 99: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

A Dedicated Connection// From the book Oracle JDBC by Balesimport java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;

public class DedicatedConnectionServlet extends HttpServlet { Connection connection; long connected;

Page 100: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void init(ServletConfig config) throws ServletException { super.init(config); try { // load the driver Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); } catch (ClassNotFoundException e) { throw new UnavailableException( "DedicatedConnection.init() ClassNotFoundException: " + e.getMessage()); } catch (IllegalAccessException e) { throw new UnavailableException( "DedicatedConnection.init() IllegalAccessException: " + e.getMessage()); }

Page 101: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

catch (InstantiationException e) { throw new UnavailableException( "DedicatedConnection.init() InstantiationException: " + e.getMessage()); } try { // establish a connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger"); connected = System.currentTimeMillis(); } catch (SQLException e) { throw new UnavailableException( "DedicatedConnection.init() SQLException: " + e.getMessage()); } }

Page 102: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void doGet( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>A Dedicated Connection</title>"); out.println("</head>"); out.println("<body>"); Statement statement = null; ResultSet resultSet = null; String userName = null;

Page 103: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

try { // test the connection statement = connection.createStatement(); resultSet = statement.executeQuery( "select initcap(user) from sys.dual"); if (resultSet.next()) userName = resultSet.getString(1); } catch (SQLException e) { out.println( "DedicatedConnection.doGet() SQLException: " + e.getMessage() + "<p>"); } finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) { } if (statement != null) try { statement.close(); } catch (SQLException ignore) { } }

Page 104: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

out.println("Hello " + userName + "!<p>"); out.println( "This Servlet's database connection was created on " + new java.util.Date(connected) + "<p>"); out.println("</body>"); out.println("</html>"); } public void doPost( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } public void destroy() { // close the connection if (connection != null) try { connection.close(); } catch (SQLException ignore) { } }}

Page 105: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

A Session Connection

Servlet init() { load the driver and inform the driver manager } doxxx() { establish an HTTP Session object that holds the database connection If the session expires we must notify the connection to close }

Page 106: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

A Session Connection

We need an HTTPSessionBindingListener to close the connection when the session expires.

HTTPSession

SessionConnection

Implements HTTPSessionBindingListener

When this session expires the system will call the valueUnBound()method in the HTTPSessionBindingListener.

Page 107: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

SessionConnection// From Oracle JDBC by Balesimport java.sql.*;import javax.servlet.http.*;

public class SessionConnection implements HttpSessionBindingListener {

Connection connection;

public SessionConnection() { connection = null; }

Page 108: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public SessionConnection(Connection connection) { this.connection = connection; }

public Connection getConnection() { return connection; }

public void setConnection(Connection connection) { this.connection = connection; }

Page 109: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void valueBound(HttpSessionBindingEvent event) { if (connection != null) { System.out.println("Binding a valid connection"); } else { System.out.println("Binding a null connection"); } }

public void valueUnbound(HttpSessionBindingEvent event) { if (connection != null) { System.out.println( "Closing the bound connection as the session expires"); try { connection.close(); } catch (SQLException ignore) { } } }}

Page 110: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

SessionLogin import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;

public class SessionLogin extends HttpServlet {

public void init(ServletConfig config) throws ServletException { super.init(config); try { // load the driver Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); }

Page 111: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

catch (ClassNotFoundException e) { throw new UnavailableException( "Login init() ClassNotFoundException: " + e.getMessage()); } catch (IllegalAccessException e) { throw new UnavailableException( "Login init() IllegalAccessException: " + e.getMessage()); } catch (InstantiationException e) { throw new UnavailableException( "Login init() InstantiationException: " + e.getMessage()); } }

Page 112: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

public void doGet( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Login</title>"); out.println("</head>"); out.println("<body>"); HttpSession session = request.getSession(); SessionConnection sessionConnection = (SessionConnection)session.getAttribute("sessionconnection"); Connection connection = null;

Page 113: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

if (sessionConnection != null) { connection = sessionConnection.getConnection(); } if (connection == null) { String userName = request.getParameter("username"); String password = request.getParameter("password"); if (userName == null || password == null) { // prompt the user for her username and password out.println("<form method=\"get\" action=\"SessionLogin\">"); out.println("Please specify the following to log in:<p>"); out.println("Username: <input type=\"text\" " + "name=\"username\" size=\"30\"><p>"); out.println("Password: <input type=\"password\" " + "name=\"password\" size=\"30\"><p>"); out.println("<input type=\"submit\" value=\"Login\">"); out.println("</form>"); }

Page 114: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

else { // create the connection try { connection = DriverManager.getConnection( "jdbc:oracle:thin:@dssw2k01:1521:orcl", userName, password); } catch (SQLException e) { out.println("Login doGet() " + e.getMessage()); } if (connection != null) { // store the connection sessionConnection = new SessionConnection(); sessionConnection.setConnection(connection); session.setAttribute("sessionconnection", sessionConnection); response.sendRedirect("SessionLogin"); return; } } }

Page 115: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

else { String logout = request.getParameter("logout"); if (logout == null) { // test the connection Statement statement = null; ResultSet resultSet = null; String userName = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery( "select initcap(user) from sys.dual"); if (resultSet.next()) userName = resultSet.getString(1); } catch (SQLException e) { out.println("Login doGet() SQLException: " + e.getMessage() + "<p>"); }

Page 116: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) { } if (statement != null) try { statement.close(); } catch (SQLException ignore) { } } out.println("Hello " + userName + "!<p>"); out.println("Your session ID is " + session.getId() + "<p>"); out.println("It was created on " + new java.util.Date(session.getCreationTime()) + "<p>"); out.println("It was last accessed on " + new java.util.Date(session.getLastAccessedTime()) + "<p>"); out.println("<form method=\"get\" action=\"SessionLogin\">"); out.println("<input type=\"submit\" name=\"logout\" " + "value=\"Logout\">"); out.println("</form>"); }

Page 117: JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.

else { // close the connection and remove it from the session try { connection.close(); } catch (SQLException ignore) { } session.removeAttribute("sessionconnection"); out.println("You have been logged out."); } } out.println("</body>"); out.println("</html>"); }

public void doPost( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }}