web based development.ppt
-
Upload
mumbai-academics -
Category
Documents
-
view
218 -
download
0
Transcript of web based development.ppt
-
8/14/2019 web based development.ppt
1/50
Web-based Database
Development
IS 465
Min Song
-
8/14/2019 web based development.ppt
2/50
Three-Tier Architecture
Oracle/MySQLDB Server
Apache TomcatApp Server
MicrosoftInternetExplorer
HTML
Tuples
HTTPRequests
JDBC
Requests
Java ServerPages (JSPs)
Located@ your server
Located@ Your PC
Located@ Any PC
-
8/14/2019 web based development.ppt
3/50
Data Entry Forms
-
8/14/2019 web based development.ppt
4/50
JavaDatabaseConnectivity (JDBC)
-
8/14/2019 web based development.ppt
5/50
Instruction for Building Web-based
Database in Java
Tomcat 6.0 or above
http://tomcat.apache.org/download-60.cgi
From the above download site, choose Binary Distribution-> Core -> Zip
Unzip the package to C:\Program Files\ApacheSoftware Foundation\Tomcat 6.0\webapps
Start Tomcat by executing tomcat6w in C:\ProgramFiles\Apache Software Foundation\Tomcat 6.0\bin
Open the internet browser and typehttp://localhost:8080/. If you see the tomcat on theupper left corner, you are successful so far.
http://tomcat.apache.org/download-60.cgihttp://localhost:8080/http://localhost:8080/http://tomcat.apache.org/download-60.cgihttp://tomcat.apache.org/download-60.cgihttp://tomcat.apache.org/download-60.cgi -
8/14/2019 web based development.ppt
6/50
Download mysql server at
http://dev.mysql.com/downloads/mysql/5.1.h
tmland install it onto your computer
Download a sample DB from my home page
Create a database in mysql as follows:
http://dev.mysql.com/downloads/mysql/5.1.htmlhttp://dev.mysql.com/downloads/mysql/5.1.htmlhttp://dev.mysql.com/downloads/mysql/5.1.htmlhttp://dev.mysql.com/downloads/mysql/5.1.html -
8/14/2019 web based development.ppt
7/50
Shell > mysqlu rootp
mysql> CREATE DATABASE world;
mysql> USE world; mysql> SOURCE world.sql;
mysql> SHOW TABLES;
-
8/14/2019 web based development.ppt
8/50
Go to the following url:
http://localhost/world_db/index.jsp
Note: You need to modify configuration files
and properties file such as sqldb.xml and
build.properties
http://localhost/world_db/index.jsphttp://localhost/world_db/index.jsp -
8/14/2019 web based development.ppt
9/50
Data Base Connectivity From JAVA
package edu.njit.is465;
import java.sql.Connection; // Javas interface to SQLimport java.sql.DriverManager; // Loads the appropriate SQL driver
import java.sql.SQLException; // Handles errors from the database
import java.util.Properties; // Configuration file to load the//db.properties file
import java.util.logging.Level; // Logs information
import java.util.logging.Logger; // Logs information
/**
* Base class for those that use a database connection
*
* @version 1.0
* @since 1.0
*/
public abstract class DatabaseConnection{
protected final Logger logger;
protected Connection connect = null;
-
8/14/2019 web based development.ppt
10/50
import java.sql.*;
class JdbcTest {
public static void main (String args []) throws SQLException {
// Load Oracle driver
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
// Connect to the local database
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myhost:1521:ORCL","scott",
"tiger");
JDBC
-
8/14/2019 web based development.ppt
11/50
// Query the student names
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT name FROM
Student");// Print the name out
//name is the 2ndattribute of Student
while (rset.next ())
System.out.println (rset.getString (1));
//close the result set, statement, and the connection
rset.close();stmt.close();
conn.close();
-
8/14/2019 web based development.ppt
12/50
PreparedStatement ObjectIf you want to execute a Statement object many times, it will
normally reduce execution time to use a PreparedStatement
object instead.
PreparedStatement updateStud = conn.prepareStatement(
"UPDATE Student SET name = ? WHERE lastname LIKE
?");
updateStud.setString(1, John);
updateStud.setString(2, Smith);
updateStud.executeUpdate();
-
8/14/2019 web based development.ppt
13/50
PreparedStatement Objectthe following two code fragments accomplish the same thing:
Code Fragment 1:
String updateString = "UPDATE COFFEES SET SALES = 75" + "WHERE COF_NAME LIKE 'Colombian'";
stmt.executeUpdate(updateString);
Code Fragment 2:
PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME
LIKE ? "); updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():
-
8/14/2019 web based development.ppt
14/50
int getInt int columnIndex)Retrieves the value of the designated column in thecurrent row of this ResultSet object as an int in the Javaprogramming language.
int getInt String columnName) String getString int columnIndex) String getString String columnName)
-
8/14/2019 web based development.ppt
15/50
Using TransactionsWhen a connection is created, it is in auto-commit mode. This means that
each individual SQL statement is treated as a transaction and will beautomatically committed right after it is executed.conn.setAutoCommit(false);....transaction...con.commit();con.setAutoCommit(true);
-
8/14/2019 web based development.ppt
16/50
Using Transactionsexamplecon.setAutoCommit(false);PreparedStatement updateSales = con.prepareStatement( UPDATECOFFEES SET SALES = ? WHERE COF_NAME LIKE ? );updateSales.setInt(1, 50);updateSales.setString(2, Colombian );updateSales.executeUpdate();PreparedStatement updateTotal = con.prepareStatement( UPDATECOFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ? );updateTotal.setInt(1, 50);updateTotal.setString(2, Colombian );updateTotal.executeUpdate();con.commit();con.setAutoCommit(true);
-
8/14/2019 web based development.ppt
17/50
Retrieving Exceptions
JDBC lets you see the warnings and exceptions generated by your
DBMS and by the Java compiler. To see exceptions, you can have a
catchblock print them out. For example, the following two catch
blocks from the sample code print out a message explaining the
exception:
try {
// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
-
8/14/2019 web based development.ppt
18/50
JSP Syntax
Comment
Expression
Scriplet
Include
-
8/14/2019 web based development.ppt
19/50
Entry Form - First Attempt
-
8/14/2019 web based development.ppt
20/50
Entry Form - First Attempt
Data Entry Menu
Courses
Classes
Students
Menu HTML Code
-
8/14/2019 web based development.ppt
21/50
Entry Form - First Attempt
Open connection code
Statement code
Presentation codeClose connection code
JSP Code
-
8/14/2019 web based development.ppt
22/50
Entry Form - First Attempt
Open Connectivity Code
-
8/14/2019 web based development.ppt
23/50
Entry Form - First Attempt
Statement Code
-
8/14/2019 web based development.ppt
24/50
Entry Form - First Attempt
SSN
First
Last
College
Iteration Code
Presentation Code
-
8/14/2019 web based development.ppt
25/50
Entry Form - First Attempt
-
8/14/2019 web based development.ppt
26/50
Entry Form - First Attempt
Iteration Code
-
8/14/2019 web based development.ppt
27/50
Entry Form - First Attempt
Close Connectivity Code
-
8/14/2019 web based development.ppt
28/50
Entry Form - Second Attempt
-
8/14/2019 web based development.ppt
29/50
Entry Form - Second Attempt
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
JSP Code
-
8/14/2019 web based development.ppt
30/50
Entry Form - Second Attempt
// Check if an insertion is requestedString action = request.getParameter("action");
if (action != null && action.equals("insert")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to// INSERT the student attrs INTO the Student table.
PreparedStatement pstmt = conn.prepareStatement(
("INSERT INTO Student VALUES (?, ?, ?, ?, ?)"));
pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN")));
pstmt.setString(2, request.getParameter("ID"));
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
Insertion Code
-
8/14/2019 web based development.ppt
31/50
Entry Form - Second Attempt
SSN
First
Last
College
Insert Form Code
Iteration Code
Presentation Code
-
8/14/2019 web based development.ppt
32/50
Entry Form - Second Attempt
Insert Form Code
-
8/14/2019 web based development.ppt
33/50
Entry Form - Third Attempt
-
8/14/2019 web based development.ppt
34/50
Entry Form - Third Attempt
Open connection codeInsertion Code
Update Code
Delete Code
Statement code
Presentation codeClose connection code
JSP Code
-
8/14/2019 web based development.ppt
35/50
Entry Form - Third Attempt
// Check if an update is requestedif (action != null && action.equals("update")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// UPDATE the student attributes in the Student table.PreparedStatement pstatement = conn.prepareStatement(
"UPDATE Student SET ID = ?, FIRSTNAME = ?, " +
"LASTNAME = ?, COLLEGE = ? WHERE SSN = ?");
pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Update Code
-
8/14/2019 web based development.ppt
36/50
Entry Form - Third Attempt
// Check if a delete is requestedif (action != null && action.equals("delete")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// DELETE the student FROM the Student table.
PreparedStatement pstmt = conn.prepareStatement(
"DELETE FROM Student WHERE SSN = ?");
pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));int rowCount = pstmt.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Delete Code
-
8/14/2019 web based development.ppt
37/50
Entry Form - Third Attempt
SSN
First
Last
College
Insert Form Code
Iteration Code
Presentation Code
-
8/14/2019 web based development.ppt
38/50
Entry Form - Third Attempt
Iteration Code
-
8/14/2019 web based development.ppt
39/50
Data Base Connectivity From JAVA
public DatabaseConnection() throws Exception{
logger = Logger.getLogger(this.getClass().getName());
Properties props = new Properties();try {props.load(getClass().getResourceAsStream("db.properties"));final String driver = props.getProperty("driver");final String url = props.getProperty("url");final String user = props.getProperty("user");final String pass = props.getProperty("pass");
Class.forName(driver).newInstance();connect = DriverManager.getConnection(url, user, pass);}catch (Exception ex) {
logger.log(Level.SEVERE, "Unable to create databaseconnection",
ex);throw new Exception("Unable to create database
connection",
ex);}
}
-
8/14/2019 web based development.ppt
40/50
-
8/14/2019 web based development.ppt
41/50
Data Base Connectivity From JAVA
When an object goes out of scope it is important to close the connection.
protected void finalize()
{
if (connect != null) {
try {
connect.close();
connect = null;
}
catch (SQLException ex) {
logger.log(Level.SEVERE, "Unable to close database connection",
ex);
}}
}
}
-
8/14/2019 web based development.ppt
42/50
Data Base Connectivity From JAVA
/*
* DatabaseCourseManager.java
**/
package edu.njit.is465;
import java.sql.PreparedStatement; //Executes a SQL statement
import java.sql.ResultSet; //Stores the rows returned from the query
import java.sql.SQLException;//Handles errors
import java.util.ArrayList;//Dynamic structure
import java.util.List;//Interface to an ArrayListimport java.util.logging.Level; Used to log errors
/**
* Database backed course manager
* * @version 1.0
* @since 1.0
*/public class DatabaseCourseManager extends DatabaseConnection
implements CourseManager
{
-
8/14/2019 web based development.ppt
43/50
Data Base Connectivity From JAVA
ADDING A RECORD TO THE DATABASEExample: AddCourse
A course contains:
Department NameDepartment NumberNumber of CreditsNameDescription
Therefore, the insert statement will contain five values. In its most basic form, a SQL INSERT statement has the following s yntax:
INSERT INTO TableName VALUES (list of values)
This form of SQL INSERT requires the knowledge of the order of the fields in the table. The SQL table was created in the orderthe fields are listed above. Therefore, we can perform a SQL insert by listing the values in their proper place.
Java allows this to be done without a lot of fancy string manipulation if you use the PreparedStatement object. Observe thefollowing code which associates each value to be inserted with the proper question mark.
One huge benefit to using the PreparedStatement instead of building the string manually, is it handles any special charactersthat would need to be escaped. i.e. double quote. In addition, it will prevent SQL code from inadvertently being executed, butthat is an advanced topic.
-
8/14/2019 web based development.ppt
44/50
Data Base Connectivity From JAVA
/*
* @see edu.njit.is465.CourseManager#addCourse(edu.njit.is465.Course)
*/
public void addCourse(final Course course) throws SchedulerException
{
try {
final PreparedStatement stm = connect.prepareStatement(
"INSERT INTO Course VALUES(?, ?, ?, ?, ?)");
stm.setString(1, course.getDepartment());
stm.setInt(2, course.getNumber());
stm.setInt(3, course.getCredits());
stm.setString(4, course.getName());
stm.setString(5, course.getDescription());
int n = stm.executeUpdate();stm.close();
if (n != 1)
throw new SchedulerException("Unable to add course");
}
catch (SQLException ex) {
logger.log(Level.SEVERE, "addStudent", ex);
throw new SchedulerException("Unable to add course", ex);
}
}
Executing the SQL command is simply a matter of calling the executeUpdatemethod of thePreparedStatementobject.
-
8/14/2019 web based development.ppt
45/50
Data Base Connectivity From JAVA
RETRIEVING RECORDS FROM A DATABASE
Example: getAllCourses
We need to select data from the database and return it into a structure Java can understand.
In its most basic form, a SQL SELECT statement has the following syntax:
SELECT * FROM TableName ORDER BY ListOfFields
The ORDER BYclause is optional, but will allow the results to be sorted by the fields we list after the keywords ORDER
BY.
Again we will use the PreparedStatementto hold the SQL command.
The results of the query will be stored in a ResultSet object and then each record will be added to our coursesobject.
-
8/14/2019 web based development.ppt
46/50
Data Base Connectivity From JAVA
/*
* @see edu.njit.is465.CourseManager#getAllCourses()
*/
public Course[] getAllCourses()
{
try {
final PreparedStatement stm = connect.prepareStatement(
"SELECT * FROM Course ORDER BY dept, num");
final ResultSet result = stm.executeQuery();
final List courses = new ArrayList();
while (result.next())
courses.add(toCourse(result));
result.close();stm.close();
return courses.toArray(new Course[0]);
}
catch (SQLException ex) {
logger.log(Level.SEVERE, "getAllCourses", ex);
return new Course[0];
}
}
-
8/14/2019 web based development.ppt
47/50
-
8/14/2019 web based development.ppt
48/50
Data Base Connectivity From JAVA
/*
* @see edu.njit.is465.CourseManager#getCourse(java.lang.String, int)
*/
public Course getCourse(final String dept, int num)
{
Course course = null;
try {
final PreparedStatement stm = connect.prepareStatement(
"SELECT * FROM Course WHERE dept = ? AND num = ?");
stm.setString(1, dept);
stm.setInt(2, num);
final ResultSet result = stm.executeQuery();
if (result.next())course = toCourse(result);
result.close();
stm.close();
}
catch (SQLException ex) {
logger.log(Level.SEVERE, "getCourse", ex);
}
return course;
}
-
8/14/2019 web based development.ppt
49/50
Data Base Connectivity From JAVA
/*
* @see edu.njit.465.CourseManager#removeCourse(java.lang.String, int)
*/
public void removeCourse(final String dept, int num) throws SchedulerException
{
try {
final PreparedStatement stm = connect.prepareStatement(
"DELETE FROM Course WHERE dept = ? AND num = ?");
stm.setString(1, dept);
stm.setInt(2, num);
stm.executeUpdate();
stm.close();
}
catch (SQLException ex) {
logger.log(Level.SEVERE, "removeCourse", ex);throw new SchedulerException(ex);
}
}
-
8/14/2019 web based development.ppt
50/50
Data Base Connectivity From JAVA
/** @see edu.njit.is465.CourseManager#updateCourse(edu.njit.is465.Course)*/public void updateCourse(final Course course) throws SchedulerException
{ try {final PreparedStatement stm = connect.prepareStatement(
"UPDATE Course SET credits = ?, name = ?,description = ?" +
" WHERE dept = ? AND name = ?");stm.setInt(1, course.getCredits());stm.setString(2, course.getName());stm.setString(3, course.getDescription());stm.setString(4, course.getDepartment());stm.setInt(5, course.getNumber());
stm.executeUpdate();stm.close();}catch (SQLException ex) {
logger.log(Level.SEVERE, "updateCourse", ex);throw new SchedulerException(ex);
}}
private Course toCourse(final ResultSet result) throws SQLException{
final String dept = result.getString("dept");
final int num = result.getInt("num");final Course course = new Course(dept, num);course.setCredits(result.getInt("credits"));course.setName(result.getString("name"));course.setDescription(result.getString("description"));return course;
}}