1 Databases & Web-based Applications JDBC & Java Servlets A. Benabdelkader ©UvA, 2002/2003.

Slides:



Advertisements
Similar presentations
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Advertisements

Java Servlets Java Server Pages (JSP)
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/
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.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Java database Programming JDBC Trademarked name of a Java API that supports Java programs that access relational databases Stand for Java DataBase Connectivity.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
1 Servlets and HTML Form Data Parts of this presentation was provided by Vijayan Sugumaran Department of DIS Oakland University Rochester,
Server Side Programming Web Information Systems 2012.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
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 support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Java Servlets and Java Server Pages Carol Wolf Computer Science.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
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.
Java Servlets & Java Server Pages Lecture July 2013.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling the Client Request: Form Data Core Servlets & JSP book:
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
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.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
Java Servlets and Java Server Pages Norman White Stern School of Business.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
 2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
Java Servlets and Java Server Pages
How CGI and Java Servlets are Run By David Stein 14 November 2006.
1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 8: Applications Programming for Relational Databases Instructor’s.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Distributed Web Systems Java Servlets Lecturer Department University.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
JDBC & Servlet CSE 4504/6504 Lab.
CS320 Web and Internet Programming Database Access with JDBC
Servlet.
Chapter 26 Servlets.
Servlets and Java Server Pages
Web Search Interfaces.
Java Servlets Servlet Overview Servlets and HTML Forms Servlet Basics
Basic servlet structure
Presentation transcript:

1 Databases & Web-based Applications JDBC & Java Servlets A. Benabdelkader ©UvA, 2002/2003

2 JDBC

3 JDBC Java Database Connectivity - JDBC n Modeled after ODBC, JDBC API supports basic SQL functionality n With JDBC, Java can be used as host language for writing database applications n On top of JDBC, higher-level APIs can be built n Currently, two types of higher-level APIs: q An embedded SQL for Java (eg. SQLJ) q A direct mapping of relational database tables to Java classes (eg. Java Blend from Sun) Connolly © Addison Wesley, 2002

4 JDBC n JDBC API consists of two main interfaces: an API for application writers, and a lower-level driver API for driver writers n Applications and applets can access databases using: q ODBC drivers and existing database client libraries q JDBC API with pure Java JDBC drivers Connolly © Addison Wesley, 2002

5 JDBC Connolly © Addison Wesley, 2002

6 JDBC - Advantages/Disadvantages n Advantage of using JDBC drivers is that they are a de facto standard for PC database access, and are available for many DBMSs, for very low price n Disadvantages with this approach: q Non-pure JDBC driver will not necessarily work with a Web browser q Currently downloaded applet can connect only to database located on host machine q Deployment costs increase Connolly © Addison Wesley, 2002

7 java.sql Package JDBC - java.sql Package q Driver : supports the creation of a data connection q Connection : represents the connection between a Java client and an SQL database server q DatabaseMetaData : contains information about the database server q Statement : includes methods for executing SQL queries q PreparedStatement : represents a pre-compiled and stored query q CallableStatement : used to execute SQL stored procedures q ResultSet : contains the results of the execution of a select query q ResultSetMetaData, contains information about a ResultSet, including the attribute names and types A. Benabdelkader ©UvA, 2002/2003

8 JDBC - Connecting to Databases n java.sql.Driver q no methods for users q DriverManager.Connect method create connection n java.sql.Connection q createStatement n java.sql.Statement q executeQuery returns table as ResultSet q executeUpdate returns integer update count A. Benabdelkader ©UvA, 2002/2003

9 Connections JDBC - Connections n Loading driver classes q Class.forName("myDriver.ClassName"); u Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); n Database connection URL q jdbc: : u jdbc:odbc:mydatabase q subname example  //hostname:port/databasename u //enp01.enp.fsu.edu:3306/gsim n Database MetaData q DatabaseMetaData dma = con.getMetaData(); A. Benabdelkader ©UvA, 2002/2003

10 Connection JDBC Examples - Connection import java.sql.*; public class JDBC_Connection { public static void main(String args[]) { String url = "jdbc:mt://amelie.wins.uva.nl/QueryDemo"; try { Class.forName("com.matisse.sql.MtDriver"); } catch(java.lang.ClassNotFoundException e) { System.err.println(e.getMessage());} try { Connection con = DriverManager.getConnection(url); DatabaseMetaData dma = con.getMetaData(); // Get information about the connection System.out.println("\nConnected to : " + dma.getURL() + "\nDriver : " + dma.getDriverName() + "\nVersion : " + dma.getDriverVersion()); } con.close(); } catch(SQLException ex) {System.err.println(ex.getMessage());} } A. Benabdelkader ©UvA, 2002/2003

11 Meta Data JDBC Examples - Meta Data ….. String query = “Select ….” Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsmd = rs.getMetaData (); int numCols = rsmd.getColumnCount (); for (i=1; (i<=numCols); i++) { System.out.println("\n” + “Column Name: " + rsmd.getColumnLabel(i) + ”Type: " + rsmd.getColumnType(i)); } A. Benabdelkader ©UvA, 2002 /2003

12 Execute Query JDBC Examples - Execute Query public class SQLStatement { try { // make the connection …... Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); While (rs.next()) { For (int i = 1; i <= numCols; i++) { System.out.print(“Column “+ i + ": "); System.out.println(rs.getString(i)); } } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(ex.getMessage());} } A. Benabdelkader ©UvA, 2002 /2003

13 Update Statements JDBC - Update Statements n Create new Objects String insertSQL = ”insert into Course (Code, Name) ” +”values (’Brown’,’Web Databases’)”; int rowcount = stmt.executeUpdate(insertSQL); if (rowcount == 0) // insert failed n Update Objects String updateSQL = “update Course set “ +”Course.Credit = 7 where Code =’BI301004’”; int count = stmt.execute(updateSQL); // count is number of rows affected A. Benabdelkader ©UvA, 2002 /2003

14 Executing unknown SQL JDBC - Executing unknown SQL n Arbitrary SQL may return table (ResultSet) or row count (int) n Statement.execute method stmt.execute(sqlStatement); result = stmt.getResultSet(); while (true) {// loop through all results if (result != null) // process result else {// result is not a ResultSet rowcount = stmt.getUpdateCount(); if (rowcount == -1) break // no more results else // process row count } result = stmt.getMoreResults()) } A. Benabdelkader ©UvA, 2002/2003

15 Universal Database Discovery JDBC - Universal Database Discovery n Get DB MetaData - Get DB Tables DatabaseMetaData dmd; try {dmd = con.getMetaData(); try { String tables[] = {"TABLE", "VIEW"}; results = dmd.getTables("", "", "", tables); } catch (SQLException e){out.println(e);} } catch (Exception e) {out.println(e);} // GET ALL RESULTS A. Benabdelkader ©UvA, 2002/2003

16 Universal Database Discovery JDBC - Universal Database Discovery n Get Tables Results try { ResultSetMetaData rsmd = results.getMetaData(); int numCols = rsmd.getColumnCount(); while (results.next()) { System.out.println("Table Name: " + results.getString("TABLE_NAME")); } results.close(); con.close(); } catch (Exception e) { out.println(e); } A. Benabdelkader ©UvA, 2002/2003

17 Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com Java Servlets

18 Outline Java servlets Advantages of servlets Servlet structure Servlet examples Handling the client request –Form Data –HTTP request headers

19 A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client (status codes and response headers)

20 Why Build Web Pages Dynamically? The Web page is based on data submitted by the user –E.g., results page from search engines and order- confirmation pages at on-line stores The Web page is derived from data that changes frequently –E.g., a weather report or news headlines page The Web page uses information from databases or other server-side sources –E.g., an e-commerce site could use a servlet to build a Web page that lists the current price and availability of each item that is for sale.

21 The Advantages of Servlets Over “Traditional” CGI Efficient –Threads instead of OS processes, one servlet copy, persistence Convenient –Lots of high-level utilities Powerful –Sharing data, pooling, persistence Portable –Run on virtually all operating systems and servers Secure –No shell escapes, no buffer overflows Inexpensive –There are plenty of free and low-cost servers.

22 Simple Servlet Template import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g. cookies) and HTML form data (query data) // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to browser }

23 A Simple Servlet That Generates Plain Text import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); }

24 A Servlet That Generates HTML public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + " \n" + " Hello WWW \n" + " \n" + " Hello WWW \n" + " "); }

25 The Servlet Life Cycle init –Executed once when the servlet is first loaded. Not called for each request. service –Called in a new thread by server for each request. Dispatches to doGet, doPost, etc. Do not override this method! doGet, doPost, doXxx –Handles GET, POST, etc. requests. –Override these to provide desired behavior. destroy –Called when server deletes servlet instance. Not called after each request.

26 Handling the Client Request: Form Data Form data Processing form data Reading request parameters Filtering HTML-specific characters

27 The Role of Form Data Example URL at online travel agent – –Names come from HTML author; values usually come from end user Parsing form (query) data in traditional CGI –Read the data one way (QUERY_STRING) for GET requests, another way (standard input) for POST requests –Chop pairs at ampersands, then separate parameter names (left of the equal signs) from parameter values (right of the equal signs) –URL decode values (e.g., "%7E" becomes "~") –Need special cases for omitted values (param1=val1&param2=&param3=val3) and repeated parameters (param1=val1&param2=val2&param1=val3)

28 Creating Form Data: HTML Forms A Sample Form Using GET A Sample Form Using GET First name: Last name: See CSAJSP Chapter 16 for details on forms

29 HTML Form: Initial Result

30 Reading Form Data In Servlets request.getParameter("name") –Returns URL-decoded value of first occurrence of name in query string –Works identically for GET and POST requests –Returns null if no such parameter is in query request.getParameterValues("name") –Returns an array of the URL-decoded values of all occurrences of name in query string –Returns a one-element array if param not repeated –Returns null if no such parameter is in query request.getParameterNames() –Returns Enumeration of request params

31 An HTML Form With Three Parameters First Parameter: Second Parameter: Third Parameter:

32 Reading the Three Parameters public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters"; out.println(ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " \n" + " param1 : " + request.getParameter("param1") + "\n" + " param2 : " + request.getParameter("param2") + "\n" + " param3 : " + request.getParameter("param3") + "\n" + " \n" + " "); }}

33 Reading Three Parameters: Result

34 Filtering Strings for HTML-Specific Characters You cannot safely insert arbitrary strings into servlet output – can cause problems anywhere –& and " can cause problems inside of HTML attributes You sometimes cannot manually translate –The string is derived from a program excerpt or another source where it is already in some standard format –The string is derived from HTML form data Failing to filter special characters from form data makes you vulnerable to cross-site scripting attack – –