Introduction to JDBC
1. What is JDBC and Why JDBC?
1. There is not abbreviation for JDBC, "JDBC is just JDBC"
The unofficial abbreviation accepted by industry is
"Java DataBase Connectivity"
2. The JDBC is a technology, it is a specification', it is a
contract document between Java application and DBs for
establishing connection between Java program to DB
for performing CRUD operations.
2. What does JDBC provide?
- JDBC provides 'set of classes and interfaces' for connecting to DB
to perform CRUD operations on DB tables.
- The CRUD operations means
DB teminology
C - Create Insert
R - Read Select
U - Update Update
D - Delete Delete
- The CRUD operations are also called as
CURD or SCUD operations
- As per operations order
'CRUD' is the correct acronym
3. What are API and JDBC API?
- API stands for 'Application Programming Interface'
- A predefined library or a set of predefined classes and interfaces
meant for developing our applications with thier functionality
are all together is called API.
- An 'Interface meant for Programming a new Application'
is called API
- A predefined classes and interfaces those are meant
for establishing 'Java to DB Connectivity' are called JDBC API.
4. What are the 4 operations we can perform on DB by using JDBC API?
- By using JDBC API we can perform below 3 operations
1. Connecting to DB
2. Executing SQL queries and PL/SQL procedures
3. Feching the results from DB to Java program
4. Closing connections
5. Different types of queries available in SQL (Languages)?
1. SQL Langagues(DDL, DML, DQL/DRL, TCL, DCL)
1. DDL(Data Definition Laguage)
1. CREATE
2. ALTER
3. RENAME
4. DROP
5. TRUNCATE
...
2. DML (Data Manipulation Langauge)
1. INSERT
2. UPDATE
3. DELETE
4. INSERTALL
5. MERGE
3. DQL (Data Query Langauge)
1. SELECT
4. TCL (Transcation Control Langauge)
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
5. DCL (Data Control Langauge)
1. GRANT
2. REVOKE
2. PL/SQL
1. Functions
2. Procedures
3. Cursors
6. JDBC API providing 'interfaces and classes'
for running SQL queries to perfom CRUD operations?
- JDBC API is organized into 2 packages
1. [Link]
2. [Link]
- [Link] package provides the basic interfaces and classes
for establishing connection to the DB and running SQL queries in DB
- [Link] package provides the eXtesion interfaces and classes
to the [Link] package interfaces for creating connection pool
and advanced resultsets
- below are the list of interfaces and classes
available in above two packages
- [Link] package interfaces and classes
interfaces classes
============= =======
1. Driver 1. DriverManager
2. Connection 2. Types
3. Date
3. Statement 4. Time
4. PreparedStatement 5. Timestamp
5. CallableStatement 6. SQLException
6. ResultSet
7. ResultSetMetaData
8. DatabaseMetaData
9. Blob
10. Clob
11. Savepoint
- [Link] pacakge interfaces
1. DataSource
2. RowSet
7. What is JDBC Driver?
- The database vendor provided set of implementation classes
for JDBC API interfaces is called JDBC driver
- Every database vendor provides separate implementation classes
for JDBC interfaces by calling their specific database
internal C functions
8. What is the difference between JDBC API and JDBC driver?
- JDBC API is a specification provides set of interfaces
- JDBC driver is an implementation of JDBC API interfaces
- We will get JDBC API by installing jdk software
- The JDBC driver is not part of JDK Software either
1. we must download it separately or
2. we will get it by installing database software
9. Java program, JDBC API and JDBC driver architecture?
- Java program access JDBC specification interfaces to invoke
methods
for creating connection, for executing SQL statements and for
fetching
results from the database
- Inside Java program we must not use jdbc driver implementation
class names
directly , then Java program becomes static nature code or
tightly coupled
code specific to one database.
- For example, consider below code
class Test {
public static void main(String[] args) {
Driver driver = new OracleDriver();
Connection con = new OracleConnection();
Statement stmt = new OracleStement();
----
----
}
}
- In the above program we have Oracle DB supplied
implementation classes, then our Java program
can only connects to Oracle DB, tight coupling.
- For changing to other DB, every time we must modify
source code by changing class names to other DB supplied
implememtation classes names
10. How can we make Java program loosely coupled and dynamic with Jdbc
driver
implementation classes?
- Don't create JDBC Driver implementation classes objects directly
in the source code by using new keyword, instead read, load and
instantiate jdbc driver implementation classes dynamically at
runtime
by using 'factory methods'
11. What is a factory method?
- A method that creates object of a class dynamically and
returns this object reference to method caller is called
factory method
- By using a factory method we can create an interface
implementation classes object dynamically without
remembering those implemenation classes names
- JDBC API is also provides factory methods for
each interface separately for creating and
returning those interfaces implementation classes
objects
12. What is the difference between new keyword and factory method?
- via 'new keyword' the object creation is static nature code,
always object is created for the same sub class/implementation
class
Connection con = new OracleConnection();
- always creates only OracleCollection object
- via 'factory method' the object creation is dynamic nature code,
based on the passed name implementation class object is created
Connection con = [Link](db_url);
- getConnection() is a factory method that creates and
returns
object of Connection interface implementation class
dynamically
based on the given data base
13. Factory methods for creating JDBC API implementation classes objects?
1. Driver interface methods
=======================================
1. The Driver interface is the main interface
which is responsible for estalishing connection
to the data base
2. For creating Driver interface implemetation class
we do not any specific factory method
1. Eiter we must create its object directly or
2. we must use Reflection API factoy method
[Link]("DB driver classname");
3. Then by using this driver interface implemtation class
object we can create Connection interface implementation
class object
4. Driver interface provides a factory method for creating
Connection interface implementation class object of
the loaded DB driver
- The method is
public Connection connect(String url, Properties info)
throws SQLException
5. The code for Loading and instantiating driver,
creating connection 'directly with Driver interface'
becomes lengthy and difficulty.
6. To simplify creating Connection interface implementation
class object
we have a factory class DriverManager
2. DriverManager class and its methods
========================================
1. It is a factory class it has static factory methods
to register dirver, creating Connection interface object
- The methods are
- Methods for registing and deregistering drivers
1. public static void registerDriver(Driver driver)
2. public static void deregisterDriver(Driver driver)
- Methods for retrieving all registered drivers
3. public static Enumeration<Driver> getDrivers()
4. public static Stream<Driver> drivers()
- Methods for creating connection with the registered driver
5. public static Connection getConnection(String url)
6. public static Connection getConnection(String url,
Properties info)
7. public static Connection getConnection(String url,
String user, String pwd)
3. Connection interface and its methods
=======================================
- A connection is a Java object
- it is a session between Java program and database
- A connection object contains the connection id specific to this
client application and an associated buffer for running sql
queries and
storing results specific to this client application
- After 'COMMIT' is executed, this client results are stored in
main table
as shown in the above diagram
- To create connection to the database we must use we must pass 4
inputs
related to database in the Java application
1. Driver implementation class name (predefined)
2. DB URL (predefined)
3. DB Schema username (user defined)
4. DB Schema password (user defined)
- Every database has its own specific above 4 values
Oracle DB details
================
Driver_Name: [Link]
DB_URL : jdbc:oracle:thin:@localhost:1521:XE
DB_USERNAME: hknit4pm
DB_PASSWORD: hari
- Program #1: Sample program to connect to Oracle DB
//Test01_Connection.java
import [Link].*;
class Test01_Connection {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException {
//1. Load DB driver implementation class
[Link]("[Link]");
//2. Establishing connection
Connection con = [Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"system", "manager"
);
[Link]("Connection is created");
[Link]("con: "+ con);
}//main method close
}//class close
- Connection object is responsible to create and return
Statement and its sub type Statements objects for sending and
running SQL Queries, procedures, functions and Cursors.
- Connection interface provides factory methods for creating and
returning Statement, PreparedStatement and CallableStatement
interface implementation classes objects
1. public Statement createStatement()
throws SQLException
2. public PreparedStatement prepareStatement(String sql)
throws SQLException
3. public CallableStatement prepareCall(String call)
throws SQLException
- In addition to above three methods connection interface
provides other methods for transction management,
for creating and obtaining blob, clob object, etc...
4. Statement interface and its methods
=======================================
- The statement is a Java object, using which we can send SQL
queries to
the DB and execute them on the Connection object connected data
base.
- We have 2 types of sql queries, functions, procedures and
cursors
- We have three types of statement objects for running queries
functions
procedures and cursors
1. Statement
2. PreparedStatement
3. CallableStatement
- Statement is the root interface of PreparedStatement and
CallableStatement. CallableStatement is the sub interface of
PreparedStatement
1. Statement is used for running static sql statement
means without IN parameters or IN parameters with fixed
values
For example:
SELECT * FROM student;
(or)
SELECT * FROM student
WHERE sno=101;
2. PreparedStatement is used for executing pre-compiled
dynamic SQL
statements means IN parameters with runtime values
For example:
SELECT * FROM student
WHERE sno=?;
(or)
INSERT INTO student(sno, sname, course, fee)
VALUES(?, ?, ?, ?);
3. CallableStatement is used for procedures, functions and
cursors
- Statement interface provides below methods for sending and
executing
queries on DB
1. public boolean execute(String sql) throws SQL Exception
- by using this method we can execute all types of
SQL queries. It may return ResultSet or int value
- if the result is ResultSet, it returns true
- if the result is non ResultSet, it returns false
- This method best suitable for executing
procedures, functions and cursors and DDL, TCL
queries
2. public int executeUpdate(String sql) throws SQLException
- It is used for executing DML queries
- It result o or 1 or more than one based on the
number of rows inserted or updated or deleted
3. public ResultSet executeQuery(String selectQuery)
throws SQLException
- It is used for executing DQL query SELECT
- It returns the ResultSet object which points to
the set of rows queried at DB end
5. ResultSet interface and its methods
========================================
- ResultSet is a cursor object pointing to the results
queried at data base end by running SELECT query
- It feches the results from DB to Java program
- When ResultSet object is created first its cursor
points to 'before first row' (BFR).
- ResultSet interface provides methods
1. for moving cursor from BFR to
first row, then next row, and so on, last row,
after last row (ALR) also
2. it provides methods for retrieving the coloumns
values of each row
- The methods are
1. public boolean next() throws SQLException
- moves the cursor to the next row
- If row presents, return true
else returns false
2. public xxx getXxx(int columnIndex)
public xxx getXxx(String columnLabel)
- here xxx is Java data type name
- byte, short, int, long, float, double
char, boolean, String, Date, Time,
Timestamp,
Blob, Clob, Object, Array
For example:
public int getInt(int columnIndex)
public int getInt(String columnLabel)
- these methods are used for retrieving
column values from this row either
by passing column index or column name
- ResultSet object memory daigram
6. ResultSetMetaData interface and its points
=============================================
- ResultSetMetaData is used for retrieving columns
information of a table whose data is queried
by using the ResultSet object
- It has below methods to columns information
1. public int getColumnCount()
2. public String getColumnLabel(int index)
3. public String getColumnName(int index)
4. public int getColumnDisplaySize(int index)
- The factory method for obtaning ResultSetMetaData object is
avaiable in RestultSet interface, it is
- public ResultSetMetaData getMetaData()
throws SQLException
14. Steps to develop JDBC program to connect and run SQL queries on DB?
1. Loading database JDBC driver
2. Establishing connection
3. Creating statement object
4. Executing SQL query and obtain ResultSet at object
5. Fetching results from database to Java program
6. Closing connections in the reverse creation order
7. Handling SQLException
15. JDBC objects creation flow and dependency?
16. PreparedStatement interface and its methods?
============================================
1. PreparedStatement is a sub interface of Statement interface
2. It is used for executing a precompiled sql statement with
runtime values
3. In PreparedStatement object creation we must submit sql
statement,
but not at the time of execute() method calling
4. For creating PreparedStatement object, in the Connection
interface we
have a factory method called prepareStatement()
public PreparedStement prepareStatement(String sql)
5. By using PreparedStatement we can run both static sql statement
and
dynamic sql statement by giving values at runtime
- A static SQL query is a query, that doesn't take inputs
or contains fixed value/inputs
SELECT * FROM student;
SELECT * FROM student WHERE sno=101;
- A dynamic SQL query is a query that has placeholders(?)
that takes inputs at runtime at the time of query
execution.
We can have multiple placeholders based on number of
values
we want read
SELECT * FROM student
WHERE sno=?;
SELECT * FROM student
WHERE sno=?
AND sname='?'
INSERT INTO student(sno, sname, course, fee)
VALUES(?, ?, ?, ?);
6. Below code shows creating a PreparedStatement object
with a Precompiled dynamic sql statement to insert a record
String insertQuery =
"INSERT INTO student(sno, sname, course, fee)" +
"VALUES(?, ?, ?, ?)";
PreaparedStatement psmt =
[Link](insertQuery);
7. The PreparedStatement interface contains special methods for
setting
values to the placeholders available in the query in this
PreparedStatement object and further to execute this query on DB
1. setter methods
public void setXxx(int placeHolderIndex, xxx value)
throws SQLException
for example
public void setInt(int placeHolderIndex, int value)
public void setDouble(int placeHolderIndex, double
value)
public void setString(int placeHolderIndex, String
value)
public void setDate(int placeHolderIndex, Date
value)
2. executor methods
public boolean execute() throws SQLException
public int executeUpdate() throws
SQLException
public ResultSet executeQuery() throws SQLException
JDBC PROGRAM
//Program #1: Sample program to connect to Oracle DB
//Test01_Connection.java
import [Link].*;
class Test01_Connection {
public static void main(String[] args)
throws ClassNotFoundException, SQLException {
//1. Load DB driver implementation class
[Link]("[Link]");
[Link]("OracleDriver is loaded");
//2. Establishing connection
Connection con = [Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"system", "manager"
);
[Link]("Connection is created");
[Link]("con: "+ con);
}//main method close
}//class close
/*
Compilation and Execution
==========================
1. Save above program with the name Test01_Connection
in the folder "D:\FSJD\04 AJ\01JDBC"
2. Open command prompt pointing to the above folder path
3. we must set classpath to Oracle JDBC Driver software jar file
cmd>set classpath=.;C:\Oracle21c\dbhomeXE\jdbc\lib\[Link]
cmd>javac Test01_Connection.java
|-> Test01_Connection.java
cmd>java Test01_Connection
Output
Connection is created
con: [Link].T4CConnection@5d47c63f
*/
/*
Program #2:
Develop a JDBC program to create a schema(DB user)
with the username hknit4pm with the password hari
Queries: (DDL)
ALTER SESSION SET \"_ORACLE_SCRIPT\"=true";
CREATE USER hknit4pm IDENTIFIED BY hari";
GRANT DBA to hknit4pm";
JDBC method:
boolean execute(query)
*/
//Test02_SchemaCreation.java
import [Link];
import [Link];
import [Link];
import [Link];
class Test02_SchemaCreation {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException {
//loading driver
[Link]("[Link]");
//establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"system", "manager");
//creating statement object
Statement stmt = [Link]();
//executing query for creating schema(user)
[Link]("ALTER SESSION SET \"_ORACLE_SCRIPT\"=true");
[Link]("CREATE USER hknit4pm IDENTIFIED BY hari");
[Link]("GRANT DBA to hknit4pm");
[Link]("Schema is created, permissions are
granted");
//closing connections
[Link]();
[Link]();
}//main close
}//class close
/*
Program #3:
Develop a JDBC program to create a table student
with columns 'sno, sname, course, fee'
in the schema(user) hknit4pm
Query: (DDL)
CREATE TABLE student(
sno NUMBER(4) PRIMARY KEY,
sname VARCHAR2(15),
course VARCHAR2(15),
fee NUMBER(6, 2)
);
JDBC method:
boolean execute(query)
*/
//Test03_TableCreation.java
import [Link];
import [Link];
import [Link];
import [Link];
class Test03_TableCreation {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException {
//loading driver
[Link]("[Link]");
//establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"hknit4pm", "hari");
//creating statement object
Statement stmt = [Link]();
//executing query for creating table
[Link](
"CREATE TABLE student(
" +
" sno NUMBER(4) PRIMARY KEY,
" +
" sname VARCHAR2(20), "
+
" course VARCHAR2(20), "
+
" fee NUMBER(10, 2)
" +
" )
"
);
[Link]("Table is created successfully");
//closing connections
[Link]();
[Link]();
}//main close
}//class close
Program #4:
Develop a JDBC program to insert records in student table
Query: (DML)
INSERT INTO student(sno, sname, course, fee)
VALUEs(101, 'Hari Krishna', 'Full Stack Java', 20000);
INSERT INTO student(sno, sname, course, fee)
VALUEs(102, 'Balayya Babu', 'Acting', 30000);
INSERT INTO student(sno, sname, course, fee)
VALUEs(103, 'Pavan Kalyan Babu', 'Politics', 10000);
JDBC method:
public int executeUpdate(query)
*/
//Test04_InsertRows.java
import [Link];
import [Link];
import [Link];
import [Link];
class Test04_InsertRows {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException {
//loading driver
[Link]("[Link]");
//establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"hknit4pm", "hari");
//creating statement object
Statement stmt = [Link]();
//executing query for inserting rows
[Link](
"INSERT INTO student(sno, sname, course, fee)
"+
"VALUES(101, 'Hari Krishna', 'Full Stack Java',
20000)"
);
[Link](
"INSERT INTO student(sno, sname, course, fee)"+
"VALUES(102, 'Balayya Babu', 'Acting', 30000)"
);
[Link](
"INSERT INTO student(sno, sname, course, fee)
"+
"VALUES(103, 'Pavan Kalyan Babu', 'Politics',
10000)"
);
[Link]("Rows are inserted successfully");
//closing connections
[Link]();
[Link]();
}//main close
}//class close
/*
Program #5:
Develop a JDBC program to seclect rows from student table
display all rows data on console
Query: (DQL)
SELECT * FROM student;
JDBC method:
public ResultSet executeQuery(selectQuery)
*/
//Test04_InsertRows.java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class Test05_SelectingRows {
public static void main(String[] args) //[Link] exceptions
throws ClassNotFoundException,
SQLException {
//1. loading driver
[Link]("[Link]");
//2. establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"hknit4pm", "hari");
//3. creating statement object
Statement stmt = [Link]();
//4. executing select query and obtaining ResultSet object
ResultSet rs = [Link]("SELECT * FROM student");
//5. featching results from DB to java program and printing on
console
while([Link]()) {
int sno = [Link](1);
String sname = [Link](2);
String course = [Link](3);
double fee = [Link](4);
[Link](sno + "\t"+sname+"\t\
t"+course+"\t"+fee);
}//while close
/*
rs-----> BFR [Link]() -> moves cursor to next row->
returns true (r1)
|---> row1 101 HK FSJD 20000 ->
returns true (r2)
|---> row2 102 BK Acting 30000 ->
returns true (r3)
|---> row3 103 PK polotics 10000 -> returns
false(r4)(exit loop)
|--------> ALR
*/
//6. closing connections
[Link]();
[Link]();
[Link]();
}//main close
}//class close
Program #6:
Develop program to display a table columns names and rows data\
Query: (DQL)
SELECT * FROM student;
JDBC method:
public ResultSet executeQuery(selectQuery)
public ResultSetMetaData getMetaData()
*/
//Test06_ColumnsAndRows.java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class Test06_ColumnsAndRows {
public static void main(String[] args) //[Link] exceptions
throws ClassNotFoundException,
SQLException {
//1. loading driver
[Link]("[Link]");
//2. establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"hknit4pm", "hari");
//3. creating statement object
Statement stmt = [Link]();
//4. executing select query and obtaining ResultSet object
ResultSet rs = [Link]("SELECT * FROM student");
//Obtaining ResultSetMetaData object
ResultSetMetaData rsmd = [Link]();
int numberOfColumns = [Link]();
for(int columnIndex=1; columnIndex<=numberOfColumns;
columnIndex++){
[Link]([Link](columnIndex) +
"\t\t");
}
[Link]();
//5. featching results from DB to java program and printing on
console
while([Link]()) {
int sno = [Link](1);
String sname = [Link](2);
String course = [Link](3);
double fee = [Link](4);
[Link](sno + "\t"+sname+"\t\
t"+course+"\t"+fee);
}//while close
//6. closing connections
[Link]();
[Link]();
[Link]();
}//main close
}//class close
Program #8:
Develop program to update Adv Student's course as Adv Java, HTML
*/
//Test08_UpdateRows_Pstmt.java
import [Link];
import [Link];
import [Link];
import [Link];
class Test08_UpdateRows_Pstmt{
public static void main(String[] args)
throws ClassNotFoundException,
SQLException {
//1. loading driver (optional from JDBC 4.0 onwards with feature
'Auto Loading'
//[Link]("[Link]");
//2. establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"hknit4pm", "hari");
//3. creating PreparedStatement object
PreparedStatement pstmt =
[Link](
"""
UPDATE student
SET course=?
WHERE course=?
"""
);
//4. executing the query available in psmt
//1. set values to pstmt
[Link](1, "Adv Java, HTML");
[Link](2, "Adv Java");
//2. execute pstmt
int noOfRowsUpdated =
[Link]();
[Link](noOfRowsUpdated+ "
student(s) data is updated");
//5. closing connections
[Link]();
[Link]();
}//main close
}//class close
/*
Program #9:
Develop program to delete rows from the table
based on the course value given from keyboard
*/
//Test09_DeleteRows_Pstmt.java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class Test09_DeleteRows_Pstmt{
public static void main(String[] args)
throws SQLException {
//1. establishing connection
Connection con =
[Link](
"jdbc:oracle:thin:@localhost:1521:XE",
"hknit4pm", "hari");
//2. creating PreparedStatement object
PreparedStatement pstmt =
[Link](
"""
DELETE FROM student
WHERE course LIKE ?
"""
);
//3. set values to pstmt
Scanner scn = new Scanner([Link]);
[Link]("Enter course to delete: ");
[Link](1, "%"+[Link]()+"%");
//4. executing the query
int noOfRowsDeleted = [Link]();
[Link](noOfRowsDeleted+ " student(s) data is
deleted");
//5. closing connections
[Link]();
[Link]();
}//main close
}//class close
WORKING WITH ECLIPSE
Working with IDE and Eclipse
====================================================
1) What is an IDE, Why IDE and Adv of IDE?
2) What are the popular IDEs?
3) What is eclipse?
4) Why eclipse?
5) How to install and start eclipse?
7) What is a workspace, what is a perspective, what is a project?
8) Diff implicit configuration folders and files created by eclipse and
their purpose?
9) Diff types of projects we can create in eclipse?
10) Downloading JDK latest version plugin from eclipse market place?
11) Developing a Java project with class and interface?
12) Compiling and Running a class using eclipse?
13) Running a class by reading runtime values as command line arguments
and from Scanner?
14) Diff short cuts to work with eclipse?
15) Debugging project in eclipse?
==============================================================
1) What is an IDE?
- An IDE stands for Integrated Development Environment
- The IDE is an editor software that provides an evironment to
develop projects
by integrating to different softwares which are used as part of
this project
- That means IDE provides connectivity to different sotwares from
the same editor window.
- We no need to open each software in separate window those we are
using in our project
- IDE provides fast development
2) What are the advantages of IDEs?
1) it gives code help (less typing, more choosing)
2) automatic compilation of the code
3) automatic importing packages
4) easy to copy paste and moving lines
5) auto generation of code (fields, constructors, methods,
condition, loops, try, catch, finally, throws, etc...)
6) easy debugging means we can easily track the flow of execution
and we can find bug
7) we can connect to diff sotwares from this IDE editor
8) fast development
9) time and money is saved
3) Popular IDEs for Java application development?
1) Eclipse IDE
2) STS
3) IntelliJ IDEA
4) Working with Eclipse?
1) What is eclipse?
- An eclipse is an IDE software
- It is an text editor software
- It is an open source software (freely avilable to
download, we can get its source code and
even we can also involve in its features
development )
- It is meant for developing projects more faster with less
typing
2) Why Eclipse?
- for fast develop with ease and less efforts
3) How to install eclipse?
1) download eclipse from "[Link]/downloads"
2) click on "Download Packages" (don't click download
button directly)
3) click "Eclipse IDE for Enterprise Java Developers"
4) click "Windows x86_64"
5) you will find "[Link]" file is downloaded into your
system
6) extract it to "C:\" drive by using winrar software
7) eclipse installation is completed.
4) How to start eclipse, choosing workspce and perspective?
1) go to eclipse installed folder "C:\eclipse"
2) double click "[Link]" file
3) select workspace directory*
4) click "Launch" button
5) eclipse is started and welcome page is opened
Q) What is a workspace and what is the use of it?
- A Workspace is a folder where you want to store
projects.
- It is used by eclipse for storing all plugings,
and setups we are doing for this workspace
- When we launch eclipse next time it starts eclipse
by loading the setups we saved in this workspace
- To identify a folder as workspace, in this folder
eclipse creates
a directory with the name ".metadata".
- In this folder eclipse stores all plugins and the
setups we are doing for this workspace.
Note: Do not delete this folder, it is not a
virus folder
- If you delete this folder, eclipse can not
recognize your folder as workspace
- All setups and projects you created earlier
are not loaded into eclipse
5) Creating project
- Click "create project"
- Click "Java project" -> Next
- Enter project name: Test
- Choose Execution environment: Java SE 21
- Uncheck Module-info check box
- Click Finish
- Click Open Java Project perspective
6) Project folder stuctrue
A new project with the name "Test" is created
- verify its structure in the workspace folder
- you will find
1) src folder -> contains .java files
those we are creating from eclipse
2) bin folder -> contains .class
files those are compiled from .java files
3) .settings folder -> contains the setting
we did for this project
4) .classpath file -> contins the jars
information those attached to this poject
5) .project file -> contins
information above this project to load when eclipse is started
Note: if we delete any of above folders or files
your project will not work from eclipse
7) Developing a class in eclipse?
1) right click on src folder in Test project
2) click "class"
3) enter class name: Test
4) click main method chck box
5) click finish
7) add [Link]("Hi"); in main method
8) Compiling and running a class from eclipse
1) In eclipse every class is auto compiled and
.class is saved in bin folder
2) We no need to compile but we must execute
3) We have 4 options to run java class in eclipse
1) By using "Run button" available in images bar
2) Right click on editor any where -> click "Run As"
-> click "Java Application"
3) In package explore view -> Right click on .java
file -> click "Run As" -> click "Java Application"
4) Short cut -> press (Ctrl + F11) (or) (Ctrl + fn
+ F11)
9) Changing font
1) for just increasing and decreasing font size
- press ctrl ++ and ctrt --
2) for changing font name, font style and font size
- click window menu
- click Preferences menu item
- click General -> Appearances -> Colors and Fonts
- double click basic -> scroll down -> select Text
font
- click Edit button -> select the font name, font
style, font size
- click "Apply and close" button
10) Showing compiler and JVM errors and exceptions
- shows compile time errors with red color mark
- shows exception in console window, click on line number
hyper link showing in this exception message
to goto the line number directly in this Java file
13) Running Java program in eclipse with command line arguments
cmd>java Addition 10 20
Editplus
-> Tools
-> Configure User Tools
-> Select JVM
-> Argument
-> place $(prompt) at end
Eclipse
1) Right click on editor any where
2) Click "Run As"
3) Click "Run Configuration"
4) Click "Arguments" tab
5) Enter arguments with space separator
6) Click Run
14) Short cuts to work with eclipse
=====================================
To open short cut keys list
ctrl + shift + L
For Changing Eclipse short curts
Window -> preferences -> keys
=====================================
for code drop down --> ctrl + space
for filtering code --> type some
partial text --> press ctrl + space
for generating main method --> type main
--> press ctrl + space
for adding [Link]() -->
sysout/sys/syso/sout + (ctrl + space)
for adding [Link]("trace") -->
systrace/sys/syst/strace + (ctrl + space)
for adding [Link](); -->
syserr/sys/syse/serr + (ctrl + space)
For executing --> ctrl +F11
For commting & uncommenting one line ctrl +
shift + c -> SLC
For comming & uncommenting multiple lines ctrl
+ /, / -> SLC
For comming & uncommenting multiple lines ctrl +
shift + /, \ -> MLC
For adding doc comment
alt + shift + j -> DocC
For indentation for one line ctrl + i,
For indentation for all lines ctrl + A then
ctrl + i
For formatting ctrl + shift +
f,
For Duplicate line(C and P) ctrl + alt +
down arrow/up arrow
|-> For disabling hot keys on windows
|-> Right click on desktop ->
Graphics options -> Hot keys -> Disable
For Moving line down and up alt + down
arrow, alt + up arrow
For deleting complete line ctrl + D
For deleting next word ctrl +
Delete
For deleting previous word ctrl + Backspace
For converting to upper case ctrl + shift + X
For converting to lower case ctrl + shift + Y
For finding the selected word occurrences ctrl +
shift + K
For minimize and collape the a method block ctrl +
shift + / * on number pad
For creating a class or interface or enum or package
-> ctrl + N
For quick fix/for generating class, field,
constructor, method -> ctrl + 1
Right click -> Source ->
For generting constructor alt +
shift + s, o, enter
For generting getter and setter
alt + shift + s, r, alt+a, alt+r
For generting toString
alt + shift + s, s, enter
Right click -> Refactor -> Rename (alt + shift + r)
For replacing a PE dec name alt +
shift + r
in the entire project(refactoring)
Moving to next Editor cltr + page down
Moving to previous Editor cltr + page up
for chaning editors ctrl + f6 +
"hold ctrl" -> keep pressing F6 for selecting editor -> release ctrl
For chaning views ctrl + f7 +
"hold ctrl" -> keep pressing F7 for selecting view -> release ctrl
For changing perspecitives ctrl + f8 + "hold ctrl"
-> keep pressing F8 for selecting perspective> release ctrl
Note: if you "leave ctrl" key after function key
pressed, previously opened editor, view and perspective will be opened
Attach source code to eclipse -> place cursor
on [Link] or method
-> press F3 -> Click Browse ->
-> select JDK-16\lib\[Link]
For opening source code F3 or
ctrl + mouse click
For going to prev and next alt + <- / ->
For opening API Doc F2
open particular type ctrl +
shift + t
For adding import statements ctrl + shift + o
for working line number tab ctrl + F10
For running a class ctrl +
F11 (if main method is not available in this class,
previously executed class is executed)
For closing editor ctrl +
F4
For closing editor ctrl + w
For closing all editors ctrl +
shift + w
Summary on function keys:
f1 -> help menu will be opened
ctrl + F1 -> same work [help menu will be
opened]
f2 -> for showing PE Dec &API Documentation -> place
curson on PE -> press F2
ctrl + F2 -> do nothing
f3 -> for opening source code of a PE -> place
curson on PE -> press F3
ctrl + F3 -> for opening PE outline
f4 -> for opening type hierarchy (for seeing its
super classes and its members at a time)
ctrl + F4 -> editor is closed
f5 -> for refreshing project (this project
modifications are loaded from HD to eclipse)
ctrl + F5 -> do nothing
f6 -> do nothing
ctrl + f6 -> shows all editors
f7 -> do nothing
ctrl + f7 -> shows all views
f8 -> do nothing
ctrl + f8 -> shows all perspectives
f9 -> do nothing
ctrl + f9 -> opens active task window to
select a task
f10 -> selecting menus(like pressing alt)
ctrl + f10 -> shows line numbers bar
shortcuts
f11 -> Program is executed in debugging mode
ctrl + f11 -> program is executed normally
and output is displayed
f12 -> do nothing
ctrl + f12 -> opens active task window to
select a task like as ctrl + f9
Setting build path (eclipse classpath)
-> Right click on project
-> Build Path
-> Configure Build path
-> Click Libraries, Select classpath
-> Click Add External Jars
-> Select jar file from the required software
-> Click Apply and Close button
-> this jar will be shown under your project explorer
-> under Referenced libraries
For changing compiler/JRE system
-> Right click on project
-> Build Path
-> Configure Build path
-> Project Facets
-> Click on Runtimes
-> Unselect jdk check box
-> Under Facets selct Java version number
-> Click Apply and Close
Installing JDK software:
=================
1) Go to [Link] -> search JDK 14 download -> click second link
2) Click JDK download
3) Click Windows [Link]
4) Double click the downloded exe file
5) Click Next
6) Click Change button -> remove "\program files\Java"
and make installation path as "C:\jdk-14.0.2"
7) Click Next -> Close/Finish
*** jdk-14 is installed in C:\jdk-14.0.2 folder
*** this jdk-14.0.2 is called JAVA_HOME
Different types of files exist in a software
==============================
When we install any software we will get two types of files
1) binary files
2) library files
- binaray file is a command file using which we can run the current
software
and also we can run other programs by using this software.
- library file is a program file it contains logic to perform one
operation
and by using it we can develop our own programms.
- The library files are also called as API(Application Programming
Interface)
- by default binary files are stored in "bin" folder
- by default library files are stored in "lib" folder
Some times we need to access and run a software binary and library files
from outside of this software installed directory from other
folders from command prompt
Ofcourse we can not access them by default, because command prompt
software does not know
the path where those binary and library files are available in this system
We must tell to OS/cmd prompt the path of binary and library files.
For this purpose we must create some variables inside OS
for finding a software installed directory, its binary and library files
those variables are technically called environment variables.
About environment variables
====================
A variable that is created inside OS for finding
a Software installed directory, its binary and library files is
called env variable.
For Java software we have four env variables
1) JAVA_HOME
2) path
3) classpath
4) module-path
- JAVA_HOME is used for finding JDK software installed directory
- path is used for finding ANY software binary files
- classpath is used for find library files of JDK software, our
project and Java related other sofwares classes
- module-path is used for finding modules of JDK software, our
project and Java related other sofwares modules
Note:
1) JAVA_HOME, classpath and module-path are specific to Java software
where as path is common to all softwares we are installing in the
system, including OS
Who does use above environment variables?
===============================
- JAVA_HOME is set by programmer and it is used by server software (ex:
tomcat)
- *** path is set by programmer and it is used by command prompt software
for finding javac and java tools ***
- classpath and module-path are used by compiler and JVM for finding the
classes and modules
those available in other directories
Which environment variable is mandatory to set?
=================================
- As of now we must set path variable, it is mandatory
because we need to access "javac and java" commands from our
project directory
- We not need to set JAVA_HOME, classpath and module-path, they are
optional.
Diff ways of Setting env variables
========================
We can set env variables in two ways
1) temporarily (at command promopt window)
2) permanently (in system environment variables window)
Temporary settings
==============
1) Open cmd widow
2) run below command
>set path=C:\jdk-14.0.1\bin;-------;--------;-------;%path%
(Donot show your typing talent, Copy and
Paste path values )
Commands we use in setting env var temporarity
1) set -> creating and
updating env variable
2) ; -> separating
one software path to another s/w path
3) %evn var% -> for retrieving
existing value of this env var
4) echo %evn var% -> for printing this
env variable value
The "set command" based setup is called temporary, because
those setups are available
only for this command prompt window. Once this command
prompt window is closed
all setups are lost. we must do same setups repeateadly
every time when new cmd window opened
Solution: permanent setup
Permanent setups:
=============
1) Copy the JDK software "bin" folder path
2) Right Click on "This PC"
3) Click "Properties"
4) Click "Advanced System Settings"
5) Click "Envinorment Variables"
6) In System Variables section
1) Dobule click "path"
In windows XP, 7, 8
2) Press "Home" key on keyboard
3) Paste the path you copied (ctrl+v)
4) Enter ";"
5) Click "Ok" -> "OK"
6) Close all windows
In windows 10
2) Click "New" button
3) Paste the path you copied (ctrl+v)
4) Click "Move Up" and bring "Java path" as first
path
5) Click "Ok"
6) Close all windows
Rule: JDK path must be always first in path variable value
because other software(ex: Oracle) also contains inbuild
JDK
If we place our JDK path at end in path variable value,
our JDK will not be used in compiling and executing
our class.
OS searching algorithm for finding binary files
================================
CWD --> if not available -> Path variable -> First Come First Load
(FCFL) (Left -->Right Seaching in path variable)
Q1) In one computer how many JDK softwares can we install?
Mulitiple JDK of diff versions
Q2) If we install mulitple diff versions of JDK from which version
JDK javac and java will run?
CWD or First placed JDK in path variable
(Current Working Directory)
Q3) How can we run Java program with different versions?
- set one JDK path in permanent path, which you want to use
always
- set another JDK path in temporary setting in cmd window
which you use for one time
Q4) If there are two JDK paths are stored in path variable, which
JDK will used?
- First placed JDK
Q5) In path variable, I have placed jdk-14 version path,
and in cmd window, I have changed path (CWD) to jdk1.7,
then which version javac will be used?
- 1.7 vesion will be used (first priority to CWD)
Q6) Can we set mulitple JDKs in Permanent Path?
- Yes, but no use, because it follows FCFE
- If we palce mutiple JDKs in PP no problem
but only first placed JDK is used.
Q7) We never to set path for game software to run,
why do we need to set path for JDK to run?
- We no need to set path for game software,
because we do not run game software binary files
from cmd window
- We must set path for JDK,
because we need to run javac and java from cmd
window from our
project directory
Q8) Summary: When, we must set path for any software?
- if we need to access any software binary files
from cmd prompt window from outside of software
installed directory
we must set path.
- If we no need to access a sotfware binary files from cmd
window
from other directories, we no need to set path
Q9) Can we run javac and java like game software?
- not possible because they are not GUI based programs
- they are CUI based programs, they must be executed only
from cmd promt window
- GUI means Graphical User Interface, a separate
window will open
- CUI means Console User Interface, a separate
window will not there
to run it needs console to run means cmd
window
Q10) If we develop programs by using IDEs (Eclipse, MyEclipse,
Netbeans, intelliJ, JBuilder, etc...)
do we need to set path, classpath?
- No, not require
- IDE will take care of all required setup
IDE -> Integraged Development Environment
It is editor software, which has advanced features
for fast development
SERVLET NOTES
Java Platforms, Java SE and Java EE technologies
=================================================
1. What are the Java platforms?
2. Difference between Java SE and Java EE?
3. Java EE architecture and version history?
4. Different applications and technolgies for developing these
applications?
Introduction to Server softwares
=================================================
5. Server software and types of server softwares?
- A software that runs web and enterprise applications
by taking request from remote clients through network
is called server Software
- A server software is installed in server computer. We can also
install it
in our client computer for testing web applications locally
- We have two types of server softwares
1. Web Server
2. Application Server
- A Web server is a Java EE implemented server software
that executes web technologies Servlet and JSP.
The Web server contains 2 containers
1. Servlet container -> for running servlet program
2. JSP container -> for running JSP program
- An application server is also a Java EE implemented server
software
that executes both web and enterprise technologies Servlet, JSP
and EJB
An application server contains 3 containers
1. Servlet container -> for running servlet program
2. JSP container -> for running JSP program
3. EJB container -> for running EJB program and
middleware services
- The popular Java EE Web Server is 'Tomcat'. It is provided by
'Apache'
company. The Apache is a open source company it has provided many
softwares(tools) for Java applications development.
- The popular Java EEE application server is 'Web logic'. It is
provided by
'BEA' company. It is sold to Oracle Company later. Weblogic is
not open
source it is commercial, we must buy license to use.
6. Downloading and installing Tomcat Server?
1. Abount Tomcat
- For running servlet and JSP programs we need web server Tomcat
- The Tomcat Web Server is a open source software
it is a freely available to download and use.
- The latest version of Tomcat is 11
It supports JDK 17 version, Servlets 6.1v, JSP 4.0.
- For more details on Version numbers refer '[Link]'
site
2. Downloading and installing Tomcat 11.0.0
1. Open browser
2. Search download Tomcat 11
3. Click on first link 'Apache Tomcat 11 download'
4. Scroll down -> click zip/windows zip file link
5. Tomcat software is downloaded
6. Click or double click [Link] file
7. Open with winrar software
8. Extract to C:\ drive
9. That's it Tomcat is installed
10. The Tomcat software HOME directory is "C:\apache-tomcat-11.0.0"
7. Changing Tomcat server port number?
- Every server software runs on one unique port number
- A port number is a integer number uising which a server software
is
identified in the network and receives the request from client
software
- Every server software should have separate unique port number
- No two server software run on same port
- The Tomcat Server default port number is 8080
- It is a good practice changing the port number to our own unique
port
For example 9090
- Tomcat has three port numbers
1. Startup port number (8005)
2. Shudown port number (8005)
3. Connector port number (8080)
- Change above port numbers as below
1. open tomcat folder (C:\apache-tomcat-11.0.0)
2. open 'conf' folder
3. open '[Link]' file by using notepad or editplus
4. find (press ctrl+f) 'port' and replace
8005 as 9005
8080 as 9090
save file, thats all port numbers are changed
8. Starting Tomcat server
- To run webapplications we must start tomcat server
- To start tomcat sever we must run '[Link]' file
- Rule: To start and run tomcat, tomcat needs JDK installed folder
path
- For providing JDK installed directory path we must set an
environment variable 'JAVA_HOME' for tomcat
- open cmd prompt with folder path
C:\apache-tomcat-11.0.0\bin
- set JAVA_HOME and then run '[Link]' file as below
[Link]
C:\apache-tomcat-11.0.0\bin>set JAVA_HOME=C:\jdk-21
C:\apache-tomcat-11.0.0\bin>[Link]
--------
--------
--------
--------
--------
tomcat server is started
9. Accessing tomcat server from browser
1. open browser
2. type below url and press enter
[Link]
then tomcat server home page is displayed
10. Tomcat server software folder structure
Introduction to Servlets and Servlet
=================================================
1. What is a Servlets and why Servlets?
- A Servlets is a Java EE technology, it is a web technology
specification
- it is used for developing a web application or a web site.
2. What is a Servlet and why Servlet?
- A Servlet is a Java program that runs in a web server in server
computer
- It is used for developing server side program as part a web
application
- A Servlet is used for processing a web request and generates
response
with the inputs sent from web client (Browser)
- A Servlet is used for executing our business appliation as an IA
- A Servlet program is a replacement for main method class
for executing business logic of an application via network call
as IA
- A main method class can execute blogic of an application
as SA within the same system from cmd prompt with 'java'
command
- A Servlet class can execute the same blogic of an
application
as IA from remote system from browser with an 'url'
3. What is Servlets API?
- A set of classes and interfaces those are used
for developing a web application is called Servlets API
- A Servlet API classes and interfaces are organized into 3
packages
1. [Link]
2. [Link]
3. [Link]
- From Tomcat 10 onwards the package names are changed to jakarta
1. [Link]
2. [Link]
3. [Link]
- The package '[Link]' provides classes and interfaces
for developing 'basic Servlet' program common to all protocols
- The package '[Link]' provides classes and
interfaces
for developing 'http protocol based Servlet' program
- The package '[Link]' provides annotations
to develop servlet with annotations. It eliminates XML files
usage.
- The Servlets API interfaces and classes are provided SUN
and their implementation classes are provided by Web server and
Application servever vendor like Apache, Weblogic
(BEA/Oracle),...
- The above vendors provides thier implementation classes
as jar files. We can get them by installing server software
or we can download those jar files separately.
- Below diagram shows above points
4. Servlets API classes and inerfaces?
5. How can we get Servlet API and its implementation classes?
- By installing server software (ex: Apache Tomcat)
- Both Servlet API classes and interface
and Servlet API interfaces implementation classes
are provided by server vendor as jar file(ex: Apache)
- In Apcahe tomcat server software we have Servlet API and
its implementation classes in [Link] file
6. Setting classpath to Servlet API?
- Just by installing server software we can not access
Servlet API interfaces and classes in our program.
- We must set classpath to the Servlet API jar file path
given by the Server vendor
- For accessing Apache Tomcat [Link] file,
we must set classpath as below
cmd>set classpath=.;C:\apache-tomcat-11.0.0\lib\servlet-
[Link]
- If we don't set classpath, we will get compile time error
CE: package [Link].* not found
CE: can not find symbol Servlet
7. Steps to develop servlet program?
1. Develop a packaged public class deriving from
Servlet interface or GenericServlet class or HttpServlet class.
2. Override Servlet life-cycle method 'service(req,resp)'
and place the request processing logic (vals and cals)
3. Configure this servlet class name in [Link] file
The [Link] file is called Deployment Descriptor file.
It contains Servlet class name mapped with url-pattern
using which this servlet class is requested from web browser.
It also contains Web Application and Servet initilaization
valaues
and many other configurations like filters, listeners, ...
4. Set classpath to Servlet API jar file provided by
the Servler vendor (ex: tomcat server - [Link])
5. Compile Servlet class
6. Create WAR file with this project (optional)
7. Deploy(copy) project into server software
for example in tomacat we must copy into 'webapps' folder
8. Start server, send request from browser by using servlet url
The serlvet url-pattern
protocol://ip:port/projectname/servlet-url-pattern
For example
[Link]
servlet-url-pattern
mapped in '[Link]' file
8. Web application folder structure?
- A web application folder is divided into 2 parts
1. Front-end execution programs
2. Back-end execution programs
- The division is done by a folder named 'WEB-INF'
- The files available outside 'WEB-INF' folder
are front-end execution programs, they are
downloaded into brower and executed in client system
- The files available inside 'WEB-INF' folder
are back-end execution programs, they are
executed in server computer only output is
sent to browser as response to display on client system.
- The web appliction folder structure looks as below
+ Project Folder
|- html files
|- jsp files
|- image files
|
|- WEB-INF
|- classes
| |- servlet programs (*.java,
*.class)
| |- core java programs (*.java,
*.class)
| |- jdbc programs (*.java,
*.class)
|
|- [Link]
9. Servlet programs