COSC 2206 Internet Tools Java Servlets with JDBC and MySQL

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
Servlets and JDBC. Servlets A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password:
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password:
Java database Programming JDBC Trademarked name of a Java API that supports Java programs that access relational databases Stand for Java DataBase Connectivity.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
Examples of Using Servlets and JSP Representation and Management of Data on the Internet.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Java Servlets and Java Server Pages Carol Wolf Computer Science.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
Georgia Institute of Technology Making Text for the Web part 5 Barb Ericson Georgia Institute of Technology March 2006.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
Mark Dixon 1 09 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
JDBC – Java Database Concentricity
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Copyright  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
EXAMPLE I An application showing JDBC access to Cloudscape.
 2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Web Programming Assistant Professor Xiaozhong Liu
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
1 Download current version of Tomcat from: g/tomcat/ g/tomcat/ Install it in: C:\Program Files\Apache.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
Interacting with Database
Lec - 14.
JDBC 15-Apr-18.
J2EE (Enterprise Programing)
PERTEMUAN 3.
JDBC & Servlet CSE 4504/6504 Lab.
CS320 Web and Internet Programming Database Access with JDBC
Servlets Hits Counter 20-Jul-18.
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
Introduction to Server-Side Web Development using JSP and Databases
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
JAVA DATABaSE CONNECTIVITY
JDBC API.
JDBC Example.
Java Servlets Servlet Overview Servlets and HTML Forms Servlet Basics
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

COSC 2206 Internet Tools Java Servlets with JDBC and MySQL For complete install instructions http://www.cs.laurentian.ca/badams/c2206

JDBC-MySQL driver (1) JDBC (Java DataBase Connector) is a common interface (API) to various relational databases We will use the JDBC-MySQL driver that can be obtained from the MySQL web site www.mysql.com Download the file mysql-connector-java-3.0.14-production.zip 8/23/2019 BGA

JDBC-MySQL driver (2) Unzip to get a jar file which you can rename to a shorter name such as mysql-jdbc-driver.jar There is also an unjarred version in the com directory: the full name of the driver is com.mysql.jdbc.Driver Put the com directory and the jar file in your packages directory (e.g., c:\packages) for use in stand-alone java applications 8/23/2019 BGA

JDBC-MySQL driver (3) This gives two ways to compile a Java class that uses the driver: java -cp CLASSPATH MyClass where CLASSPATH is .;c:\packages;c:\packages\mysql-jdbc-driver.jar .;c:\packages The first uses the jar file and the second uses the unpacked com directory. 8/23/2019 BGA

JDBC-MySQL driver (4) When using servlets the tomcat server has its own classpath. In a web applciation called test the driver file mysql-jdbc-driver.jar must go in the directory c:\tomcat\webapps\test\WEB-INF\lib To make it available to all web applications put it in directory c:\tomcat\common\lib We won't need to do this. See JDBC install instructions for all details 8/23/2019 BGA

Database independence ResultSet ResultSet Statement PreparedStatement Connection DriverManager Driver Driver Driver MySQL database Oracle database ODBC database 8/23/2019 BGA

JDBC interface Class DriverManager Interface Connection ResultSet Statement RowSet PreparedStatement ResultSetMetaData CallableStatement RowSetMetaData 8/23/2019 BGA

Loading the driver The driver is loaded at runtime using the statement A ClassNotFoundException can be thrown Note that the Java compiler doesn't need to know the classpath to the driver since it is loaded at runtime by the Java interpreter. Class.forName("com.mysql.jdbc.Driver"); 8/23/2019 BGA

Connecting to database (1) The database, user name and password are specified by a URL-like string such as Parts of string can be specified by variables Now connect using String dsn = "jdbc:mysql://localhost:3306/ myDatabase?user=myUserName&password=myPassword"; String dsn = "jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password; Connection conn = DriverManager.getConnection(dsn); 8/23/2019 BGA

Connecting to database (2) import java.sql.*; ... try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) {...} try { Connection conn = DriverManager.getConnection(dsn); } catch (SQLException e) {...} 8/23/2019 BGA

ConnectionTester import java.sql.*; public class ConnectionTester { public static void main(String[] args) { // connection parameters String host = "localhost"; String port = "3306"; String user = ""; String password = ""; String database = ""; See jdbc install notes (html) 8/23/2019 BGA

ConnectionTester if (args.length == 3) { user = args[0]; password = args[1]; database = args[2]; } else { System.out.println( "args: user password database"); System.exit(0); } 8/23/2019 BGA

ConnectionTester try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password); conn.close(); } catch (ClassNotFoundException e) {...} catch (SQLException e) {...} System.out.println("Connection success"); } } ConnectionTester.java 8/23/2019 BGA

ConnectionTester Compile the class using Run the class using javac ConnectionTester Run the class using java -cp .;c:\packages ConnectionTester user password web_db Replace user and password with your values Replace web_db with your database 8/23/2019 BGA

Executing a SELECT query First create a Statement object Then create a query string. For example Execute the query The ResultSet object returned contains the results of the query. Statement stmt = conn.createStatement(); String query = "SELECT * FROM table"; ResultSet rs = stmt.executeQuery(query); 8/23/2019 BGA

Getting query results (1) Column names and number of columns. If rs is a ResultSet object then number of columns in table is The name of column i (i=1,2,3,...) is ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); String colName = rsmd.getColumnName(i) 8/23/2019 BGA

Getting query results (2) Iterating over the rows of a table while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { String columnValue = rs.getString(i); // do something with columnValue } } There are lots of get methods for retriving column values as integers, doubles, etc. 8/23/2019 BGA

Executing a simple command First create a Statement object Then create a command string. For example Execute the command Statement stmt = conn.createStatement(); String cmd = "DROP TABLE IF EXISTS test"; stmt.execute(cmd); 8/23/2019 BGA

The Connection interface Two important methods: Statement with no parameters Statement with parameters PreparedStatement is a subinterface of Statement public Statement createStatement() public PreparedStatement prepareStatement() 8/23/2019 BGA

Example Make a connection and create a statement Connection conn = DriverManager.getConnection(url,user,pass); Statement st = conn.createStatement(); 8/23/2019 BGA

The Statement interface Execute a command Execute a query which returns a result set Execute an update, insert, or delete SQL statement Many other methods boolean execute(String sql) ResultSet executeQuery(String sql) int executeUpdate(String sql) 8/23/2019 BGA

Types of statements A Statement object is used to execute a simple SQL statement without parameters A PreparedStatement object is used to execute a precompiled SQL statement with or without IN parameters There are also CallableStatement objects for OUT parameters (uses stored procedures in the database) 8/23/2019 BGA

Dropping a table Dropping a database table Another way Statement dropTable = connection.createStatement( "DROP TABLE IF EXISTS ages"); dropTable.execute(); PreparedStatement dropTable = connection.prepareStatement( "DROP TABLE IF EXISTS ages"); ... dropTable.execute(); 8/23/2019 BGA

Creating a table Creating a database table PreparedStatement createTable = connection.prepareStatement( "CREATE TABLE ages (" + "ID INT(10) NOT NULL AUTO_INCREMEMT, " + "Name VARCHAR(12), " + "Age INT, " + "PRIMARY KEY(ID)" + ")" ); ... createTable.execute(); 8/23/2019 BGA

books database table (1) CREATE DATABASE IF NOT EXISTS web_db; USE web_db; DROP TABLE IF EXISTS books; CREATE TABLE books ( isbn CHAR(15) PRIMARY KEY NOT NULL, title VARCHAR(100) NOT NULL, author VARCHAR(100) NOT NULL, pub VARCHAR(20) NOT NULL, year year NOT NULL, price DECIMAL(9,2) DEFAULT NULL ); 8/23/2019 BGA

books database table (2) INSERT INTO books VALUES ( '0-672-31784-2', 'PHP and MySQL Web Development', 'Luke Welling, Laura Thomson', 'Sams', 2001, 74.95 ); ............ INSERT INTO books VALUES ( '1-56592-243-3', 'Perl Cookbook', 'Tom Christianson, Nathan Torkington', 'O\'Reilly', 1999, 56.95 ); 8/23/2019 BGA

MySQLTester.java import java.sql.*; public class MySQLTester { private String host = "localhost"; private String port = "3306"; public static void main(String[] args) { MySQLTester prog = new MySQLTester(); if (args.length == 4) prog.run(args[0], args[1], args[2], args[3]); else System.out.println( "Args: user password database \"query\""); } See jdbc install notes (html) 8/23/2019 BGA

MySQLTester.java public void run(String user, String password, String database, String query) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Could not find driver"); System.exit(0); } 8/23/2019 BGA

MySQLTester.java try { Connection conn = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password); // Execute a query and get resulting table Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); 8/23/2019 BGA

MySQLTester.java // Get number of columns in table ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); // Simple display of column names for (int i = 1; i <= numberOfColumns, i++) { System.out.print(rsmd.GetColumnName(i)); if (i < numberOfColumns) System.out.print(":"); // separator } System.out.println(); 8/23/2019 BGA

MySQLTester.java // Use ResultSet iterator to display table // columns while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { String columnValue = rs.getString(i); System.out.println(columnValue); if (i < numberOfColumns) System.out.print(":"); } System.out.println(); } 8/23/2019 BGA

MySQLTester.java rs.close(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); System.exit(); } } } MySQLTester.java (see install notes) Compile it and run it using the command java -cp .;c:\package\mysql-jdbc-driver.jar MySQLTester user password web_db "SELECT * FROM books" 8/23/2019 BGA

DBaseTestServlet.java (1) package dbase; import java.io.*; import java.sql.*; import java.servlet.*; import java.servlet.http.*; public class DBaseTestServlet extends HttpServlet { private Connection connection; public void init() throws ServletException { See jdbc install notes (html) DBaseTestServlet.java This servlet is part of the install instructions and is available in the test webapp as dbase.DBaseTestServlet 8/23/2019 BGA

DBaseTestServlet.java (2) try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql"//localhost:3306/web_db", "user", "password"); } catch (ClassNotFoundException e) { ... } catch (SQLException e) { ... } } There is a better way 8/23/2019 BGA

DBaseTestServlet.java (3) public void doGet(HttpServletRequest request, HttpServlet response) throws IOException, ServletException { String name = ""; int age = 0; response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { Statement st = connection.createStatement(): st.execute("DROP TABLE IF EXISTS test"); st.execute( "CREATE TABLE test (" + "name VARCHAR(20) NOT NULL," + "age INTEGER NOT NULL )"); 8/23/2019 BGA

DBaseTestServlet.java (4) st.execute( "INSERT INTO test VALUES ('Fred', 34)"); ResultSet rs = st.executeQuery( "SELECT * FROM test"); result.next(); // only one row name = result.getString("name"); age = result.getInt("age"); st.execute("DROP TABLE test"); } catch (SQLException e) { System.out.println("Error in statement"); } 8/23/2019 BGA

DBaseTestServlet.java (5) out.println("<html>\n" + "<head><title>Testing JDBC</title></head>\n" + "<body>\n" + "The name is " + name + "<br />" + "The age is " + age + "</body>\n" + "</html>\n"); } // end of doGet 8/23/2019 BGA

DBaseTestServlet.java (6) public void destroy() { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end servlet 8/23/2019 BGA

BookDisplayServlet0 (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class BookDisplayServlet0 extends HttpServlet { private Connection connection; private PreparedStatement getBooks; See jdbc install notes (html) This servlet is part of the install instructions and is available in the test webapp as dbase.BookDisplayServlet0 8/23/2019 BGA

BookDisplayServlet0 (2) public void init() throws ServletException { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/bookstore", "user", "password"); the three argument form of the getConnection method 8/23/2019 BGA

BookDisplayServlet0 (3) getBooks = connection.prepareStatement( "SELECT * FROM books"); } catch (Exception e) { e.printStackTrace(); throw new UnavailableException(e.getMessage()); } } // end init method 8/23/2019 BGA

BookDisplayServlet0 (4) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); 8/23/2019 BGA

BookDisplayServlet0 (5) try { ResultSet book = getBooks.executeQuery(); ResultSetMetaData rsmd = book.getMetaData(); int numColumns = rsmd.getColumnCount(); out.println( "<html>\n" + "<head><title>Displaying the books database table</title></head>\n" + "<body>\n" + "<h1>Displaying the books database table</h1>\n" + "<table border=\"1\">"); 8/23/2019 BGA

BookDisplayServlet0 (6) // display column names out.println("<tr>"); for (int col = 1; col <= numColumns; col++) { out.println("<th>" + rsmd.getColumnName(col) + "</th>"); } out.println("</tr>"); 8/23/2019 BGA

BookDisplayServlet0 (7) // Display rows of table while(book.next()) { out.println("<tr>"); for (int col = 1; col <= numColumns;col++) { out.println("<td>" + book.getString(col) + "</td>"); } out.println("</tr>"); } out.println("</table>\n</html>"); out.close(); } // end try 8/23/2019 BGA

BookDisplayServlet0 (8) catch (SQLException e) { e.printStackTrace(); out.println( "<html>\n" + "<head><title>SQL Error</title></head>\n" + "<body>\n" + "<h1>SQL Error</h1>\n" + "<p>A database error occurred</p>" + "</body></html>" ); out.close(); } } // end doGet 8/23/2019 BGA

BookDisplayServlet0 (9) public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end BookDisplayServlet0 8/23/2019 BGA

Using web.xml (1) Constants can be stored here to specify database parameters: <context-param> <param-name>jdbc.driver</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </context-param> <context-param> <param-name>jdbc.url</param-name> <param-value> jdbc:mysql://localhost:3306/web_db </param-value> </context-param> 8/23/2019 BGA

Using web.xml (2) <context-path> <param-name>jdbc.username</param-name> <param-value>uuuuu</param-value> </contex-path> <context-path> <param-name>jdbc.password</param-name> <param-value>ppppp</param-value> </context-path> The next example, SQLTestServlet, shows how to read these values using the ServletContext 8/23/2019 BGA

SQLTestServlet output (1) DROP TABLE IF EXISTS ages; CREATE TABLE ages ( ID INT(10) NOT NULL AUTO_INCREMENT, Name VARCHAR(12), AGE INT, PRIMARY KEY(ID) ); INSERT INTO ages (Name,Age) VALUES (?,?); SELECT * FROM ages 8/23/2019 BGA

SQLTestServlet output (2) DELETE FROM ages WHERE ID < 3 SELECT * FROM ages 8/23/2019 BGA

SQLTestServlet output (3) UPDATE ages SET Age='99' WHERE ID=6 SELECT * FROM ages 8/23/2019 BGA

SQLTestServlet.java (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class SQLTestServlet extends HttpServlet { private Connection connection; private PreparedStatement dropTable; private PreparedStatement createTable; private PreparedStatement insertRow; private PreparedStatement deleteRows; private PreparedStatement updateRow; private String table = "ages"; See the c2206 web app servlet dbase.SQLTestServlet 8/23/2019 BGA

SQLTestServlet.java (2) public void init() throws ServletException { // get database parameters from web.xml ServletContext context = getServletContext(); String driver = context.getInitParameter("jdbc.driver"); String url = context.getInitParameter("jdbc.url"); String user = context.getInitParameter("jdbc.username"); String pass = context.getInitParameter("jdbc.password"); 8/23/2019 BGA

SQLTestServlet.java (3) try { // Load driver and make a connection to the // java_db database Class.forName(driver); connection = DriverManager.getConnection(url, user, pass); 8/23/2019 BGA

SQLTestServlet.java (4) // Define all the SQL commands and queries dropTable = connection.prepareStatement( "DROP TABLE IF EXISTS " + table ); createTable = connection.prepareStatement( "CREATE TABLE " + table + "(" + "ID INT(10) NOT NULL AUTO_INCREMENT, " + "Name VARCHAR(12), " + "Age INT, " + "PRIMARY KEY(ID)" + ")" ); 8/23/2019 BGA

SQLTestServlet.java (5) insertRow = connection.prepareStatement( "INSERT INTO " + table + "(Name, Age)" "VALUES (?,?)" ); deleteRows = connection.prepareStatement( "DELETE FROM " + table + " WHERE ID < 3" ); updateRow = connection.prepareStatement( "UPDATE " + table + " SET Age='99' WHERE ID=6" ); } // end try 8/23/2019 BGA

SQLTestServlet.java (6) catch (Exception e) { e.printStackTrace(); throw new UnavailableException( e.getMessage()); } } // end init 8/23/2019 BGA

SQLTestServlet.java (7) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "<html>\n" + "<head><title>Database operations" + "</title></head>\n" + "<body>\n" ); 8/23/2019 BGA

SQLTestServlet.java (8) try { // create the database table dropTable.execute(); createTable.execute(); // Insert a few rows and display table String[] names = {"Fred", "Gord", "Alice", "Bob", "Barney", "Wilma"}; int[] ages = {37,23,17,23,35,33}; for (int k = 0; k < ages.length; k++) { insertRow.setString(1, names[k]); insertRow.setInt(2, ages[k]); insertRow.executeUpdate(); } 8/23/2019 BGA

SQLTestServlet.java (9) out.println( "<h1>Initial database table</h1>"); displayTable(out); // Delete entries with ID < 3 and display deleteRows.execute(); out.println( "<h1>Table with rows deleted</h1>"); displayTable(out); 8/23/2019 BGA

SQLTestServlet.java (10) // Update a table row updateRow.executeUpdate(); out.println("<h1>After update ...</h1>"); displayTable(out); out.println("<body>\n</html>"); } catch (SQLException e) { e.printStackeTrace(); } } // end doGet 8/23/2019 BGA

SQLTestServlet.java (11) public void displayTable(PrintWriter out) throws SQLException { Statement st = connection.createStatement(); ResultSet result = st.executeQuery("SELECT * FROM " + table); ResultSetMetaData rsmd = result.getMetaData(); int numColumns = rsmd.getColumnCount(); // begin the HTML table out.println( "<table border=\"1\" cellpadding=\"3\">"); 8/23/2019 BGA

SQLTestServlet.java (12) // display column headings out.println("<tr>"); for (int col= 1; col <= numColumns; col++) { out.println("<th>" + rsmd.getColumnName(col) + "</th>"); } out.println("</tr>"); 8/23/2019 BGA

SQLTestServlet.java (13) // display table rows while (result.next()) { out.println("<tr>"); for (int col = 1; col <= numColumns; col++) { out.println("<td>" + result.getString(col) + "</td>"); } out.println("</tr>"); } out.println("</table>"); result.close(); } // end displayTable 8/23/2019 BGA

SQLTestServlet.java (14) public void destroy() { try { connection.close(); dropTable.close(); createTable.close(); insertRow.close(); deleteRows.close(); updateRow.close(); } catch (SQLException e) { e.printStackTrace(); } } // end destroy } // end SQLTestServlet 8/23/2019 BGA

BookDisplayServlet1 The following version uses web.xml to store the database parameters so that they are not "wired-in" to the class. See the c2206 web app servlet dbase.BookDisplayServlet1

BookDisplayServlet1 (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class BookDisplayServlet1 extends HttpServlet { private Connection connection; private PreparedStatement getBooks; 8/23/2019 BGA

BookDisplayServlet1 (2) public void init() throws ServletException { // Get the jdbc connection parameters from the // web.xml file ServletContext context = getServletContext(); String driver = context.getInitParameter("jdbc.driver"); String url = context.getInitParameter("jdbc.url"); String user = context.getInitParameter("jdbc.username"); String pass = context.getInitParameter("jdbc.password"); 8/23/2019 BGA

BookDisplayServlet1 (3) try { Class.forName(driver); connection = DriverManager.getConnection(url,user,pass); getBooks = connection.prepareStatement( "SELECT * FROM books"); } catch (Exception e) { e.printStackTrace(); throw new UnavailableException(e.getMessage()); } } // end init method 8/23/2019 BGA

BookDisplayServlet1 (4) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); 8/23/2019 BGA

BookDisplayServlet1 (5) try { ResultSet book = getBooks.executeQuery(); ResultSetMetaData rsmd = book.getMetaData(); int numColumns = rsmd.getColumnCount(); out.println( "<html>\n" + "<head><title>Displaying the books database table</title></head>\n" + "<body>\n" + "<h1>Displaying the books database table</h1>\n" + "<table border=\"1\">"); 8/23/2019 BGA

BookDisplayServlet1 (6) // display column names out.println("<tr>"); for (int col = 1; col <= numColumns; col++) { out.println("<th>" + rsmd.getColumnName(col) + "</th>"); } out.println("</tr>"); 8/23/2019 BGA

BookDisplayServlet1 (7) // Display rows of table while(book.next()) { out.println("<tr>"); for (int col = 1; col <= numColumns;col++) { out.println("<td>" + book.getString(col) + "</td>"); } out.println("</tr>"); } out.println("</table>\n</html>"); out.close(); } // end try 8/23/2019 BGA

BookDisplayServlet1 (8) catch (SQLException e) { e.printStackTrace(); out.println( "<html>\n" + "<head><title>SQL Error</title></head>\n" + "<body>\n" + "<h1>SQL Error</h1>\n" + "<p>A database error occurred</p>" + "</body></html>" ); out.close(); } } // end doGet 8/23/2019 BGA

BookDisplayServlet1 (9) public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end BookDisplayServlet1 8/23/2019 BGA

Beans version of the Book display servlet

BookDisplayServlet (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import beans.BookBean; import beans.BookDataBean; import beans.DBConnectorBean; public class BookDisplayServlet extends HttpServlet { private BookDataBean bookDataBean; 8/23/2019 BGA

BookDisplayServlet (2) public void init() throws ServletException { // Get the jdbc connection parameters from the // web.xml file ServletContext context = getServletContext(); String driver = context.getInitParameter("jdbc.driver"); String url = context.getInitParameter("jdbc.url"); String user = context.getInitParameter("jdbc.username"); String pass = context.getInitParameter("jdbc.password"); 8/23/2019 BGA

BookDisplayServlet (3) try { DBConnectorBean = new DBConnectorBean(); db.setDriver(driver); db.setUrl(url); db.setUserName(username); db.setPassword(password); // pass connection to the bean bookDataBean = new BookDataBean(); bookDataBean.setConnection(db); } } // end init method 8/23/2019 BGA

BookDisplayServlet (4) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { DecimalFormat cents = new DecimalFormat("0.00"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); 8/23/2019 BGA

BookDisplayServlet (5) out.println( "<html>\n" + "<head><title>...</title></head>\n" + "<body>\n" + "<h1>...</h1>\n" + "<table border=\"1\">" + "<tr>\n" + "<th>ISBN</th\n<th>TITLE</th>\n" + "<th>AUTHOR</th>\n<th>PUB</th>\n" + "<th>YEAR</th?\n<th>PRICE</th>\n" + "</tr>"); 8/23/2019 BGA

BookDisplayServlet (6) Iterator bookListIterator = bookDataBean.getIterator(); BookBean book; while (bookListIterator.hasNext()) { book = (BookBean) bookListIterator.next(); out.println("<tr>\n" + "<td>" + book.getIsbn() + "</td>" + "<td>" + book.getTitle() + "</td>" + "<td>" + book.getAuthor() + "</td>" + "<td>" + book.getPub() + "</td>" + "<td>" + book.getYear() + "</td>" + "<td>" + cents.format(book.getPrice()) + "</td></tr>"); } out.println("</table></body></html>"); } out.close(); 8/23/2019 BGA

BookDisplayServlet (7) public void destroy() { bookDataBean.destroy(); } } // end of servlet 8/23/2019 BGA

BookBean (1) package beans; public class BookBean implements java.io.Serializable { // instance datafields are called properties private String isbn, title, author, pub, year; private double price; public String getIsbn() { return isbn; } public String getTitle() { return title; } public String getAuthor() { return author; } public String getPub() { return pub; } public String getYear() { return year; } public double getPrice() { return price; } 8/23/2019 BGA

BookBean (2) public void setIsbn(String isbn) { this.isbn = isbn; } public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } public void setPub(String pub) { this.pub = pub; } public void setYear(String year) { this.year = year; } public void setPrice(double price) { this.price = price; } } 8/23/2019 BGA

DBConnectorBean (1) package beans; import java.sql.*; public class DBConnectorBean implements java.io.Serializable { private String theUrl; private String theUsername; private String thePassword; public void setDriver(String driver) { try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } 8/23/2019 BGA

DBConnectorBean (2) public void setUrl(String url) { theUrl = url; } public void setUsername(String username) { theUsername = username; } public void setPassword(String password) { thePassword = password; } public Connection getConnection() { Connection conn = null; try { con = DriverManager.getConnection( theUrl, theUserName, thePassword); return null; } catch (SQLException e) {e.printStackTrace();} return null; } } 8/23/2019 BGA

BookDataBean (1) package beans; import java.sql.*; import java.util.*: import beans.BookBean; public class BookDataBean implements java.io.Serializable { private Connection connection; private PreparedStatement getBooks; public void setDatabase(DBConnectorBean db) { connection = db.getConnection(); } 8/23/2019 BGA

BookDataBean (2) public Iterator getIterator() { List bookList = new ArrayList(); try { getBooks = connection.preparedStatement( "SELECT * FROM books"); resultSet results = getBooks.executeQuery(); while (results.next()) { BookBean book = new BookBean(); book.setIsbn(results.getString(1)); book.setTitle(results.getString(2)); book.setAuthor(results.getString(3)); book.setPub(results.getString(4)); 8/23/2019 BGA

BookDataBean (3) book.setYear(results.getString(5)); book.setPrice(results.getDouble(6)); bookList.add(book); } } catch (SQLException e) { System.out.println("SQL query failed"); } return bookList.iterator(); } 8/23/2019 BGA

BookDataBean (4) public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end BookDataBean 8/23/2019 BGA