You are on page 1of 48

Topic 3: Distrib Programming

Distributed Programming
Tier Architecture
Overview
 In the beginning, life was simple. Computers were separate, individual
devices.
Programs had access to all the computer's input and output through
computer- connected devices. With the invention of networks, life became
more complicated.
 Now we have to write programs that depend on other programs
running on faraway computers. Often, we have to write all those
faraway programs as well! This is what's called distributed
programming.
Distributed Application
 A distributed application is a system comprised of programs running on
multiple host computers. The architecture of this distributed application is
a sketch of the different programs, describing which programs are running
on which hosts, what their responsibilities are, and what protocols
determine the ways in which different parts of the system talk to one
another.
Tier Architecture
 The concept of tiers provides a convenient way to group different
classes of architecture.
One Tier
 it has a one-tier architecture. If your application is running on two
computers --
for instance, a typical Web CGI application that runs on a Web browser
(client) and a Web server
. In a two-tier system
 , you have a client program and a serverprogram. The main difference
between the two is that the server responds to requests from many
different clients, while the clients usually initiate the requests for
information from a single server
Three tier
 A three-tier application adds a third program to the mix, usually a
database, in which the server stores its data. The three-tier application
is an incremental improvement to the two-tier architecture.
N-tier
 An n-tier architecture, on the other hand, allows an unlimited number of
programs
to run simultaneously, send information to one another, use different
protocols to communicate, and interact concurrently. This allows for a
much more powerful application, providing many different services to
many different clients.
JDBC Overview
1. Get a Connection to the database.
2. Create a Statement using the Connection.
3. Execute the Statement with SQL string.
4. Use the results.
JDBC Overview
selects a specific Connection type
and instantiates it

creates Statements
for database actions
JDBC Code
/** BAD CODE. We'll fix this later. */
static final String URL = "jdbc:mysql://dbserver/world";
static final String USER = "student";
static final String PASSWORD = "secret";
// 1. Get a Connection to the database.
Connection connection =
DriverManager.getConnection( URL, USER, PASSWORD );

// 2. Create a Statement
Statement statement = connection.createStatement();

// 3. Execute the Statement with SQL command.


ResultSet rs = statement.executeQuery("SELECT * FROM ...");

// 4. Use the Result.


while ( rs.next( ) ) {
String name = rs.getString("name");
Connecting to a Database in Java (1)
 java.sql.Connection is a standard interface for connecting
to any database.
 Each database type requires its own jdbc driver that implements this
interface.
 MySQL driver
mysql-connector-java-5.1.7-bin.jar
 Derby driver: derby.jar or derbyclient.jar

 HSQLDB driver: hsqldb.jar

 DriverManager selects the driver based on URL.


DriverManager returns a Connection
url = "jdbc:mysql://hostname/database"

DriverManager <<interface>>
creates Connection
getConnection( url, user,
passwd) : Connection createStatement(): Statement
close( )
isClosed( ): boolean
getCatalog( ): String

HSQLConnection MySqlConnection
Patterns Question
What design pattern is used by DriverManager?

DriverManager <<interface>>
creates Connection
getConnection( url, user,
passwd) : Connection createStatement(): Statement
close( )
isClosed( ): boolean
getCatalog( ): String

HSQLConnection MySqlConnection
Where is the Database Driver?
Driver is in a JAR file.
JAR file must be on the
CLASSPATH. Use one of these:
1. add as an external jar file to your IDE project
2. add the JAR to your CLASSPATH
CLASSPATH = /my/path/mysql-connector.jar;.

3. add JAR using the Java command line:


java -cp /my/path/mysql-connector.jar ...

4. Put JAR file in the JRE/lib/ext directory:


C:/java/jre1.6.0/lib/ext/mysql-connector.jar
Can't find the Driver?
DriverManager finds a registered database driver.
How?
1. Automatically. This should happen with type 4 & 5.
2. Load the driver class in your program:
Class.forName("com.mysql.jdbc.Driver");
3. Add driver to the jdbc.drivers property
System.setProperty("jdbc.drivers",
"com.mysql.jdbc.Driver");
4. Specify jdbc.drivers property on command line:
java -Djdbc.drivers="com.mysql.jdbc.Driver" ...
Database URL
The format of a database URL is:

String DB_URL = "jdbc:mysql://dbserver:3306/world";

Protocol Sub-protocol Hostname Port DatabaseName

 Port is the TCP port number where the database server


is listening.
 3306 is the default port for MySQL
 Use hostname "localhost" for the local machine.
Database URL
The hostname and port are optional.
For MySQL driver: defaults are localhost and port 3306

Example: These 4 URL refer to the same database


"jdbc:mysql://localhost:3306/world"
"jdbc:mysql://localhost/world"
"jdbc:mysql:///world"
"jdbc:mysql:/world"
JDBC Driver
You can get a JDBC driver (network connector) for most
databases: MySQL, PostgreSQL, Oracle, SQLite ...

5 Types of JDBC drivers


Type 1: JDBC-to-ODBC bridge driver for Microsoft ODBC. Java
JDBC includes the bridge driver: sun.jdbc.odbc.JdbcOdbcDriver.
Type 2: Native-API driver (written in C or C++ using JNI)
Type 3: Pure Java client-to-server driver, use a standard network
protocol. The server translates requests to server-specific protocol.
Type 4: Pure Java drivers implementing a database-specific network
protocol. Java programs can connect directly to the database.
Type 5: The latest.
Exercise: Install JDBC Driver
 Download the mysql-connector-*.jar file

 use http://se.cpe.ku.ac.th/download/mysql
 alternate: http://www.mysql.com
 Install it in your software "library" directory,
e.g. C:/lib/mysql

JDBC Connector for MySQL:


mysql-connector-java-5.x.y.zip
Executing SQL Queries
 A statement.executeQuery( ) returns a ResultSet.
 ResultSet is a scrollable set of values.

Statement statement = connection.createStatement();

// execute a SELECT command


ResultSet rs = statement.executeQuery(
"SELECT * FROM city WHERE id = "+id );
rs.first(); // scroll to first result
do {
String name = rs.getString(1);// get 1st field
int population = rs.getInt("population");
...
} while( rs.next() );
JSP Database (Two-tier)
 Importing Libraries
 Initializing Database Connection
 Performing CRUD (Create, Read, Update and Delete)
 Display.jsp
 Insert.jsp
 Update.jsp
 Delete.jsp
1. Importing Libraries
<%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@
page import="javax.servlet.http.*,javax.servlet.*" %> <%@
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <
%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
2. Initialize Database Connection
<sql:setDataSource var="snapshot"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/loginjdbc"
user="root" password=""/>
3. Performing Read (Display Records)
<<sql:query dataSource="${snapshot}"
var="result"> SELECT * from Product;
</sql:query>

<c:forEach var="row" items="${result.rows}">


<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.pname}"/></td>
<td><c:out value="${row.quantity}"/></td>

</tr>
</c:forEach>
3. Performing Create (Insert Records)
<c:set var="id_n" value=“67"/>
<c:set var="pname_n" value=“Printer"/>
<c:set var="quantity_n" value=“3"/>

<sql:update dataSource="${snapshot}" var="result">


INSERT INTO Product VALUES (?,?,?);
<sql:param value="${id_n}"/>
<sql:param value="${pname_n}"/>
<sql:param value="${qty_n}"/>
4. Performing Update (Update Records)

<c:set var=”id_n" value=”2"/>

<sql:update dataSource="${snapshot}"
var="count"> UPDATE Product SET pname =
'colgate' WHERE id = ?
<sql:param value="${id_n}" />
</sql:update>
4. Performing Delete (Delete Records)

<c:set var=”id_n" value=”3"/>

<sql:update dataSource="${snapshot}"
var="count"> DELETE FROM Product WHERE
id = ?
<sql:param value="${empId}" />
</sql:update>
Three-tier Architecture
Three-tier Architecture
Three-tier Architecture
The 3-Tier Architecture for Web Apps

Presentation Layer - Static or dynamically generated content rendered


by the
browser (front-end)

Logic Layer - A dynamic content processing and generation level


application server, e.g., Java EE, ASP.NET, PHP, ColdFusion
platform (middleware)

Data Layer - A database, comprising both data sets and the database
management system or RDBMS software that manages and provides
access to the data (back- end)
Origin of Design Patterns

 Architectural concept by Christopher Alexander (1977/79)


 Adapted to OO Programming by Beck and Cunningham (1987)
 Popularity in CS after the book: “Design Patterns: Elements of Re-
useable Object- oriented software”, 1994. Erich Gamma, Richard Helm,
Ralph Johnson, John Vlissides
 Now widely-used in software engineering
MVC for Java Servlets

9-Nov-16
The MVC pattern
 MVC stands for Model-View-Controller
 The Model is the actual internal representation
 The View (or a View) is a way of looking at or displaying the
model
 The Controller provides for user input and modification
 These three components are usually implemented as separate
classes
MVC
 One of the most common Design Patterns is Model-View-Controller
(MVC)
 The model does all the computational work
 It is input/output free
 All communication with the model is via methods
 The controller tells the model what to do
 User input goes to the controller
 The view shows results; it is a “window” into the model
 The view can get results from the controller, or
 The view can get results directly from the model
36
Advantages of MVC
 One advantage is separation of concerns
 Computation is not intermixed with I/O
 Consequently, code is cleaner and easier to understand
 Another advantage is flexibility
 The GUI (if one is used) can be completely revamped without touching the
model in any way
 Another big advantage is reusability
 The same model used for a servlet can equally well be used for an
application or an applet (or by another process)

 MVC is widely used and recommended

37
MVC Design Pattern Example in Java console
Model - Model represents an object or JAVA POJO carrying data. It can
also have logic to update controller if its data changes.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both model and view.
Implementation

We are going to create a


1. Student object acting as a model.
2. StudentView will be a view class which can print student details on
console
3. StudentController is the controller class responsible to
store data in Student object and update view StudentView
accordingly.
Class Diagram
Student.java (model)
 public class Student {
 private String rollNo;
 private String name;

 public String getRollNo() {
 return rollNo;
 }

 public void setRollNo(String rollNo) {
 this.rollNo = rollNo;
 }

Student.java (model)
 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }
 }
StudentView.java (View)

public class StudentView {


public void printStudentDetails(String studentName, String
studentRollNo){ System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
StudentController.java (Controller)
public class StudentController {
private Student model;
private StudentView view;

public StudentController(Student model, StudentView view){


this.model =
model;
this.view = view;
}

public void setStudentName(String name){


model.setName(name);
}

public String getStudentName(){


return model.getName();
}
StudentController.java (Controller)
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}

public String getStudentRollNo(){


return model.getRollNo();
}

public void updateView(){


view.printStudentDetails(model.getName(), model.getRollNo());
}
}
MVC Servlet Architecture
Explore More Please

You might also like