Week 7 JSP’s and Scope A Shopping cart application using JSP and JavaBeans A Simple JSP/JDBC Example A JSP/JDBC Example using connection pooling Much of.

Slides:



Advertisements
Similar presentations
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Advertisements

19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
Java/JDBC Some Database terminology (brief) A simple stand alone JDBC Application Java Server Pages and Scoping A simple JSP and JDBC example JSP and JDBC.
Object Oriented Programming Java Java’s JDBC Allows access to any ANSI SQL-2 DBMS Does its work in terms of SQL The JDBC has classes that represent:
Week 6 JSP’s and JavaBean Page Scope JSP’s and JavaBean Request Scope
Internet Technologies1 JSP and JDBC JSP’s and Scope A Shopping cart application using JSP and JavaBeans A Simple JSP/JDBC Example A JSP/JDBC Example using.
DT228/3 Web Development Databases. Database Almost all web application on the net access a database e.g. shopping sites, message boards, search engines.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
ECE356 – Database Systems Lab 1 – Building a Web Project with NetBeans Tiuley Alguindigue Lab Instructor – University of Waterloo, E & CE Dept. Fall 2013.
ODBC and JDBC What are they – libraries of function calls that support SQL statements Why do we need them –Provide a way for an application to communicate.
TUTORIAL (1) Software installation Written by: Eng. Ahmed Mohamed Abdel Ghafar, Edited by Eng. Muhammed Hammad, Eng. Hamdy Soltan & Eng. Osama Talaat.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
CST JavaScript Validating Form Data with JavaScript.
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Component-Based Software Engineering Internet Applications Paul Krause.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Jaeki Song JAVA Lecture 11 Java Database Connectivity.
Examples of Using Servlets and JSP Representation and Management of Data on the Internet.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Java Servlets and Java Server Pages Carol Wolf Computer Science.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
Georgia Institute of Technology Making Text for the Web part 5 Barb Ericson Georgia Institute of Technology March 2006.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 32.1 Reviewing the Bookstore Application 32.2.
Java Servlets & Java Server Pages Lecture July 2013.
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.
Chapter 8 Databases.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
PHP. $_GET / $_POST / $_SESSION PHP uses predefined variables to provide access to important information about the server and requests from a browser.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
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.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
EXAMPLE I An application showing JDBC access to Cloudscape.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Vakgroep Informatietechnologie – Onderzoeksgroep (naam) Web Centric Design of Distributed Software.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Web Programming Assistant Professor Xiaozhong Liu
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.
Database Processing with JSP ISYS 350. Database Applications Applications Database Server Queries/Updates Results.
A Presentation Presentation On JSP On JSP & Online Shopping Cart Online Shopping Cart.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
Lec - 14.
JDBC Database Management Database connectivity
HW#4 Making Simple BBS Using JDBC
Super Market Management
Lecture 11 Database Connection
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Week 7 JSP’s and Scope A Shopping cart application using JSP and JavaBeans A Simple JSP/JDBC Example A JSP/JDBC Example using connection pooling Much of this lecture is from a nice little book entitled “Pure JSP” by Goodwill published by SAMS

Page Scope Beans with page scope are accessible only within the page where they were created. A bean with page-level scope is not persistent between requests or outside the page

Page Scope Example /* A simple bean that counts visits. */ import java.io.*; public class Counter implements Serializable { private int count = 1; public Counter() {} public int getCount() { return count++; } public void setCount(int c) { count = c; } }

Under Tomcat webapps myApplication WEB-INF classesweb.xml Counter.java SomeFile.jsp

<%-- The Counter class must be imported. Its in the WEB-INF/classes directory --%> Page Bean Example Page Bean Example The current count for the counter bean is:

The count never changes.

One Page May Call Another Caller page Caller page Any response data is cleared and control passes to the new page.

Callee.jsp Callee page Callee page

After Visiting Caller.jsp

Request Scope One page may call another and the bean is still available. Its considered one request. The second page will use an existing bean before creating a new one. When the current request is complete the bean is reclaimed by the JVM.

Request Scope Caller.jsp Caller page Caller page

Request Scope Callee.jsp Callee page Callee page

After Visiting Caller.jsp

Session Scope Beans with session scope are accessible within pages processing requests that are in the same session as the one in which the bean was created. Session lifetime is typically configurable and is controlled by the servlet container. Currently, my session ends when the browser exits. Multiple copies of the same browser each get their own session bean.

Session Scope Example Session Bean Page Session Bean Page Visit number

Session Scope Example The counter increments on each hit till browser exits. New browser back to 1.

Application Beans A bean with a scope value of application has an even broader and further reaching availability than session beans. Application beans exist throughout the life of the JSP container itself, meaning they are not reclaimed until the server is shut down. Session beans are available on subsequent requests from the same browser. Application beans are shared by all users.

Application Bean Example 1 Application Bean Page Application Bean Page Visit number <jsp:getProperty name = "ctr“ property = "count"/>

Application Bean Example 2 Application Bean Page Two Application Bean Page Two Visit number <jsp:getProperty name = "ctr“ property = "count"/>

After several visits with IE5 we visit with Netscape.

After visiting from a different machines with a different browsers, we still keep count.

A Shopping Cart AddToShoppingCart.jsp

ShoppingCart.jsp

The Bean – ShoppingCart.java // Adapted from From James Goodwill Pure JSP // ShopingCart.java import java.util.*; public class ShoppingCart implements Serializable { protected Hashtable items = new Hashtable(); public ShoppingCart() {}

public void addItem(String itemId, String description, float price, int quantity) { // pack the item as an array of Strings String item[] = { itemId, description, Float.toString(price), Integer.toString(quantity)}; // if item not yet in table then add it if(! items.containsKey(itemId)) { items.put(itemId, item); } else { // the item is in the table already String tempItem[] = (String[])items.get(itemId); int tempQuant = Integer.parseInt(tempItem[3]); quantity += tempQuant; tempItem[3] = Integer.toString(quantity); } } Get a reference to a hashtable entry. Change it.

public void removeItem(String itemId) { if(items.containsKey(itemId)) { items.remove(itemId); } public void updateQuantity(String itemId, int quantity) { if(items.containsKey(itemId)) { String[] tempItem = (String[]) items.get(itemId); tempItem[3] = Integer.toString(quantity); } public Enumeration getEnumeration() { return items.elements(); }

public float getCost() { Enumeration enum = items.elements(); String[] tempItem; float totalCost = 0.00f; while(enum.hasMoreElements()) { tempItem = (String[]) enum.nextElement(); totalCost += (Integer.parseInt(tempItem[3]) * Float.parseFloat(tempItem[2])); } return totalCost; }

public int getNumOfItems() { Enumeration enum = items.elements(); String tempItem[]; int numOfItems = 0; while(enum.hasMoreElements()) { tempItem = (String[]) enum.nextElement(); numOfItems += Integer.parseInt(tempItem[3]); } return numOfItems; }

public static void main(String a[]) { ShoppingCart cart = new ShoppingCart(); cart.addItem("A123", "Bike", (float)432.46, 10); cart.addItem("A124", "Bike", (float)732.46, 5); System.out.println(cart.getNumOfItems()); System.out.println(cart.getCost()); cart.updateQuantity("A123", 2); System.out.println(cart.getNumOfItems()); cart.addItem("A123", "Bike", (float)432.46, 4); System.out.println(cart.getNumOfItems()); } D:\Apache Tomcat 4.0\webapps\myjsp\WEB-INF\classes>java ShoppingCart

AddToShoppingCart.jsp <jsp:useBean id = "cart" scope = "session" class = "ShoppingCart" /> DVD Catalog

<% String id = request.getParameter("id"); if(id != null) { String desc = request.getParameter("desc"); Float price = new Float(request.getParameter("price")); cart.addItem(id, desc, price.floatValue(), 1); } %> JSP uses java as the scripting language. Think of this code as being a part of the resulting servlet. We have access to the request object. Add an item to the bean. It will be null on the first visit.

Shopping Cart Quantity DVD Catalog <table border = "1" width = "300“ cellspacing = "0" cellpadding = "2" align = "center" > Description Price This is a JSP expression. It’s evaluated and sent to the response object. It will change every time The servlet is hit within this session.

Happy Gilmore $19.95 If this form is clicked we execute this same servlet but pass back the hidden form fields.

Brassed Off Full Monty $23.99 <input type = "hidden" name = "desc" value = "Brassed Off Full Monty" > Hidden data going back to the server.

FlashDance $12.95 <input type = "hidden" name = "desc" value = "FlashDance" >

ShoppingCart.jsp We have access to the same bean.

Shopping Cart Contents <table width = "300" border = "1" cellspacing = "0" cellpadding = "2" border = "0" > Shopping Cart Contents Description Price Quantity

<% Enumeration enum = cart.getEnumeration(); String tempItem[]; while(enum.hasMoreElements()) { tempItem = (String[]) enum.nextElement(); %> This loop executes within the servlet. Notice that the loop has not ended but we are done with java for the moment…

Back to Catalog We start generating html to the response object (in the loop). End of loop. Java code is Enclosed within the

A Simple JSP/JDBC Example stocks.mdb database schema There are three tables. Both customer and stocks have a one- to-many relationship with portfolios. The database stocks.mdb was registered with the ODBC driver as “CoolStocks”

Register w/ODBC Create an ODBC data source. Click on the Start button. Choose Settings, Control Panel Double-click on ODBC Data Sources Choose the System DSN tab Click Add Click on the desired driver (MSAccess) Click on the Finish button Enter a Data Source Name (I called my database CoolStocks and that name appears in the java code below) Click on the Select button Locate the directory and file containing your database. This will be the “stock.mdb” file created by Microsoft Access. Click OK

A Simple JSP/JDBC Example JSP JDBC Example 1 <!– Adapted from James Goodwill’s Pure JSP 

<% Connection con = null; try { // Load the Driver class file Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Make a connection to the ODBC datasource Movie Catalog con = DriverManager.getConnection("jdbc:odbc:CoolStocks"); // Create the statement Statement statement = con.createStatement(); // Use the created statement to SELECT the DATA // FROM the customer Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM customer"); // Iterate over the ResultSet %>

Customer - ID Last Name First Name <% while ( rs.next() ) { // get the id, convert to String out.println(" \n " + rs.getString("id") + " "); // get the last name out.println(" " + rs.getString("lname") + " "); // get the first name out.println(" " + rs.getString("fname") + " \n</TR"); }

// Close the ResultSet rs.close(); } catch (IOException ioe) { out.println(ioe.getMessage()); } catch (SQLException sqle) { out.println(sqle.getMessage()); } catch (ClassNotFoundException cnfe) { out.println(cnfe.getMessage()); } catch (Exception e) { out.println(e.getMessage()); }

finally { try { if ( con != null ) { // Close the connection no matter what con.close(); } catch (SQLException sqle) { out.println(sqle.getMessage()); } %>

It Works!

An Example Using Connection Pooling The example above opens a connection every time there is a visit. Goodwill presents another approach in chapter 14.

PooledConnection.java // Adapted from Goodwill's Pure JSP import java.sql.*; public class PooledConnection { // Real JDBC Connection private Connection connection = null; // boolean flag used to determine if connection is in use private boolean inuse = false;

// Constructor that takes the passed in JDBC Connection // and stores it in the connection attribute. public PooledConnection(Connection value) { if ( value != null ) { connection = value; } // Returns a reference to the JDBC Connection public Connection getConnection() { return connection; }

// Set the status of the PooledConnection. public void setInUse(boolean value) { inuse = value; } // Returns the current status of the PooledConnection. public boolean inUse() { return inuse; } // Close the real JDBC Connection public void close() { try { connection.close(); } catch (SQLException sqle) { System.err.println(sqle.getMessage()); }

ConnectionPool.java // Adapted from James Goodwill's Pure Java import java.sql.*; import java.util.*; public class ConnectionPool { // JDBC Driver Name private String driver = null; // URL of database private String url = null; // Initial number of connections. private int size = 0;

// Username private String username = new String(""); // Password private String password = new String(""); // Vector of JDBC Connections private Vector pool = null; public ConnectionPool() { } // Set the value of the JDBC Driver public void setDriver(String value) { if ( value != null ) { driver = value; }

// Get the value of the JDBC Driver public String getDriver() { return driver; } // Set the URL Pointing to the Datasource public void setURL(String value ) { if ( value != null ) { url = value; } // Get the URL Pointing to the Datasource public String getURL() { return url; }

// Set the initial number of connections public void setSize(int value) { if ( value > 1 ) { size = value; } // Get the initial number of connections public int getSize() { return size; } // Set the username public void setUsername(String value) { if ( value != null ) { username = value; }

// Get the username public String getUserName() { return username; } // Set the password public void setPassword(String value) { if ( value != null ) { password = value; } // Get the password public String getPassword() { return password; }

// Creates and returns a connection private Connection createConnection() throws Exception { Connection con = null; // Create a Connection con = DriverManager.getConnection(url, username, password); return con; }

// Initialize the pool public synchronized void initializePool() throws Exception { // Check our initial values if ( driver == null ) { throw new Exception("No Driver Name Specified!"); } if ( url == null ) { throw new Exception("No URL Specified!"); } if ( size < 1 ) { throw new Exception("Pool size is less than 1!"); }

// Create the Connections try { // Load the Driver class file Class.forName(driver); // Create Connections based on the size member for ( int x = 0; x < size; x++ ) { Connection con = createConnection(); if ( con != null ) { // Create a PooledConnection to encapsulate the // real JDBC Connection PooledConnection pcon = new PooledConnection(con); // Add the Connection to the pool. addConnection(pcon); }

catch (Exception e) { System.err.println(e.getMessage()); throw new Exception(e.getMessage()); } // Adds the PooledConnection to the pool private void addConnection(PooledConnection value) { // If the pool is null, create a new vector // with the initial size of "size" if ( pool == null ) { pool = new Vector(size); } // Add the PooledConnection Object to the vector pool.addElement(value); }

public synchronized void releaseConnection(Connection con) { // find the PooledConnection Object for ( int x = 0; x < pool.size(); x++ ) { PooledConnection pcon = (PooledConnection)pool.elementAt(x); // Check for correct Connection if ( pcon.getConnection() == con ) { System.err.println("Releasing Connection " + x); // Set its inuse attribute to false, which // releases it for use pcon.setInUse(false); break; }

// Find an available connection public synchronized Connection getConnection() throws Exception { PooledConnection pcon = null; // find a connection not in use for ( int x = 0; x < pool.size(); x++ ) { pcon = (PooledConnection)pool.elementAt(x); // Check to see if the Connection is in use if ( pcon.inUse() == false ) { // Mark it as in use pcon.setInUse(true); // return the JDBC Connection stored in the // PooledConnection object return pcon.getConnection(); }

// Could not find a free connection socreate and add a new one try { // Create a new JDBC Connection Connection con = createConnection(); // Create a new PooledConnection, passing it the JDBC Connection pcon = new PooledConnection(con); // Mark the connection as in use pcon.setInUse(true); // Add the new PooledConnection object to the pool pool.addElement(pcon); } catch (Exception e) { System.err.println(e.getMessage()); throw new Exception(e.getMessage()); } // return the new Connection return pcon.getConnection(); }

// When shutting down the pool, you need to first empty it. public synchronized void emptyPool() { // Iterate over the entire pool closing the // JDBC Connections. for ( int x = 0; x < pool.size(); x++ ) { System.err.println("Closing JDBC Connection " + x); PooledConnection pcon = (PooledConnection)pool.elementAt(x); // If the PooledConnection is not in use, close it if ( pcon.inUse() == false ) { pcon.close(); }

else { // If it is still in use, sleep for 30 seconds and // force close. try { java.lang.Thread.sleep(30000); pcon.close(); } catch (InterruptedException ie) { System.err.println(ie.getMessage()); }

JDBCPooledExample.jsp <jsp:useBean id="pool" scope="application" class="ConnectionPool" />

<% Connection con = null; try { // The pool is not initialized if ( pool.getDriver() == null ) { // initialize the pool pool.setDriver("sun.jdbc.odbc.JdbcOdbcDriver"); pool.setURL("jdbc:odbc:CoolStocks"); pool.setSize(5); pool.initializePool(); } // Get a connection from the ConnectionPool con = pool.getConnection(); // Create the statement Statement statement = con.createStatement();

// Use the created statement to SELECT the DATA // FROM the customer Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM customer"); // Iterate over the ResultSet %> Customer - ID Last Name First Name

<% while ( rs.next() ) { // get the id, convert to String out.println(" \n " + rs.getString("id") + " "); // get the last name out.println(" " + rs.getString("lname") + " "); // get the first name out.println(" " + rs.getString("fname") + " \n</TR"); } // Close the ResultSet rs.close(); out.println(" "); } catch (IOException ioe) { out.println(ioe.getMessage()); }

catch (SQLException sqle) { out.println(sqle.getMessage()); } catch (ClassNotFoundException cnfe) { out.println(cnfe.getMessage()); } catch (Exception e) { out.println(e.getMessage()); } finally { try { if ( con != null ) { // release the connection no matter what pool.releaseConnection(con); }

catch (Exception e) { out.println(e.getMessage()); } %>

It works too!

Summary Connections take a long time to open. Transactions are linked to connections and should not normally be shared. If you have a very low traffic site then you might open and close the connection inside the servlet’s doxxx() method. Perhaps the best approach is to use connection pooling with different roles assigned to different connections. Each visitor has their own connection with an established role. The connections are only created during server startup.