Unit - Ii: Java - SQL

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

UNIT – II

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We can use JDBC API to access tabular data stored in any relational database. By the help
of JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class

1
o Clob class
o Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

What is API
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API can be created for
applications, libraries, operating systems, etc.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driv
method calls into the ODBC function calls. This is now discouraged because of thin driver.

2
In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.

3
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.

4
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.

DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().

Useful methods of DriverManager class

Method Description

5
1) public static void registerDriver(Driver is used to register the given driver with
driver): DriverManager.

2) public static void deregisterDriver(Driver is used to deregister the given driver (drop
driver): the driver from the list) with
DriverManager.

3) public static Connection is used to establish the connection with


getConnection(String url): the specified url.

4) public static Connection is used to establish the connection with


getConnection(String url,String the specified url, username and password.
userName,String password):

Introduction to java.sql package

This package provides the APIs for accessing and processing data which is stored in the
database especially relational database by using the java programming language. It
includes a framework where we different drivers can be installed dynamically to access
different databases especially relational databases.
This java.sql package contains API for the following :
1. Making a connection with a database with the help of DriverManager class

a) DriverManager class: It helps to make a connection with the driver.


b) SQLPermission class: It provides a permission when the code is running within a Security
Manager, such as an applet. It attempts to set up a logging stream through the
DriverManager class.
c) Driver interface : This interface is mainly used by the DriverManager class for registering
and connecting drivers based on JDBC technology.
d). DriverPropertyInfo class : This class is generally not used by the general user.
2). Sending SQL Parameters to a database :

a). Statement interface: It is used to send basic SQL statements.


b). PreparedStatement interface: It is used to send prepared statements or derived SQL

6
statements from the Statement object.
c). CallableStatement interface : This interface is used to call database stored procedures.
d). Connection interface : It provides methods for creating statements and managing their
connections and properties.
e). Savepoint : It helps to make the savepoints in a transaction.

3). Updating and retrieving the results of a query:

a). ResultSet interface: This object maintains a cursor pointing to its current row of data.
The cursor is initially positioned before the first row. The next method of the resultset
interface moves the cursor to the next row and it will return false if there are no more rows
in the ResultSet object. By default ResultSet object is not updatable and has a cursor that
moves forward only.
4.) Providing Standard mappings for SQL types to classes and interfaces in Java
Programming language.

a). Array interface: It provides the mapping for SQL Array.


b). Blob interface : It provides the mapping for SQL Blob.
c). Clob interface: It provides the mapping for SQL Clob.
d). Date class: It provides the mapping for SQL Date.
e). Ref interface: It provides the mapping for SQL Ref.
f). Struct interface: It provides the mapping for SQL Struct.
g). Time class: It provides the mapping for SQL Time.
h). Timestamp: It provides the mapping for SQL Timestamp.
i). Types: It provides the mapping for SQL types.
5). Metadata
a). DatabaseMetaData interface: It keeps the data about the data. It provides information
about the database.
b). ResultSetMetaData: It gives the information about the columns of a ResultSet object.
c). ParameterMetaData: It gives the information about the parameters to the
PreparedStatement commands.
6). Exceptions
a). SQLException: It is thrown by the mehods whenever there is a problem while accessing
the data or any other things.
b). SQLWarning: This exception is thrown to indicate the warning.

7
c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch
update are not executed successfully.
d). DataTruncation: It is thrown to indicate that the data may have been truncated.
7). Custom mapping an SQL user- defined type (UDT) to a class in the java
programming language.
a). SQLData interface: It gives the mapping of a UDT to an intance of this class.
b). SQLInput interface: It gives the methods for reading UDT attributes from a stream.
c). SQLOutput: It gives the methods for writing UDT attributes back to a stream.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException

8
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the
classpath, and then JDBC driver manager can detect and load the driver automatically.

Example to register the OracleDriver class


Here, Java program is loading oracle driver to esteblish database connection.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method


1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


1. public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");

9
2. while(rs.next()){
3. System.out.println(rs.getInt(1)+" "+rs.getString(2));
4. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException
Example to close connection
1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close resources of
type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCU
R_UPDATABLE);

Commonly used methods of ResultSet interface


is used to move the cursor to the one row next from the current
1) public boolean next():
position.

is used to move the cursor to the one row previous from the
2) public boolean previous():
current position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

10
4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean absolute(int is used to move the cursor to the specified row number in the
row): ResultSet object.

6) public boolean relative(int is used to move the cursor to the relative row number in the
row): ResultSet object, it may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of the current
columnIndex): row as int.

8) public int getInt(String is used to return the data of specified column name of the current
columnName): row as int.

9) public String getString(int is used to return the data of specified column index of the current
columnIndex): row as String.

10) public String getString(String is used to return the data of specified column name of the current
columnName): row as String.

Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

11
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the
server name on which mysql is running, we may also use IP address, 3306 is the port number
and sonoo is the database name. We may use any database, in such case, we need to replace
the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database


In this example, sonoo is the database name, root is the username and password both.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())

12
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.
Two ways to load the jar file:
1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath
) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

2) Set classpath:
There are two ways to set the classpath:
 temporary
 permanent

How to set the temporary classpath


open command prompt and write:
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5 following steps. In this
example, we are using Oracle 10g as the database. So we need to know following information for the
oracle database:
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.

13
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the
driver, localhost is the server name on which oracle is running, we may also use IP address,
1521 is the port number and XE is the Oracle service name. You may get all these information
from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.

Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL query
to create a table.

1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database


In this example, we are connecting to an Oracle database and getting data from emp table. Here,
system and oracle are the username and password of the Oracle database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");

14
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();

}catch(Exception e){ System.out.println(e);}

}
}
The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.

2) set classpath:
There are two ways to set the classpath:
 temporary
 permanent

How to set the temporary classpath:


Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

15
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int
sets the integer value to the given parameter index.
value)
public void setString(int paramIndex,
sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, float
sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex,
sets the double value to the given parameter index.
double value)
executes the query. It is used for create, drop, insert,
public int executeUpdate()
update, delete etc.

16
executes the select query. It returns an instance of
public ResultSet executeQuery()
ResultSet.

Example of PreparedStatement interface that inserts the record


First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

JDBC Exception
The Exception are the set of condition that occurred when an abnormal condition try to interrupt
the normal flow of the code during the execution of program. Exception Occurred in JDBC
Connectivity when a connection object do not find a suitable driver to connect a url-database.
Understand with Example
The Tutorial illustrates an example from JDBC Exception. In this Tutorial we want to describe
you a code that show an exception in JDBC.For this we have a class JdbcException. The first
step is to import a package name java.sql include a definition for all the classes that provides you

17
network interface to communicate between front end and back end application. The next is to
load the driver by calling class. for name( ) with driver class passed as argument.
Driver.getConnection ( ) : This is used to built connection between url and database. In case
there is an exception in try block, the subsequent catch block caught and handle the exception,
The exception show you no suitable driver is found.
con.create Statement ( ) : This is used to create a Sql object. An sql object is used to send and
execute the query in backend database.
executeQuery ( ): This is used to return the result set obtained from the record set of the
database. The select statement is used to retrieve the result set from the database.
In this program code, the exception occurred in try block, therefore the subsequent catch block
show the exception that a suitable driver do not found using print ln.Once the suitable driver is
found the print ln print and display the element of no,name,id and dob.
rs.getString ( ) -The Result set object call a get String ( ),returns you a record set into a
formatted string element.
JdbcExceptions.java
import java.sql.*;

public class JdbcExceptions {

public static void main(String args[]) throws Exception {


Connection con = null;
Statement st = null;
ResultSet rs = null;

String url = new String();


String db = new String();
String driver = "com.mysql.jdbc.Driver";
String user = new String();
String pass = new String();

Class.forName(driver);

try {
con = DriverManager.getConnection(url + db, user, pass);
} catch (Exception e) {
System.err.println(e);

url = "jdbc:mysql://localhost:3306/";
db = "komal";

18
user = "root";
pass = "root";

con = DriverManager.getConnection(url + db, user, pass);


con.setAutoCommit(false);
st = con.createStatement();

String sql = "select * from person";


rs = st.executeQuery(sql);

System.out.println("no. \tName \tDob");


while (rs.next()) {
System.out.print(rs.getString("id") + " \t");
System.out.print(rs.getString("cname") + " \t");
System.out.println(rs.getDate("dob"));
}
}
}
}
Output
java.sql.SQLException: No suitable driver found for
no. Name Dob
1 Girish 1984-06-02
2 komal 1984-10-27

JSP Tutorial
Java Server Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent method for building Web-based applications. JSP have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will
teach you how to use Java Server Pages to develop your web applications in simple and easy steps.
This tutorial has been prepared for the beginners to help them understand basic functionality of
Java Server Pages (JSP) to develop your web applications. After completing this tutorial you will find
yourself at a moderate level of expertise in using JSP from where you can take yourself to next
levels.

JSP - Database Access


Create Table
To create the Employees table in the EMP database, use the following steps −

19
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

Step 3
Create the Employee table in the TEST database as follows − −
mysql> use TEST;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>

Create Data Records


Let us now create a few records in the Employee table as follows − −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');


Query OK, 1 row affected (0.00 sec)

20
mysql>

SELECT Operation
Following example shows how we can execute the SQL SELECT statement using JTSL in JSP
programming −
<%@ 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"%>

<html>
<head>
<title>SELECT Operation</title>
</head>

<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>

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


SELECT * from Employees;
</sql:query>

<table border = "1" width = "100%">


<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>

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


<tr>
<td><c:out value = "${row.id}"/></td>
<td><c:out value = "${row.first}"/></td>
<td><c:out value = "${row.last}"/></td>
<td><c:out value = "${row.age}"/></td>

21
</tr>
</c:forEach>
</table>

</body>
</html>
Access the above JSP, the following result will be displayed −

Emp ID First Name Last Name Age


100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Khan 30
103 Sumit Mittal 28

22
Introduction to Struts framework
Model-1 Architecture

In this Architecture all kinds of requirements get fulfilled in one layer. The user provides
request to the jsp and jsp provides response to the user. This Architecture uses a set of
jsp to implement presentation logic, business logic, controlling logic. It is suitable for
small scale requirement due to its simplicity. It does not provide reusability.

Model-2 Architecture

This layer is divided into three parts they are as below

1. Model
2. Controller
3. View

Model: - This layer implements business logic and contains data. State of users can be
stored in this layer. This layer can be created by using a set of java beans.

Controller: - This layer implements controlling logic. It takes decision to make visible
appropriate view to the appropriate users. This layer can be created by using a servlet
and a set of helper classes. The users gives request to the servlet present in the layer.

View: - This layer implements presentation logic of the application. It provides response
to the user. A set of Jsp can be used to create this layer.

Introduction to Struts

This is a framework to implement MVC Architecture in a java based web application. It


uses three different layers to implements different types of logic. It provides a set of
classes and tag libraries for being used in different layers of the application.

MVC Architecture of struts

Model: - This layer implements business logic and contains data. This can be created by
using a set of java beans called as form bean. Struts provide a predefined class as the
super class of all form beans.

Controller: - This layer implements controlling logic of the application. It takes decision
to make visible appropriate view to appropriate users. This can be created by using a
controlling servlet and a set of helper class called as form- action. Struts provide a
predefined servlet as the controlling servlet .The controlling servlet receives request from
the users. Struts provide a predefined class as the super class of all form action classes.

23
View: - This layer implements presentation logic. It provides response to the users. This
layer can be created by using a set of Jsp. Struts provides tag libraries for this layer.

Installation of struts

1. Get the copy of struts binary distribution (Struts 1.3.8-all.zip) from


http://struts.apache.org/download.cgi and extract it into any folder of the file
system.
2. Search for all .tld files in extracted folder and makes those files available in WEB-
INF folder of the context.
3. Search for all .jar files in extracted folder and make those files available in lib
folder of the context.

Configuration of struts

Create a configuration file named as struts-config.xml inside WEB-INF folder. This file
contains information about form-bean, form-action, and forwards.

Tips: -

1. Search for struts-config.xml inside extracted folder of struts. Copy that


file to make available in WEB-INF folder of the context. Open this file and
remove all the tag present between <struts-config></struts-config>
2. Deploy the controlling servlet by using the required in WEB-INF. Name of the
controlling servlet is org.apache.struts.action.Actionservlet. This servlet must
accept the name of the configuration file by using an initial parameter named as
config. This servlet must be a permanent servlet. This servlet must have an url-
pattern to receive all types request.

<servlet>
<servlet-name>x</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>x</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Creating a form based application in struts

Requirements

1. Create the Jsp to contain the form.


2. Create a form-bean to contain values of form fields.

24
3. Create a form-action to validate input of user and to provide appropriate forwards
names to controlling servlets.
4. Provide information in struts-config.xml.
5. Create page for each forwards.

Creation of form bean

1. Create a class in a package by inheriting org.apache.struts.action.ActionForm.


2. Provide variables in the form-bean class as the properties.Name of these variables
must match with the value of property attributes present in form field tags.
3. Provide setter and getter methods for each of the property.
4. Optionally override reset () method to provide default values to the properties.

Creation of form action

1. Create a class in the same package where form-bean exists and this class must
inherit org.apache.struts.action.Action class.
2. Override execute () method to implement validation logic and to return a
forward.Return type of this method must be org.apache.struts.ActionForward.This
method accept four parameters as follows below.

a. org.apache.struts.action.Actionmappings:- This represents all forward name


and present in struts-config.xml and helps to create object of actionforward.

b. org.apache.struts.action.Actionform:- This represent form bean.

c. javax.servlet.http.HttpServletRequest:- This represent user request.

d. javax.servlet.http.HttpServletResponse:- This represent service response.

Compilation of bean and action: -

Compile formbean and action file simultaneously by using servlet-api.jar and struts-core-
1.3.8.jar in classpath.The jar file of struts(struts-core-1.3.8.jar) can be found in lib folder
of the context,after installation of structs.

--- \classes\logs\javac - classpath servlet-api.jar ;struts-core-1.3.8.jar *.java

Here logs is the package folder where we stored both the form bean and fom action files.

Providing information in struts-config.xml file

1. provide information about formbean by using following tags in struts-config.xml


as

<form-beans>
<form-bean name="name to map formbean with form action" type="class name with

25
package name of the form bean" />
</form-beans>

2. Supply information about form-action and forwards by using the following tags in
struts-config.xml file

<action-mappings>
<action name="mapping name specified in formbean" path="value of action attribute
present in from" type="class name of form action" >
<forward name="name of forward used by form action" path="name of the page to be
visible" />
<forward name=" name of forward used by form action " path=" name of the page to be
visible " />
</action>
</action-mappings>

Java JDBC How to - Connect to a remote mysql database


import java.sql.Connection;
import java.sql.DriverManager;
//from ww w .j a va2 s.c om
public class Main {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/mydb";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, "root", " ");
System.out.println("Database connection established");
conn.close();
System.out.println("Database connection terminated");
}
}

26

You might also like