Web Application Deployment & JDBC CSC 667, Spring 2007 Dr. Ilmi Yoon.

Slides:



Advertisements
Similar presentations
Advanced Java Server Pages An more detailed look at JSPs.
Advertisements

 Pearson Education, Inc. All rights reserved Accessing Databases with JDBC.
Distributed Application Development B. Ramamurthy.
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.
Java database Programming JDBC Trademarked name of a Java API that supports Java programs that access relational databases Stand for Java DataBase Connectivity.
Web Application Deployment & JDBC CSC 667, Spring 2004 Dr. Ilmi Yoon.
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.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
CSCI 6962: Server-side Design and Programming
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
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.
CSE470 Software Engineering Fall Database Access through Java.
Intro to JDBC To effectively use Java Data Base Connectivity we must understand: 1.Relational Database Management Systems (RDBMS) 2.JDBC Drivers 3.SQL.
Database Programming in Java Corresponds with Chapter 32, 33.
CHAPTER 7 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
 2003 Prentice Hall, Inc. All rights reserved. 1 Java Database Connectivity with JDBC TM.
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
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.
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.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
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,
CHAPTER 8 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 MySQL and JDBC.
Designing and Developing WS B. Ramamurthy. Plans We will examine the resources available for development of JAX-WS based web services. We need an IDE,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
Database: SQL and MySQL
 2004 Prentice Hall, Inc. All rights reserved. 1 Segment – 6 Web Server & database.
1 JSP with Custom Tags Blake Adams Introduction Advanced Java Server Pages – Custom Tags Keyterms: - Tag Library Descriptor(TLD) - Tag Libraries.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 32.1 Reviewing the Bookstore Application 32.2.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
COMP 321 Week 11. Overview Lab 8-1 Solution Tag Files Custom Tags Web Application Deployment.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
Chapter 8 Databases.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 31.1 Reviewing the Bookstore Application 31.2.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
JSP Custom Tags. Prerequisites Servlet API Mapping to JSP implicit objects JavaServer Pages Basic syntax Implementation via servlet API XML.
 2005 Pearson Education, Inc. All rights reserved Accessing Databases with JDBC.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
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:
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 22 - SQL, MySQL, DBI and ADO Outline 22.1 Introduction 22.2 Relational Database Model 22.3 Relational.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
Basics of JDBC Session 14.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
Web Programming Assistant Professor Xiaozhong Liu
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
17 Copyright © 2004, Oracle. All rights reserved. Integrating J2EE Components.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
ORDER BY Clause The result of a query can be sorted in ascending or descending order using the optional ORDER BY clause. The simplest form of.
Chapter 5 Introduction to SQL.
 2012 Pearson Education, Inc. All rights reserved.
JDBC.
Knowledge Byte In this section, you will learn about:
Pre-assessment Questions
Chapter 22 - SQL, MySQL, DBI and ADO
Presentation transcript:

Web Application Deployment & JDBC CSC 667, Spring 2007 Dr. Ilmi Yoon

Web Application With the release of the Java Servlet Specification 2.2 Web Application is a collection of servlets, html pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors Each web application has one and only one ServletContext doc/appdev/index.htmlhttp://tomcat.apache.org/tomcat-5.5- doc/appdev/index.html 3/15/tomcat.htmlhttp:// 3/15/tomcat.html 4/19/tomcat.htmlhttp:// 4/19/tomcat.html

Deployment Deployment descriptor (web.xml) Web applications can be changed without stopping the server With a standardized deployment comes standardized tools Check 24/667_files/frame.htm for tips for Ant, TogetherSoft, Tomcat install & deployment 24/667_files/frame.htm

Installation & Setup You may avoid these steps by installing ant & eclipse Update CLASSPATH –Identify the Classes (jsp.jar, jspengine.jar, servlet.jar, jasper.jar) or J2EE.jar to the java Compiler –Unix CLASSPATH=${TOMCAT_HOME}/webserver.jar CLASSPATH=${CLASSPATH}:${TOMCAT_HOME}/webserver.jar CLASSPATH=${CLASSPATH}:${TOMCAT_HOME}/lib/servlet/jar CLASSPATH=${CLASSPATH}:${TOMCAT_HOME}/lib/jsper.jar CLASSPATH=${CLASSPATH}:${TOMCAT_HOME}/examples/WEB-INF/classes –Windows set CLASSPATH=.;dir\servlet.jar;dir\jspengine.jar

Packing the Web Application Web ARchive file (WAR) Command : jar cvf onjava.war. Now you can deploy your web application by simply distributing this file

JSP Tag Library In JavaServer Pages technology, actions are elements that can create and access programming language objects and affect the output stream. The JSP specification defines 6 standard actions that must be provided by any compliant JSP implementation. In addition to the standard actions, JSP v1.1 technology supports the development of reusable modules called custom actions. A custom action is invoked by using a custom tag in a JSP page. A tag library is a collection of custom tags. Before the availability of custom actions, JavaBeans components in conjunction with scriplets were the main mechanism for performing such processing. The disadvantage of using this approach is that it makes JSP pages more complex and difficult to maintain. Custom actions alleviate this problem by bringing the benefits of another level of componentization to JSP pages.

What JSP Tags can do? They can be customized via attributes passed from the calling page. They have access to all the objects available to JSP pages. They can modify the response generated by the calling page. They can communicate with each other. You can create and initialize a JavaBeans component, create a variable that refers to that bean in one tag, and then use the bean in another tag. They can be nested within one another, allowing for complex interactions within a JSP page.

JSP demo JSP 1.2 tags – JSTL (JSP Standard Tag Libraries) JSP 2.0 tags – JSTL like Tags Types of Tags –Simple TagsSimple Tags –Tags With AttributesTags With Attributes –Tags With a BodyTags With a Body Usages of Tags –Choosing Between Passing Information as Attributes or BodyChoosing Between Passing Information as Attributes or Body –Tags That Define Scripting VariablesTags That Define Scripting Variables –Cooperating TagsCooperating Tags

Types of Tags –Simple TagsSimple Tags –Tags With AttributesTags With Attributes " /> –Tags With a BodyTags With a Body –Usages of tags Tags That Define Scripting Variables – Cooperating Tags –

Defining Tags Develop a tag handler and helper classes for the tag Declare the tag in a tag library descriptor (.tld) - The tag library's version - The JSP specification version the tag library depends on - A simple default name that could be used by a JSP page authoring tool to create names with a mnemonic value; for example, shortname may be used as the preferred prefix value in taglib directives and/or to create prefixes for IDs. - A URI that uniquely identifies the tag library - Descriptive information about the tag library classname …...

How is a Tag Handler Invoked? ATag t = new ATag(); t.setPageContext(...); t.setParent(...); t.setAttribute1(value1); t.setAttribute2(value2); t.doStartTag(); –out = pageContext.pushBody(); –t.setBodyContent(out); // perform any initialization needed after body content is set –t.doInitBody(); –t.doAfterBody(); t.doEndTag(); –t.pageContext.popBody(); t.release();

What methods need to be implemented? Tag Handler Type Methods SimpledoStartTag, doEndTag, release AttributesdoStartTag, doEndTag, set/getAttribute1...N Body, no interaction doStartTag, doEndTag, release Body, interaction doStartTag, doEndTag, release, doInitBody, doAfterBody

Simple Tags public SimpleTag extends Tag Support { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello."); } catch (Exception ex) { throw new JspTagException("SimpleTag: " + e.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } TLD bodycontent Element Tags without bodies must declare that their body content is empty:... empty

Tags with Attributes Tag Handler should have private AttributeClass attr1; setAttr1(AttributeClass ac) {... } AttributeClass getAttr1() {... } TLD attribute Element... attr1 true|false|yes|no public class TwaTEI extends TagExtraInfo { public boolean isValid(Tagdata data) { Object o = data.getAttribute("attr1"); …. return true; }

Tags with a Body If the body of the tag needs to be evaluated, the doStartTag method needs to return EVAL_BODY_TAG; otherwise it should return SKIP_BODY. public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); // get the bc as string String query = bc.getString(); // clean up bc.clearBody(); try { Statement stmt = connection.createStatement(); result = stmt.executeQuery(query); } catch (SQLException e) { throw new JspTagException("QueryTag: " + e.getMessage()); } return SKIP_BODY; }

JSTL-like Tags with JSP 2.0 JSP 2.0 has two APIs, called Classic Tags API and Simple Tags API Extend SimpleTagSupport or one of its subclasses. The VarTagSupport, IfTag, and WhileTag classes ub/articles/andrei_jsptags.htmlhttp:// ub/articles/andrei_jsptags.html

You are strongly encouraged to use as many tag libraries as possible in your term project. For easier grading, please demonstrate your tags during term project presentation.

JDBC Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational database –Structured Query Language JDBC –Java Database Connectivity –JDBC driver

Points to remember JDBC Driver – Load the proper driver DB connection Statement Executing the statements ResultSet Close – close connection Or connectionPool PreparedStatement

Relational-Database Model Relational database –Table –Record –Field, column –Primary key Unique data SQL statement –Query –Record sets

Manipulating Databases with JDBC Connect to a database Query the database Display the results of the query

Connecting to and Querying a JDBC Data Source DisplayAuthors –Retrieves the entire authors table –Displays the data in a JTextArea

public class SQLGatewayServlet extends HttpServlet{ private Connection connection; public void init() throws ServletException{ try{ Class.forName("org.gjt.mm.mysql.Driver"); String dbURL = "jdbc:mysql://localhost/murach"; String username = "root"; String password = ""; connection = DriverManager.getConnection( dbURL, username, password); } Create Connection at Init()

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ String sqlStatement = request.getParameter("sqlStatement"); String message = ""; try{ Statement statement = connection.createStatement(); sqlStatement = sqlStatement.trim(); String sqlType = sqlStatement.substring(0, 6); if (sqlType.equalsIgnoreCase("select")){ ResultSet resultSet = statement.executeQuery(sqlStatement); // create a string that contains a HTML-formatted result set message = SQLUtil.getHtmlRows(resultSet); } else { int i = statement.executeUpdate(sqlStatement); if (i == 0) // this is a DDL statement message = "The statement executed successfully."; else // this is an INSERT, UPDATE, or DELETE statement message = "The statement executed successfully. " + i + " row(s) affected."; } statement.close(); } From JDBC Example at course web page

public void init() throws ServletException{ connectionPool = MurachPool.getInstance(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ Connection connection = connectionPool.getConnection(); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String Address = request.getParameter(" Address"); User user = new User(firstName, lastName, Address); HttpSession session = request.getSession(); session.setAttribute("user", user); String message = "";

Processing Multiple ResultSets or Update Counts Execute the SQL statements Identify the result type –ResultSet s –Update counts Obtain result –getResultSet –getUpdateCount

Prepared Statement Sometimes prepared statement is more convenient and more efficient for sending SQL statements to the database. When to use PreparedStatement – When you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead The main feature of a PreparedStatement object is that unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement's SQL statement without having to compile it first.

PreparedStatement example try{ String _querySelect = “SELECT * FROM MOVIE WHERE title like ?”; preStatement = connection.prepareStatement( _querySelect, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); }

Prepared Statement Example Connection connection = DriverManager.getConnection("jdbc:sapdb://" + Server + "/" + Database, User, Password); // Preparing the query to be executed preStatement = connection.prepareStatement( "insert into addimage values(?,?,?)"); // Setting the actual values in the query preStatement.setString(1,fileId); preStatement.setString(2,fileDes); // A file reader to get the contents of image FileInputStream fi=new FileInputStream(fileName); byte[] Img= new byte[fi.available()+1]; fi.read(Img); preStatement.setBytes(3,Img); // Executing the SQL Query preStatement.execute(); System.out.println("Image Successfully inserted into MaxDB!");

JDBC 2.0 Optional Package javax.sql Package javax.sql –Included with Java 2 Enterprise Edition Interfaces in package javax.sql –DataSource –ConnectionPoolDataSource –PooledConnection –RowSet

Connection Pooling Database connection –Overhead in both time and resources Connection pools –Maintain may database connections –Shared between the application clients

import util.MurachPool; public class Servlet extends HttpServlet{ private MurachPool connectionPool; public void init() throws ServletException{ connectionPool = MurachPool.getInstance(); } public void destroy() { connectionPool.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ Connection connection = connectionPool.getConnection(); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String Address = request.getParameter(" Address"); User user = new User(firstName, lastName, Address); HttpSession session = request.getSession(); session.setAttribute("user", user);

Relational DB and SQL statements This section is self-study section

Relational-Database Model Relational-database structure of an Employee table.

Relational Database Overview: The books Database Sample books database –Four tables Authors, publishers, authorISBN and titles –Relationships among the tables

Relational Database Overview: The books Database

Relational Database Overview: The books Database (Cont.)

Relational Database Overview: The books Database

Relational Database Overview: The books Database (Cont.)

Fig. 8.11Table relationships in books.

Structured Query Language (SQL) SQL overview SQL keywords

Basic SELECT Query Simplest format of a SELECT query –SELECT * FROM tableName SELECT * FROM authors Select specific fields from a table –SELECT authorID, lastName FROM authors

WHERE Clause specify the selection criteria –SELECT fieldName1, fieldName2, … FROM tableName WHERE criteria SELECT title, editionNumber, copyright FROM titles WHERE copyright > 1999 WHERE clause condition operators –, =, =, <> –LIKE wildcard characters % and _

WHERE Clause (Cont.) SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘D%’

WHERE Clause (Cont.) SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘_i%’

ORDER BY Clause Optional ORDER BY clause –SELECT fieldName1, fieldName2, … FROM tableName ORDER BY field ASC –SELECT fieldName1, fieldName2, … FROM tableName ORDER BY field DESC ORDER BY multiple fields –ORDER BY field1 sortingOrder, field2 sortingOrder, … Combine the WHERE and ORDER BY clauses

ORDER BY Clause (Cont.) SELECT authorID, firstName, lastName FROM authors ORDER BY lastName ASC

ORDER BY Clause (Cont.) SELECT authorID, firstName, lastName FROM authors ORDER BY lastName DESC

ORDER BY Clause (Cont.) SELECT authorID, firstName, lastName FROM authors ORDER BY lastName, firstName

ORDER BY Clause (Cont.) SELECT isbn, title, editionNumber, copyright, price FROM titles WHERE title LIKE ‘%How to Program’ ORDER BY title ASC

Merging Data from Multiple Tables: Joining Join the tables –Merge data from multiple tables into a single view –SELECT fieldName1, fieldName2, … FROM table1, table2 WHERE table1.fieldName = table2.fieldName –SELECT firstName, lastName, isbn FROM authors, authorISBN WHERE authors.authorID = authorISBN.authorID ORDER BY lastName, firstName

Merging Data from Multiple Tables: Joining (Cont.)

INSERT INTO Statement Insert a new record into a table –INSERT INTO tableName ( fieldName1, …, fieldNameN ) VALUES ( value1, …, valueN ) INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ )

UPDATE Statement Modify data in a table –UPDATE tableName SET fieldName1 = value1, …, fieldNameN = valueN WHERE criteria UPDATE authors SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’

DELETE FROM Statement Remove data from a table –DELETE FROM tableName WHERE criteria DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’