Java comes in 3 editions
i)JSE(java standard edition(core java)).
ii)JEE(Java Enterprise Edition(Advanced java)).
This is used to develop web applications.
iii)JME(java micro eiditon).
This is used to develop mobile apps.
oop[object oriented programming]
--------------------------------
An oop consists of the following features
i)object
ii)class
iii)encapsulation
iv)abstraction
v)inheritnace
vi)polymorphism
vii)Message passing
viii)dynamic binding
object
------
An object is a real world entity.
An object is an instance of a class i,e it allocates memory for a class.
syntax
------
ClassName referenceName=new ClassName();
An object consists of
i)Properties
ii)Actions
Properties
----------
Properties are used to identify an object.
ex:
name
color
height
weight
etc
Actions are used to perform a task.
ex:
sleeping()
eating()
reading()
etc
ex:
Person-->object
Properties--> name
color
height
weight
Actions---->sleeping()
---->reading()
---->eating()
we represnt properties in a program using variables.
ex:
Sting name;
String color;
etc
we represent actions in a program using methods.
void read()
{
//...
//..
}
void display()
{
//..
//..
}
class
-----
A class is blue print of an object.
A class describes about object.
A class is collection of variables and methods.
syntax
------
acessmodifier class ClassName
{
variables;
methods;
}
steps for implementing class and object
---------------------------------------
step1:declare a class
accessmodifier class ClassName{
//variables
//methods
}
step2:create object for a class.
ClassName referenceName=new ClassName();
step3:Accessing members(variables and methods) of a class
referenceName.membername
Pojo[Plain old java object]
---------------------------
It is simple java class which follows certain standards.
It consists of private properties and public setter and getter
methods.
It have a zero argumment default constructor.
It should implement Serializable interface.
setter and getter methods
-------------------------
A setter is used set value to the property of a pojo.
syntax
------
public void setPropertyName(datatype varname)
{
this.varname=varname
}
getter method
-------------
It returns the value of a property.
syntax
------
public returntype getPropertyName()
{
return varname;
}
ex:
Customer[pojo]
name
cid
mobile
address
age
name[setter and getter]
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
abstract class
--------------
we declare a class as abstract by using the keyword abstract.
syntax
------
accessmodifier abstract class ClassName
{
//statements
}
If we want to declare an abstract method in a class then that class must be declared as abstract.
In an abstract class we can declare both concrete methods and abstract methods.
It is not mandatory to declare abstract methods in an abstract class.
Abstract class cannot be instantiated(cant create object)
The abstract methods of an abstract class must be overridden in a sub class.
Program
-------
package com.satya.jse;
abstract class A
{
abstract void m1();
abstract void m2();
}
class B extends A{
@Override
void m1() {
System.out.println("m1");
}
@Override
void m2() {
System.out.println("m2");
}
}
public class AbstractTest {
public static void main(String[] args) {
B b=new B();
b.m1();
b.m2();
}
}
we can make an application loosely coupled by using the famous jse principle "A super class refernce can refer to a sub class object whereas a sub class refernce cannot refer to super class object."
public static void main(String[] args) {
Shape triangle=new Triangle();
triangle.area();
Shape circle=new Circle();
circle.area();
}
Multiple inheritance using interfaces
-------------------------------------
Deriving a subclass from 2 or more super classes is known as multiple inheritance.
Multiple inheritance is not directly supported in java using classes however we can implement multiple inheritance using interfaces in java.
syntax
------
interface I1
{
//
}
interface I1
{
//
}
.
.
class SubClassName implements I1,I2,...
{
//
}
package com.satya.jse;
interface I22 {
void m1();
void m2();
void m3();
}
abstract class I1I2Impl implements I22 {
@Override
public void m1() {
System.out.println("m1");
}
}
class SubClass extends I1I2Impl {
@Override
public void m2() {
System.out.println("Druva");
}
@Override
public void m3() {
System.out.println("Kaidi150");
}
}
public class MulTest {
public static void main(String[] args) {
I22 i=new SubClass();
i.m1();
i.m2();
i.m3();
}
}
JEE[java enterprise edition]
----------------------------
A Jee is used to develop web applications.
A web(internet) Application is application which runs on a network
ex:
banking Applications,
insurance applications,
medical applications etcJ.
JEE is collection of Api's
API[Application programming interface]
An Api is collection of packages
Package:
A package is collection of
classes
interfaces
enum
Jdbc[java database connectivity]
--------------------------------
We can maintain data in the following ways
i)variable
ii)objects
iii)files
iv)database
Variables,objects are used to maintain data temporarily.
Files,databases are used to maintain data perminently.
Files
-----
Evnn though we can maintain perminently using files ,there are certain limitations with files.
i)Maintainence become difficult with files i'c performing operations like
insert
update
delete
becomes difficult.
ii)Files are not secured.
iii)Files can used for only maitaining data of small scale applications like simplegames,super market s/w etc
iv)Files doesn't support medium scale and large scale applications.
Database
--------
A database is coolection of tables.
A table is collection of rows(touples).
A row is collection of fields(cols).
we use a language sql to perform operations on a database
sql[structure query language]
we use 2 types of sql commands
i)DDL[data definition language]
ii)DML[data manipuation language]
DDL is used to perform
i)create
ii)alter
iii)drop operations
create
------
create command is used to create database/table/view/index/sequence.
syntax of table
----------------
create table tablename(col1 datatype primary key,col2 datatype,.....);
ex:
create a table employee
-----------------------
name--varchar(size)
id--int
sal--double
dept--varchar(size)
desi--varchar(size)
create table employee(
id int primary key,
name varchar(20),
sal double,
dept varchar(20),
desi varchar(20));
primary key
-----------
A primary key is a constraint/condition applied on a column,
A primary key ensures that the data of a column is unique and not null.
syntax
------
colname datatype primary key.
ex:
id int primary key.
alter
-----
alter command alter the structure of a table by
adding a column
modifying a column
dropping a column
add a new colum to a table
--------------------------
syntax
------
alter table tablename
add colname datatype
ex:
alter table employee
add address varchar(30);
Modifying column of a table
---------------------------
alter table tablename
modify colname datatype
ex:
alter table employee
modify sal float;
dropping column of a table
--------------------------
alter table tablename
drop colname;
ex:
alter table employee
drop address;
drop
----
This command is used to drop a database/table/view/index/sequence.
syntax
------
drop table tablename;
ex:
drop table employee;
Data Manipulation language
--------------------------
A DML is used to manipulate data in a table.
we have the following dml command
insert
update
select
delete
insert
------
An insert command will insert a row into a table.
syntax
------
insert into tablename values(value1,value2,.....);
ex:
insert into employee values(1,'manohar',1000.00,'training','trainer');
update
------
update is used to update a col or cols of a table.
syntax
------
update tablename set colname=value where condition;
ex:
update tablename set colname=value where condition;
or
update tablename set colname1=value,colname2=value,... where condition;
ex:
update employee set sal=3000.00,desi='sr.trainer' where id=1;
select
------
A select command is used to select or retrive data from a table.
syntax1
-------
selecting a single column from a table.
ex:
select name from employee;
syntax2
-------
selecting partial row from a table.
select col1,col2,.... from tablename;
ex:
select name,sal from employee;
syntax3
-------
select *from employee;
delete
------
delete is used to delete data from cols of a row or to delete a row itself.
syntax
------
delete from tablename;
ex:
delete from employee;
Jdbc
----
A jdbc is an api used to connect to a database from a java application(program).
We can execute sql queries,stored procedures,functions etc from java program using jdbc.
A jdbc api provides 2 types of packages.They are
i)java.sql.*;
ii)javax.sql.*;
Application Architecture types
i)2 tier
ii)3 tier
iii)n tier
2 tier architecture
-------------------
A 2 tier architecture typically comprises of 2 layers
i)client[Java Program/browser].
ii)server(database/application).
client --------->database.
JP/B
3 tier architecture
-------------------
A 3 tier architecture typically comprises of 3 layers
i)client[Java Program/browser].
ii)application server
ii)database server(database/application).
client------>applicationserver-------->database.
n tier architecture
-------------------
An n tier architecture consits of mutiple servers in the middle layer.
client--->AS1--->AS2......----database server.
Jdbc Api
--------
A jdbc api consists of the follwing interfaces and classes
i)Connection(java.sql.*)(I)
ii)Statement(")(I)
iii)PreparedStatement(")(I)
iv)CallableStatement(")(I)
v)ResultSet(")(I)
vi)DatabaseMetaData(")(I)
vii)ResultSetMetaData(")(I)
viii)RowSet(javax.sql.*)(i)
ix)SavePoint(")(I)
x)SQLException(java.sql.*)(c)
xi)DriverManager(class).
Driver
------
A driver is a class which is used to establish connection with a database.It is also called as connection software.
A driver is also called a conversion s/w i,e which converts java method calls to database function calls.
There are 4 types of drivers.They are
i)Type1---Jdbc-Odbc bridge driver.
ii)Type2--Java-Native Api driver.
iii)Type3--Middleware driver
iv)Type4--Thin driver
Jdbc-odbc bridge driver
-----------------------
A jdbc-odbc bridge driver converts java method calls to odbc function calls,an odbc driver converts odbc function calls to database function calls.
Advantages
----------
i)It is simple to use.
Disadvantages
-------------
i)Platform dependent[windows]
ii)Low performance[becuase types driver requires no of conversions)
iii)Database client library must be installed on client machine.
iv)Driver must be installed in client machine.
Type2--Java-Native Api driver
-----------------------------
Advantages
----------
It has better performance than type1 driver
Disadvantages
-------------
We need to install database client libraries on client machine.
Platform dependent.
Type3 --Middleware driver[pure java driver]
-------------------------------------------
Advantages
----------
It is a pure java driver
Platform independent.
Provides best performance
No need installing database client libaries on client machine
It supports middleware applications.
DisAdvantages
-------------
It requires network support.
It has latency(time delay) issue[because java calls are converted to middle ware calls]
It is expensive.
It requires database specific code because middleware server interacts with different databases.
Type4-Thin driver
-----------------
Advantages
----------
It is a pure java driver.
Best performance.
It converts java calls to database calls directly that is why we call this driver as thin driver.
Opensource.
Disadvantage
------------
Database dependent i,e we should a seperate driver for each database.
steps to connect database using jdbc
------------------------------------
step1:Loading driver
we load driver into memory by using a static method called forName available in java.lang.Class.
syntax
------
Class.forName("driver classname");
ex:
type1--sun.jdbc.odbc.JdbcOdbcDriver.
type2--oracle.jdbc.driver.OracleDriver.
type4--oracle.jdbc.driver.OracleDriver.
type4-com.mysql.jdbc.Driver.
ex:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
forName
-------
It is a static method in java.lang.Class.
It throws a checked exception ClassNotFoundException
It returns an object of java.lang.Class.
step2:Establishing connection with db
DriverManager[class]
--------------------
Establish connection with a db using driver.
It is available in java.sql.*
getConnection()
---------------
It is a static factory method available in DriverManager class.
syntax
------
public static Connection getConnection("url","username","password");
url-->uniform resource locator
Type4 oracle driver
-------------------
jdbc:oracle:thin:@localhost:1521:XE
jdbc-->connectivity.
oracle-->db type.
thin-->driver type.
localhost-->ip address of localhost[127.0.0.1].
1521-->port number on which database is running.
XE-->instance name.
username--system
password--manager
It returns Connection object.
syntax
------
Connection con=DriverManager.getConnection("url","username","password');
Connection
----------
Connection is an interface available java.sql.*;
A Connection interface holds connection object.
A Connection produces factory of Objects.
Connection interface methods
----------------------------
public Statement createStatement()
public PreparedStatement prepareStatement()
public CallableStatement prepareCall()
public void setAutoCommit()
public void commit()
public void rollback()
public void getMetaData()
public void close()
driver is a -------.
we have ----types of drivers
type1 is also called as----
type2 is also called as----
type3 is also called as----
type4 is also called as----
------method is used to load driver
forName is available in ------
syntax to load driver
DriverManger is --------
DriverManager establish connection with db using-----method.
getConnection is method------
getConnection returns ------ object
getConnection accepts---,---,---- parameters
url has----,----,----,-----,-----,-----
Connection is ------
Connection provides -------- of objects.
Connection holds------object.
step3:Performing database operations.
we can perform 2 types of operations with a database
i)select operations(select)
ii)Non select operations(insert,update,delete,create etc)
In jdbc we can perform either select or non select operations using the following interfaces.
i)Statement.
ii)PreparedStatement.
Statement
---------
Statement is an interface available in java.sql.* package.
A statement interface consists of following methods
i)executeUpdate().
ii)executeQuery().
iii)execute().
iv)close().
executeUpdate()
---------------
This method is used to perform non-select operations (insert,update,delete,ddl operations)with a database from jdbc program.
It returns an integer value.
It throws a checked exception SQLException.
syntax
------
public int executeUpdate(String sql) throws SQLException;
executeQuery()
--------------
It is used to execute select operation with a database from a jdbc program.
It returns ResultSet object.
It throws SQLException.
syntax
------
public ResultSet executeQuery(String sql)throws SQLException.
execute()
---------
It is used to perform both select/non-select operations.
It returns boolean value.
Throws checked exception SQLException.
syntax
------
public boolean execute(String sql) throws SQLException;
close()
-------
closes Statement object.
syntax
------
public void close() throws SQLException;
creating object for Statement object
------------------------------------
we can create object for Statement interface by using the factory method createStatement() available in Connection interface.
createStatement() returns Staement object.
It throws SQLException.
syntax
------
public Statement createStatement() throws SQLException;
Statement statement=con.createStatement();
step4: close statement
statement.close();
step5:close Connection
con.close();
write a jdbc program to create a table in a db
----------------------------------------------
class Test
{
public static void main(String args[])
{
//step1:loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:XE";
String username="system";
String password="manager";
//step2:establish connection
Connection con=DriverManager.getConnection(url,username,password);
//step3:creating Statement
Statement statement=con.createStatement();
String sql="create table employee(name varchar2(30),id number(10) primary key,sal number(10,5))";
int res=statement.executeUpdate(sql);
System.out.println("table created");
statement.close();
con.close();
}
}
}
}
stepts to create a project and execute a program in eclipse
-------
step1:creating project
1--open eclipse.
2--Go to File.
3--new.
4--Java Project.
5--ProjectName---JdbcProject
6-->select use default jre.
7-->finish.
step2:creating package
Goto Package explorer-->Expand JdbcProject-->
select src-->right click-->new-->package-->
Name--com.manohar.satya.jdbc
step3:Adding a class to a package
Goto package-->select com.manohar.satya.jdbc-->right click-->new-->class-->
Name--JdbcCreateDemo.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.*;
public class JdbcCreateDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
//step2:creating connection
Connection connection=DriverManager.getConnection(url,user,pass);
//step3:creating Statement
Statement statement=connection.createStatement();
String sql="create table employee(name varchar2(30),id number(10) primary key,sal number(10,5))";
int res=statement.executeUpdate(sql);
System.out.println("table created"+res);
statement.close();
connection.close();
}
}
Verifying table in database
---------------------------
Open "Run Sql Command Line"
sql>connect
sql>user-name--system
sql>password--manager
sql>connected
sql>desc employeee
name
id
sal
Program2
--------
package com.manohar.satya.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcInsertDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1:loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
//step2:creating connection
Connection connection=DriverManager.getConnection(url,user,pass);
//step3:create Stamenet
Statement statement=connection.createStatement();
String sql="insert into employee values('manohar',1001,2000.00)";
int status=statement.executeUpdate(sql);
System.out.println(status+" record(s) are inserted");
statement.close();
connection.close();
}
}
Initializing values from keyboard
---------------------------------
we use a class called Scanner to input values from keyboard.
It is available in the package java.util.*;
Methods
-------
byte--nextByte()
short--nextShort()
int--nextInt()
long--nextLong()
float--nextFloat()
double--nextDouble()
boolean--nextBoolean()
String--next()
nextLine()
Inputting String,int
Scanner s=new Scanner(System.in);
Sop("enter a");
int a=s.nextInt();
Sop("enter b");
String str=s.next();
Program
-------
package com.manohar.satya.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class JdbcDynamicInsertDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//create Scanner object
Scanner scanner=new Scanner(System.in);
System.out.println("Enter name");
String name=scanner.next();
System.out.println("Enter id");
int id=scanner.nextInt();
System.out.println("Enter sal");
double sal=scanner.nextDouble();
//step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2
Connection connection = DriverManager.getConnection(url, user, pass);
// step3
Statement statement = connection.createStatement();
String sql="insert into employee values('"+name+"',"+id+","+sal+")";
int res = statement.executeUpdate(sql);
System.out.println(res+"record(s) are inserted");
statement.close();
connection.close();
}
}
Program
-------
System.out.println("Enter id");
int id = scanner.nextInt();
System.out.println("Enter sal");
double sal = scanner.nextDouble();
String sql = null;
if (id % 2 == 0) {
sql = "update employee set sal=" + sal + " where id=" + id + "";
int res = statement.executeUpdate(sql);
System.out.println(res + "record(s) are inserted");
}
else {
System.out.println("Enter an even id");
}
Performing select operation with jdbc
-------------------------------------
steps:
step1:Loading driver
Class.forName("driverName");
step2:Establishing connection with db
Connection connection=DriverManager.getConnection(url,username,password);
step3:Creating Statement object.
Statement statement=connection.createStatement();
Step4:create select query
String sql="select *from tablename";
step5:creating ResultSet.
ResultSet rs=statement.executeQuery(sql);
step6:Iterate ResultSet
step7:close ResultSet
rs.close();
step8:close Statement
statement.close();
step9:close connection
connection.close();
ResultSet
---------
ResultSet is an interface available in java.sql.* package;
If we want to execute a select query we use executeQuery() method from Statement interface.
An executeQuery method returns ResultSet object after executing an sql query with the database by wrapping(putting) the records fetched from the database into ResultSet object.
How to get ResultSet object
---------------------------
ResultSet rs=statement.executeQuery(sql);
The above diagram depicts the flow of select query execution.
1--executeQuery() issues select query with database.
2--Reads the records from the table and wraps all the records into ResulSet object at java side
3--The address of ResultSet object is initialized to ResultSet reference "rs".
Definition
----------
A ResultSet is a cursor which is used to iterate the data fetched from a database.
Method summary
--------------
public boolean next()
This method moves cursor to next row of a ResultSet
By default the cursor will be positioned above first record of ResultSet
next method position a cursor to a row and return true if the record is available in the ResultSet otherwise returns false.
public byte getByte(int index);
or
public byte getByte(String column_name);
This method returns an integer value from the column of ResultSet.
public short getShort(int index);
or
public short getShort(String column_name);
This method returns an integer value from the column of ResultSet.
public int getInt(int index);
or
public int getInt(String column_name);
This method returns an integer value from the column of ResultSet.
public long getLong(int index);
or
public long getLong(String column_name);
This method returns an integer value from the column of ResultSet.
public float getFloat(int index);
or
public float getFloat(String column_name);
This method returns a decimal value from the column of ResultSet.
public double getDouble(int index);
or
public double getDouble(String column_name);
This method returns a decimal value from the column of ResultSet.
public String getString(int index);
or
public String getString(String column_name);
This method returns a string value from the column of ResultSet.
public String getBoolean(int index);
or
public String getBoolean(String column_name);
This method returns a boolean value from the column of ResultSet.
Note:
while trying to get a value from a column of a ResultSet we should use a getXXX() method based on the type of column in ResultSet i'e
if column is varchar2 use getString() method
if column is number use getInt()/getLong()/getByte()/getShort()
if column is decimal use getFloat()/getDouble()
if column is boolean use getBoolean() method
so on.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.*;
public class JdbcSelectDemo {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2
Connection connection = DriverManager.getConnection(url, user, pass);
// step3
Statement statement = connection.createStatement();
String sql = "select *from employee";
//step4
ResultSet rs= statement.executeQuery(sql);
while(rs.next()){
String name=rs.getString("name");
int id=rs.getInt("id");
double sal=rs.getDouble("sal");
System.out.println(name+" "+id+" "+sal);
}
rs.close();
statement.close();
connection.close();
}
}
Note:
we can get a value from the column of a ResultSet by using the index or name of the column.
syntax
------
public datatype getXXX(int index);-->returns value based on index.
public datatype getXXX(String name);-->returns value based on column_name.
The index of a column in ResultSet by default starts from 1 and then 2 and so on.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.*;
public class JdbcDynamicInsertDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2
Connection connection = DriverManager.getConnection(url, user, pass);
// step3
Statement statement = connection.createStatement();
String sql = "select name from employee";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("name");
if (name.startsWith("a") ||
name.startsWith("e")
|| name.startsWith("i") ||
name.startsWith("o")
|| name.startsWith("u")) {
System.out.println(name);
}
}
rs.close();
statement.close();
connection.close();
}
}
Introducing pojo approach in jdbc
---------------------------------
Pojo[Plain old java object]
---------------------------
It is simple java class which follows certain standards.
It consists of private properties and public setter and getter
methods.
It should have a zero argumment default constructor.
It should implement Serializable interface.
setter and getter methods
-------------------------
A setter is used set value to the property of a pojo.
syntax
------
public void setPropertyName(datatype varname)
{
this.varname=varname
}
getter method
-------------
It returns the value of a property.
syntax
------
public returntype getPropertyName()
{
return varname;
}
create a jdbc project--->JdbcPojo.
create packages under src
com.manohar.satya.jdbc.dto
Employee.java
com.manohar.satya.client
EmployeeClient
Employee.java
-------------
package com.manohar.satya.jdbc.dto;
public class Employee {
//instance variables
private String empName;
private int empID;
private double empSal;
//setters and getters
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double empSal) {
this.empSal = empSal;
}
}
EmployeeClient.java
-------------------
package com.manohar.satya.jdbc.client;
import java.sql.*
import com.manohar.satya.jdbc.dto.Employee;
public class EmployeeClient {public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
// jdbc properties
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:Establishing connection
Connection connection = DriverManager.getConnection(url, user, pass);
// step3:creating Statement
Statement statement = connection.createStatement();
// creating Employee object
Employee employee = new Employee();
// setting values
employee.setEmpID(1001);
employee.setEmpName("dddd");
employee.setEmpSal(2000.00);
String sql = "insert into employee values('" + employee.getEmpName()
+"',"+employee.getEmpID()+","+employee.getEmpSal()+ ")";
int status=statement.executeUpdate(sql);
System.out.println(status+"record(s) is inserted");
statement.close();
connection.close();
}
}
Moving jdbc properties to a properties file
-------------------------------------------
Jdbc properties
driver
url
username
pass
A properties file is used to declare data in the form of key and value pairs.
It should have an extension .properties
ex:jdbc.properties
How to create properties file in eclipse
----------------------------------------
open eclipse
-->goto project
-->src
-->right click
-->new
-->file
Name as-->jdbc.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=system
pass=manager
Properties
----------
Properties is a predefined class available in java.util.* package.
Properties class is use to store,update and read properties from a properties file.
Method
------
load(Reader reader);
load(InputStream stream);
loads properties from properties file into a proerties object.
save()
store()
write properties into proerties file.
getProperty()--read a property from a Properties object.
steps to read jdbc properties from a properties files------------------------------------------
-----
step1:open properties using FileInputStream
FileInputStream in=new FileInputStream("filepath");
ex:
FileInputStream in=new FileInputStream("D:\\JavaNewWorkShop\\AdvancedJavaBatch\\JdbcSelect\\src\\jdbc.properties");
step2:create object for Properties class.
Properties p=new Properties();
step3:
loading properties from properties file to Properties object.
p.load(in);
step4:read properties from Properties object using getProperty() method
syntax
------
String varname=p.getProperty("Propertyname");
ex:
String driver=p.getProperty("driver");
step5:
close file
in.close();
Note:FileInputStream() constructor throws FileNotFoundException(checked).
load() method throws IOException.
Note:we can perform write/read operations on a file using the following classes
Write operation
---------------
FileOutStream
FileWriter
Read operation
--------------
FileInputStream
FileReader
Program to perform select operation using jdbc
----------------------------------------------
package com.manohar.satya.jdbc.client;
import java.io.*;
import java.sql.*;
import java.util.*;
import com.manohar.satya.jdbc.pojo.Employee;
public class EmployeeClient {
public static void display(Employee employee){
System.out.println("The name is "+employee.getEmpName());
System.out.println("The id is "+employee.getEmpID());
System.out.println("The sal is "+employee.getEmpSal());
}
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException //step1:open properties
FileInputStream in=new FileInputStream("D:\\JavaNewWorkShop\\AdvancedJavaBatch\\JdbcSelect\\src\\jdbc.properties");
//step2:create Properties object
Properties properties=new Properties();
//step3:load properties
properties.load(in);
//stp4:getting properties.
String driver=properties.getProperty("driver");
String url=properties.getProperty("url");
String pass=properties.getProperty("pass");
String user=properties.getProperty("user");
//jdbc process
//step1:load driver
Class.forName(driver);
//step2:creating connection
Connection connection=DriverManager.getConnection(url,user,pass);
//step3:creating Statement
Statement statement=connection.createStatement();
String sql="select *from employee";
ResultSet rs=statement.executeQuery(sql);
Employee employee=new Employee();
while(rs.next()){
String name=rs.getString("name");
int id=rs.getInt("id");
double sal=rs.getDouble("sal");
employee.setEmpID(id);
employee.setEmpName(name);
employee.setEmpSal(sal);
display(employee);
}
in.close();
rs.close();
statement.close();
connection.close();
}
}
PreparedStatement
-----------------
It is a child interface of Statement available java.sql.*;
A PreparedStatement uses pre-compiled query,if we are executing same query repeatedly.
Whenever we execute a query with database from jdbc,the following operations are performed at database side
i)Query compilation
ii)Query execution
if we use Statement to execute a query,if it is same or different query,every time query compilation and query execution happens whereas if we use PreparedStatement ,query is compiled only for one time,if we are executing the same query repeatedly otherwise if we are executing different queries,query compilation and execution happens for both Statement and PreparedStatement every time.
We can get PreparedStatement object by using the method prepareStatement() available in Connection interface.
syntax
------
public PreparedStatement prepareStatement(String sql);
A prepareStatement() throws SQLException.
How to get PreparedStatement object.
------------------------------------
PreparedStatement statement=connection.prepareStatement(sql);
PreparedStatement suports parameter binding.
Binding values to query parameters/positional parameters of a query is known as parameter binding.
Positional parameters are repersentd with question mark(?),by default every question mark has indexing and the indexing starts with one(1) and then two(2) and so on.
we set values to the positional parameters by using setters available in PreparedStatement interface.
Method summary
--------------
public int executeUpdate()
public ResultSet executeQuery()
public boolean execute()
public void close()
public void setString(int index,String value);
public void setByte(int index,byte value);
public void setShort(int index,short value);
public void setInt(int index,int value);
public void setLong(int index,long value);
public void setFloat(int indexfloat value);
public void setDouble(int index,double value);
public void setBoolean(int index,boolean value);
Program
-------
step1:create Employee Pojo
public class Employee {
//instance variables
private String empName;
private int empID;
private double empSal;
//setters and getters
}
stpe2:create properties file.
jdbc.properties
---------------
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=system
pass=manager
step3:create JdbcClient
public class JdbcClient {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//opening file
FileInputStream in=new FileInputStream("D:\\JavaNewWorkShop\\AdvancedJavaBatch\\PreparedStatement\\src\\jdbc.properties");
//creating Properties
Properties properties=new Properties();
//loading properties
properties.load(in);
//getting properties
String driver=properties.getProperty("driver");
String url=properties.getProperty("url");
String user=properties.getProperty("user");
String pass=properties.getProperty("pass");
//jdbcproperties
Class.forName(driver);
//Connection
Connection connection=DriverManager.getConnection(url,user,pass);
//sql query
String sql="insert into employee values(?,?,?)";
//creating object for pojo
Employee employee=new Employee();
employee.setEmpName("abc");
employee.setEmpID(1002);
employee.setEmpSal(30000.00);
//PreparedStatement
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,employee.getEmpName());
statement.setInt(2,employee.getEmpID());
statement.setDouble(3,employee.getEmpSal());
int status=statement.executeUpdate();
System.out.println(status+"records are inserted");
in.close();
statement.close();
connection.close();
}
}
CallableStatement
-----------------
A CallableStatement is used to call stored procedures and functions from a database in a java program.
It is child interface of Statement available in java.sql.*;
Methods
-------
public int executeUpdate();
publlic ResultSet executeQuer();
public boolean execute();
public void close();
We get CallableStatement object by using method prepareCall() available in Connection interface.
syntax
------
public CallableStatement prepareCall(sql);
How to get CallableStatement object.
-----------------------------------
CallableStatement statement=connection.prepareCall(sql);
It throws SQLException.
Stored Procedure
----------------
A stored procedure is used to implement business logic at database side.
Storedprocedure reduces burden on Application developer.
How create sp
-------------
create or replace procedure proceduerName
(var1 paramtype datatype,
var2 paramtype datatype,
....,
....,
varn paramtype datatype)
is
begin
//statements
end;
/
parameter types in a procedure
------------------------------
In a sp we have 3 types of parameters
i)input.
ii)output.
iii)input/output.
input parameters
----------------
These are used to accept values sent from an appliacation and persist data in a table.
we use keyword "in" to declare input parameters.
syntax
------
varname in datatype;
ex:
name in varchar2;
output parameters
-----------------
These are used to return values(result) from database to a appliaction.
we use keyword "out" to declare output parameters.
syntax
------
varname out datatype;
ex:
name out varchar2;
input/output parameters
-----------------------
These acts as both input and output parameters.
we use keyword "inout" to declare input/output parameters.
syntax
------
varname inout datatype;
ex:
name inout varchar2;
creating a stored procedure to insert employee record in a table
----------------------------------------------
create or replace procedure insertProc
(name in varchar2,
id in int,
sal in float)
is
begin
insert into employee values(name,id,sal);
end;
/
Now goto database and execute query at database.
open RunSqlCommanLine
sql>copy paste procedure here
..
..
..
Procedure created.
Points to remember
------------------
------is used to execute sp,functions in jdbc.
CallableStatement is a child of -------.
-----method is used to create -------object.
prepareCall method is available in-------.
----,---,----,--- are imp methods of CS.
sp is used implement------
----parametertypes are there in sp.
----keyword is used to declare input parameters.
----keyword is used to declare output parameters.
----keyword is used to declare input/output parameters.
How to call a stored procedure
-------------------------------
syntax
------
call procedureName(?,?,.....);
ex:
call insertProc(?,?,?);
CallableStatement also supports parameterbinding i,e we can set values to the positional parameters using setter methods.
we have following setter methods in CallableStatement.
public void setString(int index,String value);
public void setByte(int index,byte value);
public void setShort(int index,short value);
public void setInt(int index,int value);
public void setLong(int index,long value);
public void setFloat(int indexfloat value);
public void setDouble(int index,double value);
public void setBoolean(int index,boolean value);
A CallableStatement provides getters also to get the values returned by output parameters of a stored procedure.
we use the following getters from CS.
public byte getByte(int index);
public short getShort(int index);
public int getInt(int index);
public long getLong(int index);
public float getFloat(int index);
public double getDouble(int index);
public String getString(int index);
public boolean getBoolean(int index);
Program(insert a record into an employee table using sp)
-------
step1:create pojo
public class Employee {
private String empName;
private int empID;
private double empSal;
//setters and getters
}
step2:create jdbc.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=system
pass=manager
step3:JdbcClient
public class JdbcClient
{
p s v m(Strin args[])
{
//code is same as above program upto here
//creating scanner
Scanner scanner=new Scanner(System.in);
// creating object for pojow
Employee e = new Employee();
System.out.println("enter name");
e.setEmpName(scanner.next());
System.out.println("enter id");
e.setEmpID(scanner.nextInt());
System.out.println("enter sal");
e.setEmpSal(scanner.nextDouble());
//creating sql
String sql="{call insertProc(?,?,?)}";
CallableStatement statement=connection.prepareCall(sql);
statement.setString(1,e.getEmpName());
statement.setInt(2,e.getEmpID());
statement.setDouble(3,e.getEmpSal());
boolean status=statement.execut();
System.out.println(status+"inserted");
in.close();
statement.close();
connection.close();
}
}
creating sp to retrive name,sal from employee table
by passing id as input.
---------------------------------------------------
create or replace procedure selectProc
(name1 out varchar2,
id1 in int,
sal1 out float)
is
begin
select name,sal into name1,sal1 from employee where id=id1;
end;
/
How to read output parameters in a jdbc program
-----------------------------------------------
We read output parameters at java side by using CallableStatement.
We should register output parameters with CallableStatement by using method registerOutParameter()
syntax
------
public void registerOutParameter(int index,Types.type);
Types
-----
Types is predefined class available in java.sql.* package which provides different datatypes.
Types class provides compatability between java datatypes and database datatypes.
Program to read out parameters from a sp
----------------------------------------
step1:create Pojo
public class Employee
{
private String empName;
private int empID;
private double empSal;
//setters and getters
}
step2:create jdbc.properties
driver
url
user
pass
step3:create JdbcSpClient.
public class JdbcSpClient
{
public static void main(String args[])
{
//code same as above program until here
//creating sql
String sql="{call selectProc(?,?,?)}";
//creating scanner
Scanner scanner=new Scanner(System.in);
// creating object for pojow
Employee e = new Employee();
System.out.println("enter id");
e.setEmpID(scanner.nextInt());
CallableStatement statement=connection.prepareCall(sql);
statement.setInt(2,e.getEmpID());
statement.registerOutParameter(1,Types.VARCHAR);
statement.registerOutParameter(3,Types.FLOAT);
boolean status=statement.execute();
System.out.println(statement.getString(1));
System.out.println(statement.getFloat(3));
in.close();
statement.close();
connection.close();
}
}
differences between storedprocedures and functions
--------------------------------------------------
storedprocedure functions
i)used to implement busines i)used to perform
logic. calculations.
ii)It consists of input/output ii)It consists of
parameters. only input parameters.
iii)returns 0 or more values iii)returns only one
value.
iv)we can call a function iv)we cannot call
from a stored procedure. stored procedure from
a function.
v)We can implement exception v)No exception hanling in sp. handling.
functions
---------
Functions are used to implement calculations.
syntax
------
create or replace function function_name
(var1 in type,var2 in type,.....)
return type
is
//variable section
begin
//logic
return var;
end;
/
function to find sum of two numbers.
create or replace function sum1
(num1 in int,num2 in int)
return int
is
num3 int;
begin
num3:=num1+num2;
return num3;
end;
/
How to call a function
----------------------
syntax
------
?=call function_name(?,?,..)
ex:
?=call sum1(?,?)
Program to call a function from jdbc program
--------------------------------------------
step1:Jdbcpropperties
same as above program
step2:JdbcFunctionClient
public class JdbcFunctionClient{
public static void main(String args[])
{
//upto here code is same as above program
//creating sql
String sql="{?=call sum1(?,?)}";
CallableStatement statement=connection.prepareCall(sql);
statement.setInt(2,10);
statement.setInt(3,20);
statement.registerOutParameter(1,Types.INTEGER);
statement.execute();
System.out.println(statement.getInt(1));
in.close();
statement.close();
connection.close();
}
}
Program to read names from database and sort names
--------------------------------------------------
step1:jdbc properties
//same as above program
step2:create JdbcStringSortClient
public class JdbcStringSortClient {
public static void main(String[] args) throws IOException,ClassNotFoundException, SQLException {
//upto here code is same as above program
// sql query
String sql = "select name from employee";
// PreparedStatement
PreparedStatement statement = connection.prepareStatement(sql);
//creating ResultSet
ResultSet rs = statement.executeQuery();
//creating String array
String s[] = new String[10];
//iterating ResultSet and copying to String array
int j = 0;
while (rs.next()) {
String name = rs.getString(1);
s[j] = name;
j++;
}
String sortedStri=sort(s);
for(String s1:sortedString){
System.out.println(s1);
}
in.close();
rs.close();
statement.close();
connection.close();
}
public static String[] sort(String s[]){
String temp;
for(int i=0;i<s.length;i++){
for(int j=i+1;j<s.length;j++)
{
if(s[i].compareTo(s[j])>0){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
return s;
}
}
Note:pass the size to String array based on rows in the tables.
Transaction Management
----------------------
Transaction:
Performing unit of task is known as transcation.
A transaction should follow ACID properties
A-atomic.
C-consistancy.
I-Isolation.
D-durable.
A transaction is said to atomic when a transaction is committed only if it is succesfully executed otherwise never commit a transaction.
we implement transaction management by using the following methods available in Connection interface.
public void setAutoCommit(boolean);
public void commit();
public void rollback();
setAutoCommit():It is used to enable or disable a commit mode.
By default commit mode is enabled in jdbc.
ex:
connection.setAutoCommit(false);
commit():
It is used to make changes perminent in the database.
rollback():
It is used to rollback a trasanction if any execption is raised while executing transaction.
Program
-------
package com.manohar.satya.jdbc.client;
import java.sql.*;
public class JdbcTransactionClient {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
Connection connection=null;
Statement statement=null;
// step2
try {
connection = DriverManager.getConnection(url, user, pass);
// step:disable auto commit
connection.setAutoCommit(false);
// step3
statement = connection.createStatement();
String sql = "insert into employee values('fff',456,40000.00)";
statement.executeUpdate(sql);
connection.commit();
}
catch (Exception exception)
{
exception.printStackTrace();
connection.rollback();
}
finally{
statement.close();
connection.close();
}
}
}
}
Layers in java
--------------
We divide a java application into 3 layers
i)Presentation layer.
ii)Business/application layer.
iii)Database layer/DAO layer.
we implement presentation/User interface logic in presentation layer.
we implement business logic in application layer
we implement database logic in dao layer.
A layered approach divides the responsibilities as per requirement of a project which makes the maintenance of project simple and easy.
Developing DAO layer
--------------------
DAO[Data Access object]
-----------------------
A DAO is a design pattern which is used to seperate database logic from business and presentaion logic.
Execution flow
--------------
Client---->service--->DAO---->(database).
creating a DAO layer
--------------------
DAO is reusable java class also people call this as design pattern.
While defining a dao layer take
i)one interface.
ii)one class.
interface is declared with all the abstract methods required in DAO operations.
A DAO consists of the following methods
i)public int save(Employee employee);
This is used to insert a row into a employee table.
ii)public int update(Employee employee);
This is used to update a row in an employee table.
iii)public int delete(Employee employee);
This is used to delete a row from an employee table.
iv)public Employee get(int id);
This is used to select a row from employee table and and set it to a pojo and returns pojo.
v)public Employee[] getAll();
It is used to select all the rows from employee table and store into Employee[] array and returns it.
creating interface EmployeeDAO.java
-----------------------------------
public interface EmployeeDAO {
public int save(Employee e);
public int update(Employee e);
public int delete(Employee e);
public Employee get(int id);
public Employee[] getAll();
}
Implementing EmployeeDAO in EmployeeDAOImpl.java
------------------------------------------------
public class EmployeeDAOImpl implements EmployeeDAO {
//declaring references
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet resultSet = null;
private Employee employee=null;
private Employee employee1[]=null;
//declaring jdbc properties
public static final String url = "jdbc:oracle:thin:@localhost:1521:XE";
public static final String user = "system";
public static final String pass = "manager";
@Override
public int save(Employee e) {
int status=0;
try {
Class.forNam("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "insert into employee values(?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1,e.getEmpName());
statement.setInt(2,e.getEmpID());
statement.setDouble(3,e.getEmpSal());
status=statement.executeUpdate();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally {
try {
statement.close();
connection.close();
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
return status;
}
@Override
public int update(Employee e) {
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "update employee set sal=? where id=?";
statement = connection.prepareStatement(sql);
statement.setDouble(1, e.getEmpSal());
statement.setInt(2, e.getEmpID());
status = statement.executeUpdate();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
try {
statement.close();
connection.close();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
return status;
}
@Override
public int delete(Employee e) {
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "delete from employee where id=?";
statement = connection.prepareStatement(sql);
statement.setInt(1, e.getEmpID());
status = statement.executeUpdate();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try {
statement.close();
connection.close();
}
catch(SQLException e1)
{
e1.printStackTrace();
}
}
return status;
}
@Override
public Employee get(int id) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "select from employee where id=?";
statement = connection.prepareStatement(sql);
statement.setInt(1,id);
//creating ResultSet
resultSet=statement.executeQuery();
//create Employee object
employee=new Employee();
while(resultSet.next()){
String name=resultSet.getString("name");
int id1=resultSet.getInt("id");
double sal=resultSet.getDouble("sal");
//setting to pojo
employee.setEmpID(id1);
employee.setEmpName(name);
employee.setEmpSal(sal);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
try {
resultSet.close();
statement.close();
connection.close();
}
catch(SQLException e1)
{
e1.printStackTrace();
}
}
return employee;
}
@Override
public Employee[] getAll() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "select *from employee";
statement = connection.prepareStatement(sql);
//creating Employee Array
employee1=new Employee[12];
for(int i=0;i<employee1.length;i++){
employee1[i]=new Employee();
}
//creating ResultSet
resultSet=statement.executeQuery();
int i=0;
while(resultSet.next()){
String name=resultSet.getString("name");
int id1=resultSet.getInt("id");
double sal=resultSet.getDouble("sal");
//setting to pojo
employee1[i].setEmpID(id1);
employee1[i].setEmpName(name);
employee1[i].setEmpSal(sal);
i++;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try {
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
return employee1;
}
}
creating service layer
-----------------------
create 2 entities
i)one Service interface
ii)one ServiceImpl class.
creating EmployeeService.java(I)
--------------------------------
copy the methods of EmployeeDAO interface to EmployeeService.
package com.manohar.satya.service;
import com.manohar.satya.model.Employee;
public interface EmployeeService {
public int save(Employee e);
public int update(Employee e);
public int delete(Employee e);
public Employee get(int id);
public Employee[] getAll();
}
//step2:create EmployeeServiceImpl.java and implement //EmployeeService.java
package com.manohar.satya.service;
import com.manohar.satya.dao.EmployeeDAO;
import com.manohar.satya.dao.EmployeeDAOImpl;
import com.manohar.satya.model.Employee;
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO dao = null;
public EmployeeServiceImpl() {
dao = new EmployeeDAOImpl();
}
@Override
public int save(Employee e) {
int staus = dao.save(e);
return staus;
}
@Override
public int update(Employee e) {
int status = dao.update(e);
return status;
}
@Override
public int delete(Employee e) {
int status = dao.delete(e);
return status;
}
@Override
public Employee get(int id) {
Employee employee = dao.get(id);
return employee;
}
@Override
public Employee[] getAll() {
Employee employee[] = dao.getAll();
return employee;
}
}
creating Model Employee.java
----------------------------
public class Employee {
private String empName;
private int empID;
private double empSal;
//setters and getters
}
creating client layer[EmployeeClient.java]
------------------------------------------
public class EmployeeClient {
public static void main(String[] args) {
// step1
EmployeeService service = new EmployeeServiceImpl();
Scanner scanner = new Scanner(System.in);
//case1:insert employee
Employee employee1=new Employee();
//setting data
System.out.println("Enter id");
employee1.setEmpID(scanner.nextInt());
System.out.println("Enter name");
employee1.setEmpName(scanner.next());
System.out.println("Enter sal");
employee1.setEmpSal(scanner.nextDouble());
//saving pojo int
status=service.save(employee1);
System.out.println(status+"inserted successfully!!!!!!");
// case2:update employee
Employee employee2 = new Employee();
//setting data
System.out.println("Enter id");
employee2.setEmpID(scanner.nextInt());
System.out.println("Enter sal");
employee2.setEmpSal(scanner.nextDouble());
// saving pojo
int status2=service.update(employee2);
System.out.println(status2 + "updated successfully!!!!!!");
// case3:delete employee
Employee employee3 = new Employee();
//setting data
System.out.println("Enter id");
employee3.setEmpID(scanner.nextInt());
// deleting pojo
int status3 = service.delete(employee3);
System.out.println(status3 + " deleted successfully!!!!!!");
// case4:get employee
System.out.println("Enter id");
int id=scanner.nextInt();
//get pojo
Employee employee = service.get(id);
System.out.println(employee.getEmpID());
System.out.println(employee.getEmpName());
System.out.println(employee.getEmpSal());
// case5:Get All employees
Employee employee[] = service.getAll();
//iteration using for each
for (Employee e : employee) {
System.out.println(e.getEmpID());
System.out.println(e.getEmpName());
System.out.println(e.getEmpSal());
}
//iteration using for loop
for (int i=0;i<employee.length;i++) {
System.out.println(employee[i].getEmpID());
System.out.println(employee[i].getEmpName());
System.out.println(employee[i].getEmpSal());
}
}
}
ResultSetMetaData interface
---------------------------
It is used to get Metadata of a table in a database.
Metadata means data about data.
Here we get
column_name
column_type
column_count
etc of a table using ResultSetMetaData.
It is available in java.sql.* package.
Method summary
--------------
public int getColumnCount();
public String getColumnName(int);
public String getColumnTypeName(int);
we get ResultSetMetaData object by using the method getMetaData() available in ResultSet interface.
syntax
------
public ResultSetMetaData getMetaData() throws SQLException;
How to create ResultSetMetaData object.
-----------------------------------------
ResultSetMetaData data=reference.getMetaData();
here reference is ResultSet type.
Program
-------
public class JdbcResultSetMetaDataDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql query
String sql = "select *from employee";
// PreparedStatement
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
//creating ResultSetMetaData
ResultSetMetaData data=rs.getMetaData();
System.out.println(data.getColumnCount());
System.out.println(data.getColumnName(2));
System.out.println(data.getColumnTypeName(3));
rs.close();
statement.close();
connection.close();
}
}
}
DatabaseMetaData interface
--------------------------
A DatabaseMetaData provides metadata of a database like
databasename
databaseversion
drivername
driver_version
etc
It is available in the package java.sql.*;
Method summary
--------------
public String getDatabaseProductName() throws java.sql.SQLEception;
public String getDatabaseProductVersion() throws java.sql.SQLException;
public String getDriverName() throws java.sql.SQLException;
public String getDriverVersion() throws java.sql.SQLException;
etc
we get DatabaseMetaData object by using the method getMetaData() available in Connection interface.
syntax
------
public DatabaseMetaData getMetaData() throws SQLException;
How to create DatabaseMetaData object
-------------------------------------
DatabaseMetaData data=reference.getMetaData();
Here reference is Connection type.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JdbcResultSetMetaDataDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
DatabaseMetaData data = connection.getMetaData();
System.out.println(data.getDatabaseProductName());
System.out.println(data.getDatabaseProductVersion());
System.out.println(data.getDriverName());
System.out.println(data.getDriverVersion());
connection.close();
}
}
storing and retrieving image from a table.
storing and retrieving file from a table.
Java Streams
------------
Stream is flow of bits.
There are 2 types of streams.
i)character streams.
ii)Binary streams.
Character streams
-----------------
This is used to handle character type of data.Also encoding is applied for character streams.
Ex:Reader/Writer classes.
Binary Streams
--------------
This is used to handle numeric type of data. Encoding is not applied for Binary streams.
Ex:InputStream/OutputStream classes.
To store an image into a table we use a datatype called BLOB.
BLOB-->Binary Large object.
-->It is to hold binary streams.
create a table to store an image
--------------------------------
create table img(id int primary key,image blob);
How to store image into table using jdbc
----------------------------------------
To store image into a table we use the method setBinaryStream() available in PreparedStatement.
syntax
------
public void setBinaryStream(int,InputStream) throws SQLException;
public void setBinaryStream(int,InputStream,long) throws SQLException;
File path:
C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JdbcImageDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException, IOException {
//open image file
FileInputStream in=new FileInputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulips.jpg");
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
//sql
String sql="insert into img values(?,?)";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setInt(1,1);
statement.setBinaryStream(2,in,in.available());
int status=statement.executeUpdate();
System.out.println(status+" inserted");
in.close();
statement.close();
connection.close();
}
}
selecting image from a table
----------------------------
To select an image from a file we use the method getBlob() available in ResultSet.
syntax
------
public Blob getBlob(int index);
or
public Blob getBlob(String colname);
getBlob() returns Blob object.
To initialize Blob object we use the class Blob available in java.sql.*.
ex:
Blob b=rs.getBlob(2);
To store image into file we have to convert Blob to byte array.
we use the method getBytes() to convert Blob to byte array available in
Blob class.
syntax
------
public byte[] getBytes(int,int);
ex:
byte bb[]=b.getBytes(1,(int)b.length());
Here parameter1 is the index of image in image column i,e 1 st image,2nd image etc
Parameter2 is length() of image,length() returns long,we should type cast to int type.
Write byte array to file using FileOutputStream.
ex:
FileOutputStream out=new FileOutputStream("D:\\tulips.jpg");
out.write(bb);
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcImageSelectDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
String sql="select *from img";
PreparedStatement statement=connection.prepareStatement(sql);
ResultSet rs=statement.executeQuery();
while(rs.next()){
int id=rs.getInt("id");
Blob blob=rs.getBlob("image");
//convert blob to bytes
byte b[]=blob.getBytes(1,(int) blob.length());
FileOutputStream out=new FileOutputStream("d:\\tulips.jpg");
out.write(b);
out.close();
}
rs.close();
statement.close();
connection.close();
System.out.println("sucess");
}
}
Servlets
--------
client
------
A client is a machine or a software which is used to make a request to a server.
A client s/w can be a browser like google chrome,mozilla firefox etc
server
------
A server is a software or a machine which accepts request from a client and process the request and sends back response.
Server s/w can be like apache tomcat,weblogic etc.
webcomponent
------------
It is a server side program which provides service to a client.
They are of 2 types
i)static webcomponents.
ii)dynamic webcomponents.
static webcomponent
-------------------
A static webcomponent is not interactive and readonly programs.
ex:
html,xml,css etc
dynamic webcomponents
---------------------
A dynamic webcomponent is interactive and responsive programs.
ex:
javascript,vbscript,servlet,jsp,asp etc
WebApplication
--------------
A webapplication is collection of webcomponents.
A webApplication consists of
html
xml
css
javascript
servlets
jsp
etc
webcontainer
------------
A webcontainer is a program which provides environment to execute servlets and jsp.
A webcontainer manages life cycle of a servlet.
A webcontainer provides multithreading support.
A webcontainer provides load balancing.
etc
Servlet
-------
A servlet is a server side dynamic webcomponent which is used to process dynamic request of a client.
A Servlet is an interface in JEE from which every servlet will be inherited directly or indirectly.
we use the following packages to work with servlets.
i)javax.servlet.*
ii)javax.servlet.http.*
Servlet interface
-----------------
It is a root interface of all servlets in jEE.
It is available in the package javax.servlet.*;
It has 5 methods
public abstract void init(ServletConfig) throws
ServletException;
public abstract ServletConfig getServletConfig()
public abstract void service(ServletRequest,ServletResponse) throws ServletException,IOException
public abstract java.lang.String getServletInfo();
public abstract void destroy();
Here the methods init(),service().destroy() are life cycle methods.
Software requirements
---------------------
i)browser.
ii)server.
iii)IDE.
steps to create a servlet program
---------------------------------
step1:Implement servlet interface in a class
syntax
------
accessmodifier class ClassName implements Servlet
{
}
ex:
public class HelloServlet implements Servlet
{
public void init(ServletConfig config) throws ServletException
{
//
}
public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException
{
//
}
public void destroy()
{
}
public ServletConfig getServletConfig()
{
}
public String getServletInfo()
{
}
}
init() method
-------------
An init() method is used to perform initialization operations on a servlet.
i)It is used to load configuration details of servlet into ServletConfig object.
ii)A ServletConfig is an interface available in javax.servlet.*;
iii)A ServletConfig object hold configuration details of a servlet.
iv)We declare configuration details of a servlet in an xml file called as web.xml file.
v)While calling init() WebContainer creates ServletConfig object and loads configuration details into ServletConfig object.
init() is also used for initalizing variables and objects of a Servlet.
init() method is executed only for one time in the entire life cycle of servlet.
init() method throws ServletException if the execution of init() is not completed within given time or if any internal exception is raised.
service()
---------
A service() provides service to a client.
Every time client make a request to server,the service method is called.
syntax
------
public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException;
A service method consists of 2 parameters
i)ServletRequest
ii)ServletResponse
The above 2 interfaces are available in javax.servlet.*;
ServletRequest
--------------
A ServletRequest is an interface available in javax.servlet.*.
A ServletRequest object is used to hold data sent by client at server side.
ServletResponse
---------------
A ServletResponse is an interface available in javax.servlet.*.
A ServletResponse object is used to hold data sent to client from server side.
Note:
ServletConfig,ServletRequest,ServletResponse are managable by webcontainer.
destroy()
---------
destroy is used to destroy servlet objects.
It is called only for one time in time in the entire life cycle of servlet.
syntax
------
public void destroy();
getServletConfig()
------------------
This method returns ServletConfig object.
syntax
------
public ServletConfig getServletConfig();
getServletInfo()
----------------
This method returns servlet information like author,date created etc.
syntax
------
public String gerServletInfo();
step1:
------
creating a Servlet to display HelloWorld onto browser.
-----------------------------------------------------
open Notepad and write HelloWorldServlet class
import javax.servlet.*;
import java.io.*;
public class HelloWorldServlet implements Servlet
{
public void init(ServletConfig config) throws ServletException
{
System.out.println("init");
}
public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("Hello World!!!!!!");
out.close();
}
public void destroy()
{
System.out.println("destroy");
}
public ServletConfig getServletConfig()
{
return null;
}
public String getServletInfo()
{
return null;
}
}
save as
HelloWorldServlet.java
To compile a Servlet program from command prompt we should set path for a jar file servlet-api.jar.
We can download jar or we can get from tomcat installation folder.
Path for servlet-api.jar in tomcat
----------------------------------
C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar
How to set servlet-api.jar to classpath and path
------------------------------------------------
Goto Mycomputer-->right click system properties-->Advanced System settings-->environment variables-->under user variables-->
name-->classpath
value-->C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;
similarly set for path
name-->path
value-->C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;
Now compile HelloWorldServlet.java
javac HelloWorldServlet.java
step4:creating deployment directory
-----------------------------------
It is project structure for a web application to deploy in a webserver.
RootFolder[HelloWorldProject]
|-->*.jsp
|-->*.html
|-->*.images
WEB-INF
|-->src
|-->*.java
|-->classes
|-->*.classes
|-->lib
|-->*.jars
|web.xml
we keep *.java files in src folder.
we keep *.class files in classes folder.
we keep *.jars in lib folder.
web.xml
-------
It is a deployement descriptor which consists of configuration details of Servlet,jsp,filter.
Quick Learning of Xml
---------------------
xml-->Extensible Mark up language.
Xml is used to perform data transportation between different techonologies like java,.net,php etc
Xml holds data.
Xml is tag based language like html.
Xml consists of user defined tags.
It is platform independent.
It can have attributes which increases readability of xml tag.
It is w3c recommendation.
strcuture
---------
<root-tag>
<child-tag>
<chid1-tag>value</child1-tag>
<chid2-tag>value</child2-tag>
<chid3-tag>value</child3-tag>
</child-tag>
<child-tag>
<chid1-tag>value</child1-tag>
<chid2-tag>value</child2-tag>
<chid3-tag>value</child3-tag>
</child-tag>
<child-tag>
<chid1-tag>value</child1-tag>
<chid2-tag>value</child2-tag>
<chid3-tag>value</child3-tag>
</child-tag>
..
..
..
</root-tag>
The starting tag in xml is called root tag.
The inner tags are child-tags.
Every tag opened must be closed with(/).
ex:
<tag>value</tag>
structure of web.xml
--------------------
<web-app>
<servlet>
<servlet-name>servletname</servlet-name>
<servlet-class>FullyQualifiedNameOfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletname</servlet-name>
<url-pattern>/url</url-pattern>
</servlet-mapping>
</web-app>
web.xml
-------
<web-app>
<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/helloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
step5:installing Apache tomcat.
download apcahe-tomcat server from google
https://tomcat.apache.org/download-80.cgi
click on "32-bit/64-bit Windows Service Installer (pgp, md5, sha1)"
Double click on downloaded apache-tomcat executable file and click on next->next-->... to finish installation.
step6:Deploying a WebProject into a webServer.
Deploying is a process of moving a project from localdrive to webserver (in ameerpet).
Deploying is a process of moving a project from development server to production server (in hitec city).
Path of deployment directory in my local machine
D:\Satya_technologies\JavaPrograms\
Goto this directory copy the project "HelloWorldProject" and paste it under the following path in tomcat.
C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps
step7:
Start tomcat server
Goto the path
C:\Program Files\Apache Software Foundation\Tomcat 8.5\bin
double click on "Tomcat8".
How to check server is started or not
-------------------------------------
Type url http://localhost:8070
It will bring up tomcat administrator console.
How to run webApplication
-------------------------
Open browser and the type the following url
http://localhost:8070/HelloWorldProject/helloWorldServlet
localhost-->ip address of local mahcine
-->In a Project ip address changes depends on server.
8070-->port number
HelloWorldProject-->Project name[context path]
helloWorldServlet-->url-pattern of a servlet.
Execution flow of HelloWorldServlet
-----------------------------------
i)Client[browser] makes a request to webserver for a servlet.
2)Webserver will check the type of request and forward it to Webcontainer if it is a dynamic request.
3,4)Webcontainer will goto web.xml and search for url-pattern of a servlet sent by user and starts processing the required servlet.
5)Container starts the proceesing servlet by loading servlet from hard disk to ram.
6)Container instatiates servlet.
7,8)Container creates ServletConfig object and the calls init method and perform required initialization operations.
9,10,11)Container creates ServletRequest and ServletResponse objects and then calls service method by passing request and response objects as parameters to service method.
12)Resonse is sent back to client.
13)If the webApplication is shutdown or server is shut down then the destroy method of servlet is called.
Creating a Web project[HelloWorldProject] in eclipse
----------------------------------------------------
Goto File-->New-->dynamic Web project--->
ProjectName-->HelloWorldProject
Provide configuration Tomcat with eclipse as shown below.
Goto Target Runtime-->
Browse NewRuntime-->select Appropriate version of Tomcat among the given versions-->
next-->
under tomcat installation directory-->
browse-->select installaton path ot tomcat-->
C:\Program Files\Apache Software Foundation\Tomcat 8.5-->finish-->finish
Project structure in eclipse
----------------------------
Add Servlets or any *.java files under JavaResources-->src-->
Add *.html,*.jsp,*.images under WebContent folder.
Add *.jars under lib folder.
How to Add servlet
------------------
Goto JavaResources-->src-->create a package-->
com.manohar.satya.servlets
Right clik on package-->new-->servlet-->
ClassName-->HelloWorldServlet
SuperClassName-->Empty
click on next-->next-->finish.
How to run a web project in eclipse
-----------------------------------
Select Project[HelloWorldProject]-->right click-->Run As-->Run on server.
Type the following url in the browser
-------------------------------------
http://localhost:8070/HelloWorldProject/HelloWorldServlet.
Note:
In the above project we are not providing configuration details of servlet in web.xml because instead of web.xml an annotaion @WebServlet was introduced in servlets.Here the annotation is used to configure servlet.
The url in the annotation is the url-pattern which is used to make a call to a servlet from a client machine.
syntax
------
@WebServlet("/url-pattern")
public class ClassName implements Servlet
{
//
}
Note:
If we are using @WebServlet annotation ,then mapping of url sent by client is done container by searching for servlets in src folder,which ever annotation is mapping with url,the servlet class under that annotation is processed by the container.
If none of the servlets is matching with url then server returns 404 error.
Form processing using servlets
------------------------------
html
----
hyper text mark up language.
i)It is used to design webpages.
ii)It is user friendly.
iii)tag based language.
iv)case insensitive
v)It has attributes.
vi)It is w3c.
Program structure of html
-------------------------
<html>
<head>
<title>....</title>
..
..
</head>
<body>
..
..
..
</body>
</html>
heading tags
------------
we have 6 types of heading
<h1>text</h1>
<h2>text</h2>
<h3>text</h3>
<h4>text</h4>
<h5>text</h5>
<h6>text</h6>
creating a web application to process a login form
--------------------------------------------------
create a new project-->LogingFormProject
-->Goto WebContent folder-->Add a html-->
Name as-->login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
</body>
</html>
Add servlet-->LoginServlet.java
Goto-->JavaResources-->src-->
create a new package-->com.manohar.login
Add a new servlet LoginServlet.java under package.
code under service() method
----------------------------
//reading form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
//displaying form
PrintWriter out=response.getWriter();
out.println(name);
out.println(pass);
out.close();
How to run Project
------------------
Goto Project-->LoginForm-->select project-->right click-->run as-->run on server
Type the following url in browser
localhost:8070/LoginFormProject/login.html
Login.html
-----------
-----------
Name:|manohar |
------------
------------
Password:|********* |
------------
submit
Output on Browser
-----------------
--------------------------------------------
|localhost:8070/LoginFormProject/login.html|
--------------------------------------------
Manohar
satya
ArmstrongProject
----------------
Add html-->armstring.html
<form action="./ArmStrongServlet">
Enter number:<input type="text" name="no" />
<input type="submit" value="armstrong" />
</form>
Add ArmStrongServlet.java
code under service method
-------------------------
//reading form
String n=request.getParameter("no");
int x=Integer.parseInt(n.trim());
int r,sum=0,temp;
temp=x;
while(x!=0){
r=x%10;
sum=sum+r*r*r;
x=x/10;
}
//
PrintWriter out=response.getWriter();
//validation
if(sum==temp){
out.println("No is Armstrong "+temp);
}
else{
out.println("No is not Armstrong "+temp);
}
out.close();
create LoginProject
-------------------
Add login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add LoginServlet.java
---------------------
@WebServlet("/LoginServlet")
public class LoginServlet implements Servlet {
//variable declaration
String s[] = null;
ArrayList list=null;
public void init(ServletConfig arg0) throws ServletException {
//initiaizing string array
s = new String[2];
s[0] = "prabhas";
s[1] = "anushka";
//initializing ArrayList
list=new ArrayList();
list.add("virat");
list.add("anushka");
}
..
..
code under service() method
---------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
// validation1
if (name.trim().equalsIgnoreCase("manohar") && pass.trim().equalsIgnoreCase("manohar")) {
out.println("<h1>Login sucess</h1>");
}
else {
out.println("<h1>Login not sucess!!!Please enter valid credentials</h1>");
}
//validation2
if (name.trim().equalsIgnoreCase(s[0]) && pass.trim().equalsIgnoreCase(s[1])) {
out.println("<h1>Login sucess</h1>");
}
else {
out.println("<h1>Login not sucess!!!Please enter valid credentials</h1>");
}
//validation3
String n=(String) list.get(0);
String p=(String) list.get(1);
if (name.trim().equalsIgnoreCase(n) && pass.trim().equalsIgnoreCase(p)) {
out.println("<h1>Login sucess</h1>");
} else {
out.println("<h1>Login not sucess!!!Please enter valid credentials</h1>");
}
out.close();
getParameter()
-------------
This method is used to get data(parameters) from a form.
It is available in ServletRequest interface.
Method signature
----------------
public String getParameter(String);
How to read a parameter from a form
-----------------------------------
syntax
------
String varname=request.getParameter("identifier");
Types of servlets
-----------------
There are 2 types of servlets in Servlet API
i)GenericServlet
ii)HttpServlet
GenericServlet
--------------
It is implementation class of Servlet interface.
It is abstract class because service of GenericServlet is abstract.
The serive() method in GenericServlet is abstract because it is developer responsibility to override service() method according to project requirements.
GenericServlet supports all the protocols like http,ftp,tcp/ip,smtp etc
It is available in the package javax.servlet.* package.
GenericServlet also implements 2 interfaces
i)Serializable
ii)ServletConfig
Methods of GenericServlet
-------------------------
public javax.servlet.GenericServlet();
public void destroy();
public java.lang.String getInitParameter(java.lang.String);
This method is used to read initialization parameters from web.xml file.
public java.util.Enumeration<java.lang.String> getInitParameterNames()
public javax.servlet.ServletConfig getServletConfig();
return ServletConfig object.
public javax.servlet.ServletContext getServletContext();
return ServletContext object.
public java.lang.String getServletInfo();
returns Servlet information.
public void init(javax.servlet.ServletConfig) throws javax.ser
tion;
performs initialization of servlet.
public void init() throws javax.servlet.ServletException;
performs initialization of servlet.
public void log(java.lang.String);
performs logging
public void log(java.lang.String, java.lang.Throwable);
performs logging.
public abstract void service(javax.servlet.ServletRequest, javtResponse) throws javax.servlet.ServletException, java.io.IOException
provides service to client.
public java.lang.String getServletName();
returns Servlet name.
Life cycle methods of Generic Servlet
-------------------------------------
A GenericServlet consists of 4 life cycle methods.
i)init(ServletConfig)
ii)init()
iii)service(ServletRequest req,ServletResponse)
iv)destroy()
why 2 init() method in GenericServlet
init(ServletConfig):
This method is always called tomcat to perform initialization task,it is also called as container's init() method.
init()
This method is used by developer to perform initialization task.
Execution flow of GenericServlet
--------------------------------
when a client makes a request to GenericServlet the following steps are implemented by container to process servlet.
step1:loading servlet into memory.
step2:Instantiating Servlet
step3:creating ServletConfig object
step4:invoke parameterized init() method by passing ServletConfig as a parameter.
step5:Parameterized init() will invoke default init() method.
step6:creating objects for ServletRequest,ServletResponse objects and invokes service() method by passing these objects as parameters to service().
step7:destroy method is called.
Create a Project FruitProject to demonstrate generic servlet.
Add servlet-->FruitServlet.java
How to Add Generic servlet.
Goto src-->package->right click-->new-->servlet-->
name as-->FruitServlet
Superclass-->javax.servlet.GenericServlet
click on finish.
FruitServlet.java
-----------------
@WebServlet("/FruitServlet")
public class FruitServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
ArrayList<String> list=null;
public void init(){
list=new ArrayList<String>();
}
code under service() method
---------------------------
//reading form
String s1=request.getParameter("f1");
String s2=request.getParameter("f2");
String s3=request.getParameter("f3");
String s4=request.getParameter("f4");
String s5=request.getParameter("f5");
//adding data to collection
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
//Iterating collections
Iterator<String> iterator=list.iterator();
PrintWriter out=response.getWriter();
while(iterator.hasNext()){
out.println(iterator.next());
}
out.close();
}
fruit.html
----------
<form action="./FruitServlet" method="get">
Enter Fruit1:<input type="text" name="f1"/><br>
Enter Fruit2:<input type="text" name="f2"/><br>
Enter Fruit3:<input type="text" name="f3"/><br>
Enter Fruit4:<input type="text" name="f4"/><br>
Enter Fruit5:<input type="text" name="f5"/><br>
<input type="submit" value="Dsiplay"/>
initialization parameters in servlets
-------------------------------------
Initialization parameters are name and value pairs declared in web.xml using a tag <init-param>.
syntax
------
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
we should declare <init-param> tag as a child tag to <servlet> tag.
we declare properties like credentials,jdbc properties,network proprties etc as initialization parameters.
How to read initialization parameters
-------------------------------------
we read initialization parameters by using ServletConfig interface.
ServletConfig
-------------
It is an interface available in javax.servlet.* package.
It is used to read configuration details of servlet declared in web.xml or @WebServlet annotation.
Method summary
--------------
public String getServletName();
returns servlet name.
public ServletContext getServletContext();
returns ServletContext object.
public String getInitParameter(java.lang.String);
gets initialization parameters from web.xml file.
public Enumeration<java.lang.String> getInitParameterNames(
);
gets all names of initialization parameters in the form of Enumeration.
How to get initialization parameters from web.xml
-------------------------------------------------
String varname=config.getInitParameter("identifier");
creating a webproject to demonstrate initialization parameters.----------------------------------------
-----------
create a dynamicwebproject-->LoginServlet
Add web.xml file under-->webcontent-->WEB-INF-->web.xml
code under web.xml
------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.manohar.servlets.LoginServlet</servlet-class>
<init-param>
<param-name>user</param-name>
<param-value>manohar</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>java</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Add a servlet-->LoginServlet.java
override parameterized init() and read initialization parameters from web.xml file using methid getInitParameter().
public class LoginServlet extends GenericServlet {
// declaring instance variables
String userName = null;
String passWord = null;
@Override
public void init(ServletConfig config) throws ServletException {
// reading initialization parameters from web.xml
userName = config.getInitParameter("user");
passWord = config.getInitParameter("password"); System.out.println(userName);
System.out.println(passWord);
}
code under service method
-------------------------
// reading form
String user = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
if (user.equalsIgnoreCase(userName) && pass.equalsIgnoreCase(passWord)) {
out.println("<h1>Login Success</h1>");
}
else {
out.println("<h1>Login UnSuccessful!!!Please enter valid credentials</h1>");
}
}
Type the following url in browser to run the application
http://localhost:8070/ServletConfigProject/login.html
Approach2 to read initialization parameters
-------------------------------------------
This time we don't need override init(ServletConfig) but we can also get ServletConfig object by using the getServletConfig() which is overridden in GenericServlet.
How to get ServletConfig object
-------------------------------
syntax
------
ServletConfig config=getServletConfig();
code under service method
-------------------------
//get ServletConfig object
ServletConfig config=getServletConfig();
String userName=config.getInitParameter("user");
String passWord=config.getInitParameter("password");
// reading form
String user = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
if (user.equalsIgnoreCase(userName) && pass.equalsIgnoreCase(passWord)) {
out.println("<h1>Login Success</h1>");
}
else {
out.println("<h1>Login UnSuccessful!!!Please enter valid credentials</h1>");
}
Important points to remember
----------------------------
i)we know that ServletConfig is used to maintain configuration details of a Servlet
How many config objects are created for a servlet
-------------------------------------------------
For each servlet one config object is created,no of config created in a project is dependent on no of servlets in the project.
--------------------------------------------
|No of servlets=No of Servletconfig objects|
--------------------------------------------
we should declare initialization parameters for each servlet seperately.
when should we declare parameters as initialization parameters
If the propertied changes from one servlet to another servlet while configuring in web.xml file,in such case we declare initialization parameters for each servlet seperately.
Context parameters
------------------
If we want to maintain application wide data then we should use context parameters.
we configure context parameters in web.xml file by using <context-param> tag.
context parameters are declared in the form of name(key) and value pairs.
syntax
------
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
ServletContext
--------------
It is an interface available in javax.servlet.* package.
It is used to maintain application wide data.
ServletContext object is common for all the servlets in a project.
Method summary
--------------
public String getInit
Parameter(String);
get context parameters from web.xml
public void setAttribute(String,Object);
stores an object into ServletContext object.
public Object getAttribute(String);
returns object from ServletContext.
public void removeAttribute(string);
remove an object from ServletContext.
ServletContext object holds data in the form of name and value pairs.
How to get ServletContext object
--------------------------------
we get ServletContext object by using the getServletContext() available in ServletConfig interface/ServletRequest interface.
syntax
------
ServletContext context=request.getServletContext();
create a project-->ServletContextProject
Add web.xml
-----------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>user</param-name>
<param-value>manohar</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>manohar</param-value>
</context-param>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.manohar.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Add servlet-->LoginServlet.java
code under service method
-------------------------
//get ServletConfig object
ServletContext context=request.getServletContext();
//reading context parameters
String userName=context.getInitParameter("user");
String passWord=context.getInitParameter("pass");
// reading form
String user = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
if (user.equalsIgnoreCase(userName) && pass.equalsIgnoreCase(passWord))
{
out.println("<h1>Login Success</h1>");
}
else {
out.println("<h1>Login UnSuccessful!!!Please enter valid credentials</h1>");
}
login.html
----------
<form action="./login" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Project url to run application
------------------------------
http://localhost:8070/ServletContextProject/login.html
Differences between ServletConfig and ServletContext
----------------------------------------------------
ServletConfig ServletContext
i)It is an interface It is an interface available in available in
javax.servlet.* javax.servlet.*
ii)This used to read This is used to
initialization parameters context parameters.
of a servlet.
3)Per each servlet One Context object
one config object per project.
is created.
4)we use method we use method getInitParameter() getInitParameter()
to read initialization to read context
parameters parameters
5)we use the we the tag <context-param>
<init-param> to declare context to declare initialization parameters
parameters in web.xml
6)we use the method we use the method
getServletConfig() getServletContext()
to get ServletConfig to get ServletContext
available in Servlet object available in
interface ServletConfig /ServleRequest interfaces.
How many implicit objects are created by Container to process a servlet?
ServletConfig
ServletContext
ServletRequest
ServletResponse
Note:For each client request one request and response object is created by container.
Creating Employee Management System
-----------------------------------
create a project struture
-------------------------
JavaResource
src
com.manohar.controller
LoginController.java
EmployeeController.java
com.manohar.model
Employee.java
com.manohar.service
EmployeeService.java
EmployeeServiceImpl.java
com.manohar.dao
EmployeeDAO.java
EmployeeDAOImpl.java
creating a web application to insert an employee record into a table using Servlet with jdbc connectivity.
step1:create a table employee
empname
empid primary key
empsal
step2:
create a html-->AddEmployee.html
action="./AddServlet"
EmpID
EmpName
EmpSal
step3:
create a pojo
com.manohar.model
Employee.java
empName
empID
empSal
step4:
create Servlet-->AddServlet.java
code under service
------------------
//read form
//convert id to int.
//convert sal to double.
//implement jdbc steps to insert a record into employee //table.
AddEmployee.html
----------------
<form action="./AddEmployeeServlet">
Enter Name:<input type="text" name="name"/><br>
Enter ID:<input type="text" name="id"/><br>
Enter Salary:<input type="text" name="sal"/><br>
<input type="submit" value="Save"/><br>
</form>
Add Pojo-->Employee.java
package com.manohar.model;
public class Employee {
private String empName;
private int empID;
private double empSal;
//setters and getters
}
Add AddEmployeeServlet.java
---------------------------
code under service method
-------------------------
//read form
String name=request.getParameter("name");
String id=request.getParameter("id");
String sal=request.getParameter("sal");
int empid=Integer.parseInt(id);
double empsal=Double.parseDouble(sal);
//setting properties to pojo
Employee employee=new Employee();
employee.setEmpID(empid);
employee.setEmpName(name);
employee.setEmpSal(empsal);
Connection connection=null;
PreparedStatement statement=null;
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
try{
//jdbc steps
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection(url, user, pass);
//sql
String sql="insert into employee values(?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,employee.getEmpName());
statement.setInt(2, employee.getEmpID());
statement.setDouble(3,employee.getEmpSal());
int status=statement.executeUpdate();
response.getWriter().println(status+"records inserted");
}
catch (Exception e) {
}
finally{
try {
statement.close();
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
creating service layer
----------------------
Add EmployeeService.java(interface)
EmployeeServiceImpl.java(class)
EmployeeService.java
--------------------
public interface EmployeeService {
public int insert(Employee employee);
public int update(Employee employee);
public int delete(int empid);
public Employee selectEmployee(int empid);
}
EmployeeServiceImpl.java
------------------------
public class EmployeeServiceImpl implements EmployeeService{
private EmployeeDAO dao=null;
public EmployeeServiceImpl(){
dao=new EmployeeDAOImpl();
}
@Override
public int insert(Employee employee) {
int status=dao.insert(employee);
return status;
}
@Override
public int update(Employee employee) {
int status=dao.update(employee);
return status;
}
@Override
public int delete(int empid) {
int status=dao.delete(empid);
return status;
}
@Override
public Employee selectEmployee(int empid) {
Employee employee=dao.selectEmployee(empid);
return employee;
}
}
creating DAO Layer
------------------
Add EmployeeDAO.java
EmployeeDAOImpl.java
EmployeeDAO.java
----------------
public interface EmployeeDAO {
public int insert(Employee employee);
public int update(Employee employee);
public int delete(int empid);
public Employee selectEmployee(int empid);
}
EmployeeDAOImpl.java
--------------------
public class EmployeeDAOImpl implements EmployeeDAO {
private Connection connection = null;
private PreparedStatement statement = null;
public int insert(Employee employee) {
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
String sql = "insert into employee values(?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1, employee.getEmpName());
statement.setInt(2, employee.getEmpID());
statement.setDouble(3, employee.getEmpSal());
status = statement.executeUpdate();
statement.close();
connection.close();
}
catch (Exception e) {
System.out.println(e);
}
return status;
}
public int update(Employee employee) {
System.out.println("update");
String sql = "update employee set name=?,sal=? where id=?";
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
statement = connection.prepareStatement(sql);
statement.setInt(3, employee.getEmpID());
statement.setString(1, employee.getEmpName());
statement.setDouble(2, employee.getEmpSal());
status = statement.executeUpdate();
statement.close();
}
catch (Exception e) {
System.out.println(e);
}
return status;
}
public int delete(int empid) {
String sql = "delete from employee where id=?";
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
statement = connection.prepareStatement(sql);
statement.setInt(1, empid);
status = statement.executeUpdate();
statement.close();
} catch (Exception e) {
System.out.println(e);
}
return status;
}
public Employee selectEmployee(int empid) {
String sql = "select *from employee where id=?";
Employee employee = new Employee();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
statement = connection.prepareStatement(sql);
statement.setInt(1, empid);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
employee.setEmpID(rs.getInt("id"));
employee.setEmpName(rs.getString("name"));
employee.setEmpSal(rs.getDouble("sal"));
}
statement.close();
} catch (Exception e) {
System.out.println(e);
}
return employee;
}
}
HttpSession
-----------
It is an interface available in javax.servlet.http.* package.
It is an object which hold data in the form key and value pairs.
HttpSession is very useful in implmenting SessionManagement/SessionTracking.
Method summary
--------------
public long getCreationTime();
public String getId();
public long getLastAccessedTime();
public ServletContext getServletContext();
public void setMaxInactiveInterval(int);
public int getMaxInactiveInterval();
public HttpSessionContext getSessionContext();
public Object getAttribute(java.lang.String);
public Object getValue(java.lang.String);
public Enumeration<java.lang.String>
getAttributeNames();
public String[] getValueNames();
public void setAttribute(String,Object);
public void putValue(String,Object);
public void removeAttribute(String);
public void removeValue(String);
public void invalidate();
public boolean isNew();
How to get session object
--------------------------
we get HttpSession object by using method getSession() available in HttpServletRequest interface.
public HttpSession getSession();
This method checks if a Session object is already associated with request and returns that object otherwise create a new Session object and return that.
public HttpSession getSession(true);
It is same as default getSession() if the parameter to getSession is true
if the parameter is false then this method checks if a Session object is already associated with request and returns that object otherwise returns null,here no new Session object is created.
syntax
------
HttpSession session=request.getSession();
creating a webApplication to demonstrate Session object
-------------------------------------------------------
login.html
----------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
LoginServlet.java
-----------------
code under doGet()
------------------
//reading form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
//create Session object
HttpSession session=request.getSession();
session.setAttribute("name",name);
session.setAttribute("pass",pass);
//create dispatcher
RequestDispatcher dispatcher=request.getRequestDispatcher("WelcomeServlet");
dispatcher.include(request,response);
WelcomeServlet.java
-------------------
code under doGet()
------------------
//get Session object
HttpSession session=request.getSession();
String u=(String) session.getAttribute("name");
String p=(String) session.getAttribute("pass");
//create PW
PrintWriter out=response.getWriter();
out.println("The name is "+u);
out.println("The pass is "+p);
out.close();
Session Tracking
----------------
when ever a client make a request to a server,the server will process the request and send the response,once the response is sent back server will forget about client information because of the stateless nature of http.
Suppose we are performning an online transaction where it requires number of request and response cycles to complete transaction,in this situation server has to remember client information.so to maintain client information at server side we need session management/Tracking.
Session Tracking is a mechanism of maintaining client information by server either at server side or client side.
we implement Session Tracking using the following techniques.
i)HttpSession
ii)Cookies.
iii)urlrewriting
iv)hidden form fields.
HttpSession
-----------
whenever a client makes a request to a server,the server will check whether the request is a new or not,if the request is a new request,server will create a new Session object and allocate this session object for the client to process subsequent request and response cycles.
Along with Session object one Session id is also created for each session,this id is used to identify a client by server.
For the first time server will process the request of client and sent back the response to client along with id and from next onwards while client is making request it will send sessionid along with request
client --->req1 -----> server
<---res1+sessionid<-----
req2+sessionid----->
<---res2+sessionid<-----
...
...
Setting time out for a session
------------------------------
we can set a timeout for a session in 2 ways
i)programmatic approach.
ii)declarative approach(xml).
Programmatic approach
---------------------
we provide session time out period programattically by using the method setMaxInactiveInterval() available in HttpSession interface.
Method signature
----------------
public void setMaxInactiveInterval(int);
Here time is represented in seconds.
code:
HttpSession session=request.getSession();
session.setMaxInactiveInterval(120);
Declarative approach
-------------------
we represent session timeout using the following tags in web.xml file
<webapp>
<session-config>
<session-timeout>value</session-timeout>
</session-config>
..
..
</webapp>
This process setting time out using xml is called declarative approach.
Here the timeout period is represented in minutes.
create a webapplication to demonstarte session-timeout
------------------------------------------------------
Add login.html
--------------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add a Servlet-->LoginServlet.java
code under doGet()
------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
// create Session object
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
if (session.isNew())
{
out.println(session.getId()+"<br>");
}
else
{
out.println(session.getId()+"<br>");
}
session.setAttribute("name", name);
session.setAttribute("pass", pass);
session.setMaxInactiveInterval(120);
// create dispatcher
RequestDispatcher dispatcher = request.getRequestDispatcher("WelcomeServlet");
dispatcher.include(request, response);
Add a servlet-->WelcomeServlet.java
code under doGet
----------------
// get Session object
HttpSession session = request.getSession();
String u = null;
String p = null;
PrintWriter out = response.getWriter();
if (session != null) {
u = (String) session.getAttribute("name");
p = (String) session.getAttribute("pass");
out.println(session.getId()+"<br>");
}
//
long l1 = session.getCreationTime();
long l2 = session.getLastAccessedTime();
// create PW
out.println("The name is " + u);
out.println("The pass is " + p);
out.println("The session created time " + new Date(l1));
out.println("The session accessed time " + new Date(l2));
out.close();
Invalidating a session
----------------------
we invalidate a session by using method invalidate() available in HttpSession interface.
syntax
------
public void invalidate();
code:
HttpSession session=request.getSession();
session.invalidate();
Cookie
------
A cookie is technique used to implement Session Tracking.
A cookie is a small text file which maintains data in the form of key and value pairs.
A cookie is created by a server and maintained at client side
A Cookie is a class available in javax.servlet.http.* package.
Constructor summary
-------------------
public Cookie(String,String)
create a cookie with key and value pair
Method summary
--------------
public void setMaxAge(int);
set expiry time to cookie.
public int getMaxAge();
gets expiry time of cookie
public String getName();
returns name of cookie.
public void setValue(String);
set a value to cookie.
public String getValue();
get a value from a cookie.
Types of cookies
----------------
There are 2 types of cookies
i)Session Cookie(temporary cookie)
ii)Persistnat cookie(perminent)
Session cookie
--------------
whenever there is a session(transaction) happening between a client and server,to identify the client by server cookie is used.
If cookie is maintained in browser memory temporarily untill the session is completed,such kind of cookie is called session cookie.
Execution flow of cookies between client and server
--------------------------------------------------
when a client make a request to a server,server will check whether the request is new,if a new a request is coming from client then server will create a cookie and send the response to the client along with cookie as shown in diagram.
From next time onwards client will send a cookie along with request so that server can identify client in the subsequent request and resonse cycles.
In this way session tracking is implemented using cookie.
How to create a cookie
----------------------
we can create cookie by using parameterized constructor.
syntax
------
Cookie cookie=new Cookie(String,String);
ex:
Cookie cookie=new Cookie("user","user");
Adding cookie to response
-------------------------
Once after we create cookie we should add cookie to response by using the method addCookie() available in HttpServletResonse.
Method signature
----------------
public void addCookie(Cookie);
syntax
------
resonse.addCookie(cookie);
step3:reading cookie coming from client request.
-----
we read cookies coming with a request from a client by using the method getCookies available in HttpServletRequest.
Method signature
----------------
public Cookie[] getCookies();
syntax
------
Cookie cookie[]=request.getCookies();
for(Cookie c1:cookie)
{
String name=c1.getName();
String value=c1.getValue();
..
..
..
}
creating a web application to demonstrate session cookie
--------------------------------------------------------
Add->login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add-->LoginServlet.java
code under doGet() method
-------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
//created cookie
Cookie cookie1=new Cookie("user",name);
Cookie cookie2=new Cookie("pass",pass);
//adding cookie to response
response.addCookie(cookie1);
response.addCookie(cookie2);
PrintWriter out=response.getWriter();
out.println("<form action='./WelcomeServlet'>");
out.println("<input type='submit' value='Go'/>");
out.println("</form>");
out.close();
Add-->WelcomeServlet.java
-------------------------
code under doGet()
------------------
Cookie cookie[] = request.getCookies();
PrintWriter out = response.getWriter();
for (Cookie c : cookie) {
String name = c.getName();
String value = c.getValue();
out.println("Nam is "+name+"<br>");
out.println("value is "+value+"<br>");
}
Execution Flow
--------------
step1:client make a request to LoginServlet
step2:Servler will execute LoginServlet,create cookie and set username and password to cookies and add them to response,along with cookies,server also sent dynamic form to client which will make a request to WelcomeServlet.
step3:
Once we click on Go button request is sent to welcomeServlet and reads cookies sent with the request and displays.
Persistent cookie
-----------------
A cookie with life time is known as persistant cookie.
A persistent cookie is stored into a browser memory perminently(i,e untill time expires).
Persistent cookie=Session cookie+expiry time.
How to set expiry time to Cookie
--------------------------------
we set expiry time to cookie by using the method setMaxAge() available in Cookie class.
syntax
------
cookie.setMaxAge(int);
Here we should represent time in seconds.
Application
-----------
In the above code add expiry time for cookies as shown in below
code
----
//created cookie
Cookie cookie1=new Cookie("user",name);
Cookie cookie2=new Cookie("pass",pass);
//setting expiry time to cookie
cookie1.setMaxAge(120);
cookie2.setMaxAge(120);
Note:
We can find persistant cookies in browser(Internet explorer) memory in the following path.
Goto Browser-->tools-->internet options-->browsing history-->settings-->view files.
Disadavantes of cookies
-----------------------
i)Cookies can deleted from browser,if such is the case session tracking may fail.
ii)Cookie is a text file and storing confidential information in cookies is not secured.
Note:
A cookie internally has a session id which is implicitly included by server at the time of cookie creation.
Session id helps server in session Tracking.
Url Rewriting
-------------
If we are using cookie to implement session tracking there is a possibility of deleting cookies from browser memory,in such situation session tracking may fail to avoid this urlrewriting is used.
Url rewriting is a technique of appending parameters with an url.
syntax
------
url?key1=value1&key2=value2&.......
sendRedirect()
--------------
It is a method which is used to navigate from one servlet to another servlet by informing to browser(through browser).
This method is available in HttpServletResponse interface.
syntax
------
response.sendRedirect("url?key1=value1&key2=value2&....");
Creating webapplication to demonstrate urlrewrting
--------------------------------------------------
Add-->login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add-->LoginServlet.java
-----------------------
code under doGet()
------------------
//read form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
//
String url="./WelcomeServlet?user="+name+"&pass="+pass+" ";
response.sendRedirect(url);
Add-->WelcomeServlet.java
-------------------------
code under doGet()
------------------
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println("Welcome "+name);
out.println("your password "+pass);
out.close();
Hidden form fields
------------------
It is a state management technique where data is transeferred between client and server in hidden i,e implicitly.
How to declare a hidden form field
----------------------------------
We declare a hidden form field by using the tag shown below
<input type="hidden" name="" value=""/>
creating a webApplication to demonstrate hidden form fields
------
Add-->login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add-->LoginServlet.java
code under doGet()
-----------------
//read form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println("<form action='./WelcomeServlet'/>");
out.println("<input type='hidden' name='user' value="+name+"/><br>");
out.println("<input type='hidden' name='pass' value="+pass+"/><br>");
out.println("<input type='submit' value='GetData'/>");
out.println("</form>");
out.close();
Add-->WelcomeServlet.java
code under doGet()
------------------
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println("Welcome "+name);
out.println("your password "+pass);
out.close();
Note:
How to remove a cookie from a client
------------------------------------
we can delete a cookie from a client by server by passing time as 0(zero)
cookie.setMaxAge(0);
}
storing and selecting file with database
----------------------------------------
We use character streams to handle files.
We use a datatype clob[character large object] to store a file into a table.
create a table to store a file
--------------------------------
create table filetable(id int primary key,files clob);
How to store file into table using jdbc
----------------------------------------
To store file into a table we use the method setCharacterStream() available in PreparedStatement.
syntax
------
public void setCharacterStream(int,Reader) throws SQLException;
public void setCharacterStream(int,Reader,long) throws SQLException;
File path:
D:\Test.java
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FileStoreDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
// open file
FileReader in = new FileReader("D:\\Test.java");
// jdbc propertoes
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql
String sql = "insert into filetable values(?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,1);
statement.setCharacterStream(2,in);
int status=statement.executeUpdate();
System.out.println(status+"inserted");
in.close();
statement.close();
connection.close();
}
}
selecting file from a table
----------------------------
To select a file from a file we use the method getClob() available in ResultSet.
syntax
------
public Clob getClob(int index);
or
public Clob getClob(String colname);
getClob() returns Clob object.
To initialize Clob object we use the class Clob available in java.sql.*.
ex:
Clob b=rs.getClob(2);
To read file we have to convert Clob to Reader.
we use the method getCharacterStream() to convert Clob to Readeravailable in
Clob class.
syntax
------
public Reader getCharacterStream();
ex:
Reader reader=clob.getCharacterStream();
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FileStoreDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql
String sql = "select *from filetable";
PreparedStatement statement = connection.prepareStatement(sql);
//
ResultSet set=statement.executeQuery();
Reader reader=null;
FileWriter out=null;
while(set.next()){
int id=set.getInt(1);
Clob clob=set.getClob(2);
reader=clob.getCharacterStream();
out=new FileWriter("d:\\Manohar.java");
int val;
while((val=reader.read())!=-1){
System.out.print((char)val);
out.write((char)val);
}
}
reader.close();
out.close();
set.close();
statement.close();
connection.close();
}
}
ResultSet is of 2 types
i)unidirectional[Forward only'
ii)Bi directional[Forward and backward]
By deafult ResultSet is Forward only and Readonly cursor.
When you create a ResultSet there are three attributes you can set to make ResultSet bidirectional and updatable.
These are:
Type
Concurrency
Holdability
There are three ResultSet types:
ResultSet.TYPE_FORWARD_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
The changes in database doesn't impact ResultSet.
ResultSet.TYPE_SCROLL_SENSITIVE
The changes in database will impact ResultSet.
Concurrency
-----------
It specifies type of operation we are performing
i)read_only
ii)Updatable
Holdability
-----------
This specfies whether to close ResultSet after committing changes or not.
Method Description
-------------------
absolute()
Moves the ResultSet to point at an absolute position.
The position is a row number passed as parameter to the absolute() method.
afterLast()
Moves the ResultSet to point after the last
row in the ResultSet.
beforeFirst()
Moves the ResultSet to point before the first row in the ResultSet.
first()
Moves the ResultSet to point at the first row in the ResultSet.
last()
Moves the ResultSet to point at the last row in the ResultSet.
next()
Moves the ResultSet to point at the next row in the ResultSet.
previous()
Moves the ResultSet to point at the previous row in the ResultSet.
relative()
Moves the ResultSet to point to a position relative to its current position.
The relative position is passed as a parameter to the relative method, and can be both positive and negative.
Moves the ResultSet
How to get Scrollable and updatable ResultSet
---------------------------------------------
We to get Scrollable and updatable ResultSet then while creating Statement or PreparedStatement object we have pass the 3 attributes
i)type
ii)concurency
ii)Holdability
syntax
------
PreparedStatement statement=connection.prepareCall(Sql,type,concurrency,holdability);
ex:
PreparedStatement statement=connection.prepareCall(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE ,ResultSet.HOLD_CURSORS_OVER_COMMIT);
Methods to update ResultSet
---------------------------
The following methods are used to update columns of a table through ResultSet.
public void updateString(int index,String value);
public void updateString(String colname,String value);
public void updateInt(int index,int value);
public void updateInt(String colname,int value);
public void updateByte(int index,byte value);
public void updateByte(String colname,byte value);
public void updateShort(int index,short value);
public void updateShort(String colname,short value);
public void updateLong(int index,long value);
public void updateLong(String colname,long value);
public void updateFloat(int index,float value);
public void updateFloat(String colname,float value);
public void updateDouble(int index,double value);
public void updateDouble(String colname,double value);
public void updateBoolean(int index,boolean value);
public void updateBoolean(String colname,boolean value);
public void updateRow();
This method is used to update a row in a table,once we set values using updateXXXX() methods,we should call updateRow() method.
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JdbcResultSetMetaDataDemo {
public static void main(String[] args) throws ClassNotFoundException,SQLException, IOException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql
String sql="select name,id,sal from employee";
PreparedStatement statement = connection.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
ResultSet rs = statement.executeQuery();
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt("id");
if (id == 20) {
rs.updateString("name", "Manohar");
rs.updateInt("id", 200);
rs.updateDouble("sal", 2000.00);
rs.updateRow();
}
System.out.println(rs.getInt("id"));
}
rs.afterLast();
while (rs.previous()) {
System.out.println(rs.getInt("id"));
}
rs.first();
System.out.println(rs.getInt("id"));
rs.absolute(5);
System.out.println(rs.getInt("id"));
rs.relative(-2);
System.out.println(rs.getInt("id"));
rs.last();
System.out.println(rs.getInt("id"));
in.close();
rs.close();
statement.close();
connection.close();
}
}
RowSet[inteface]
----------------
i)It is simplified form of ResultSet.
ii)It is available in javax.sql.*;
iii)It followd Pojo[Java bean] pattern i,e it consists of setters and getters.
iv)A RowSet has the following child interfaces.
CachedRowSet
FilteredRowSet
JdbcRowSet
JoinRowSet
SyncResolver
WebRowSet
JdbcRowSet[interface]
---------------------
This is similar to ResultSet,it is wrapper of a ResultSet interface.
To instantiate any RowSet interface we need the following entities
i)RowSetFactory[javax.sql.*]
ii)RowSetProvider[javax.sql.*]
RowSetFactory
-------------
It provides factory methods to instantiate different RowSet interfaces like JdbcRowSet,CachedRowSet.
Method summary
--------------
public CachedRowSet createCachedRowSet()
Creates a new instance of a CachedRowSet.
public FilteredRowSet createFilteredRowSet()
Creates a new instance of a FilteredRowSet.
public JdbcRowSet createJdbcRowSet()
Creates a new instance of a JdbcRowSet.
public JoinRowSet createJoinRowSet()
Creates a new instance of a JoinRowSet.
public WebRowSet createWebRowSet()
Creates a new instance of a WebRowSet.
RowSetProvider
--------------
It is a class which provides static factory methods to instantiate RowSetFactory interface.
Methods
-------
public RowSetFactory newFactory() throws SQLException;
How to get JdbcRowSet object
-----------------------------
step1
-----
RowSetFactory factory=RowSetProvider.newFactory();
step2:
------
JdbcRowSet set=factory.createJdbcRowSet();
JdbcRowSet
----------
It provides setters and getters to perform jdbc operations on a database.
Methods
-------
public void setUrl(Stri
ng);
public void setUsername(String);
public void setPassword(String);
public void setCommand(String);
public void setXXX(datatype);
public String getString(int);
public String getString(String);
public String getInt(int);
public String getInt(String);
public datatype getXXX(int);
public datatype getXXX(String);
public boolean next()
publlic execute() throws SQLException
Write a jdbc program to get rows from a table and iterate them using RowSet.
package com.manohar.satya.jdbc;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
public class JdbcRowSetDemo {
public static void main(String[] args) throws SQLException {
//step1
RowSetFactory factory=RowSetProvider.newFactory();
//step2
JdbcRowSet set=factory.createJdbcRowSet();
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
set.setUrl(url);
set.setUsername(user);
set.setPassword(pass);
set.setCommand("select *from employee");
set.execute();
while(set.next()){
String name=set.getString(1);
System.out.println(name);
}
}
}
Note:
It is not necessary to load jdbc driver in jdbc4.0 version.
Servlet Collaboration
---------------------
Communication between two servlets is known as ServletCollaboration.
we can navigate from one servlet to another using the following techniques.
i)RequestDispatcher
ii)Hyperlink
iii)sendRedirect
we can exchange data from one Servlet to another by using attributed approach.
we use the following methods to perform read,write,remove operations between 2 servlets.
i)setAttribute()
sets data to a scope.
ii)getAttribute()
gets data from a scope
iii)removeAttribute()
remove data from a scope.
what is a scope?
A scope is can be defined as the extent of service that can be provided by an Object.
we have 3 differet scope's in servlet.
i)request scope
ii)application scope(ServletContext)
iii)Session scope.
request scope is useful to exachange data between 2 servlets in one request and response cycle.
application scope is useful to exchange data between 2 servlets untill a project is running.
Session scope is useful to exchange data between 2 servlets with in a given a session.
we can write,read,remove data with all the above scopes using above 3 methods.
setAttribute()
--------------
It is used to set data to a scope.
Method signature
----------------
public void setAttribute(String,Object);
How set data to a scope
-----------------------
syntax
------
reference.setAttribute(String,Object);
Here reference is reference of request\application\session
ex:
request.setAttribute("user","manohar");
getAttribute()
--------------
It returns object from a scope.
Method signature
----------------
public Object getAttribute(String);
How to get data a scope
-----------------------
syntax
------
reference.getAttribute(String);
ex:
request.getAttribute("user");
removeAttribute()
-----------------
removes an object from a scope.
Method signature
----------------
public void removeAttribute(String);
syntax
------
request.removeAttribute(String);
ex:
request.removeAttribute("user");
RequestDispatcher
-----------------
It is an interface used to navigate from one servlet to another servlet.
It is available in javax.servlet.* package.
we have 2 types of dispatching techniques.
i)include.
ii)forward.
include mechanism
-----------------
In this technique,if we have 2 servlets Servlet1,Servlet2,
when a client makes a request,the request is sent to servlet1 and from there servlet1 dispatches a request to servlet2 using include() method,here once servlet2 process the request,the response is sent back to servlet1 and finally servlet1 will send back response to client.
forward mechanism
-----------------
In this technique,if we have 2 servlets Servlet1,Servlet2,
when a client makes a request,the request is sent to servlet1 and from there servlet1 dispatches a request to servlet2 using foward() method,here once servlet2 process the request,the response is sent back to client directly from servlet2 without giving any notification servlet1.
How to get RequestDispatcher object.
-----------------------------------
we get RequestDispatcher object by using the getRequestDispatcher() available in ServletRequest iinterface.
Method signature
----------------
public RequestDispatcher getRequestDispatcher(String url);
syntax
------
RequestDispatcher dispatcher=request.getRequestDispatcher(String);
ex:
RequestDispatcher dispatcher=request.getRequestDispatcherS("WelcomeServlet");
How to call include() method
----------------------------
syntax
------
dispatcher.include(request,response);
How to call forward() method
----------------------------
syntax
------
dispatcher.forward(request,response);
creating a webapplication to navigate from one Servlet to another servlet
Requirement
-----------
validate a login form and naviagate to WelcomeServlet if validation is successful otherwise navigate to ErrorServlet.
login.html
----------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
create LoginServlet.java
------------------------
code under service method
-------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
// creating Dispacher Objects
RequestDispatcher dispatcher1 = request.getRequestDispatcher("WelcomeServlet");
RequestDispatcher dispatcher2 = request.getRequestDispatcher("ErrorServlet");
if (name.trim().equalsIgnoreCase("manohar") && pass.trim().equalsIgnoreCase("manohar")) {
dispatcher1.include(request, response);
}
else
{
dispatcher2.include(request, response);
}
create WelcomeServlet.java
--------------------------
code under service() method
---------------------------
PrintWriter out=response.getWriter();
out.println("Login Success");
out.close();
create ErrorServlet.java
------------------------
code under service() method
---------------------------
PrintWriter out=response.getWriter();
out.println("Login UnSuccess!!!Please valid credentials");
out.close();
Url
---
http://localhost:8070/LogingProject/login.html
creating a webapplication to validate credentials and share them from LoginServlet to WelcomeServlet using request sacope.Also using Map to set credentials and share to WelcomeServlet.
login.html
----------
copy from above program
create LoginServlet.java
------------------------
code under service() method
---------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
// creating Dispacher Objects
RequestDispatcher dispatcher1 = request.getRequestDispatcher("WelcomeServlet");
RequestDispatcher dispatcher2 = request.getRequestDispatcher("ErrorServlet");
//creating HashMap
HashMap<String,String> map=new HashMap<String,String>();
if (name.trim().equalsIgnoreCase("manohar") && pass.trim().equalsIgnoreCase("manohar")) {
//setting user to request attribute. request.setAttribute("user",name);
request.setAttribute("pass",pass);
//setting credentials to Map
map.put("user",name);
map.put("pass",pass);
//setting object to request scope
request.setAttribute("map",map);
dispatcher1.include(request, response);
}
else
{
dispatcher2.include(request, response);
}
create WelcomeServlet.java
--------------------------
code under service
------------------
PrintWriter out=response.getWriter();
//reading String
String user=(String) request.getAttribute("user");
String pass=(String) request.getAttribute("pass");
//reading Map
Map<String,String> map=(Map<String, String>) request.getAttribute("map");
out.println("Welcome "+user);
out.println("Your password is "+pass);
out.println("Welcome "+map.get("user"));
out.println("Your password "+map.get("pass"));
out.close();
create ErrorServlet.java
------------------------
code under service
------------------
PrintWriter out=response.getWriter();
out.println("Login UnSuccess!!!Please enter valid credentials");
out.close();
HttpServlet
-----------
It is a child class of GenericServlet.
It supports only Http(protocol).
It provides certain http methods
doGet()
doPost()
doPut()
doXXXX()
HttpServlet is an abstract class.
why HttpServlet is an abstract ?
All the methods in HttpServlet are concrete methods,but these methods doesn't have proper logic implementation so
HttpServlet is declared as abstract,so that it is restricted from instantiation.
HttpServlet is available in javax.servlet.http.* package.
Heirarchy
---------
Servlet
^
|
GenericServlet
^
|
HttpServlet
Method summary
--------------
protected void doGet(HttpServletRequest,HttpServletResponse) throws ServletException,IOException;
protected long getLastModifie(HttpServletRequest);
protected void doHead(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doPost(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doPut(HttpServletRequest,
HttpServletResponse) throws ServletException, java.io.IOException;
protected void doDelete(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doOptions(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doTrace(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void service(HttpServletRequest,HttpServletResponse) throws ServletException,IOException;
public void service(ServletRequest,ServletResponse) throws ServletException,IOException;
Life cycle methods of HttpServlet
---------------------------------
init(ServletConfig)//Servlet
init()//GenericServlet
protected void service()//HttpServlet
public void service()//GenericServlet
doXXX()//HttpServlet
destroy()//Servlet
Excecution Flow of HttpServlet life cycle process
-------------------------------------------------
If any client make a request HttpServlet for first time the following life cycle operations take place.
step1:loading servlet.
Step2:Instantiating Servlet.
Step3:creating ServeletConfig object and invokes parameterized init method by passing ServletConfig object as a parameter
public void init(ServletConfig);
step4:Parameterized init() method calls default init()
public void init();
step5:creating ServletRequest and ServletResponse objects and then invokes service method of GenericServlet by passing request and response objects as parameters.
public void service(ServletRequest,ServletResponse)
step6:public service() will invoke protected service() method HttpServlet by passing requset and respnse objects as parameters,here casting is applied to convert ServletRequest to HttpServletRequest similarly for resonse also.
step7:protected service() will invokes doXXX() methods of a HttpServlet by passing HttpServletRequest,HttpServletResponse objects as parameters.
step8:destroy method called if the project is shutdown or a servlet is undeployed by administrator,which is used to
perform cleanup operations on a HttpServlet.
create a LoginProject to process login form using HttpServlet
Add login.html
--------------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add a HttpServlet-->LoginServlet.java
Goto src-->package-->com.manohar.servlets-->right click on package-->new-->Servlet-->ServletName-->LoginServlet
SuperClass-->HttpServlet
-->next-->next-->select required doXXX() to override in sub class-->finish
code under doGet() method
-------------------------
//read form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println(name);
out.println(pass);
out.close();
url
---
http://localhost:8070/HttpLoginProject/login.html
employee.html
-------------
<form action="./EmployeeController" method="post">
Enter Name:<input type="text" name="name"/><br>
Enter ID:<input type="text" name="id"/><br>
Enter Salary:<input type="text" name="sal"/><br>
<input type="submit" name="save" value="Save"/><br>
<input type="submit" name="update" value="update"/><br>
<input type="submit" name="delete" value="delete"/><br>
<input type="submit" name="select" value="select"/><br>
</form>
EmployeeController.java
-----------------------
@WebServlet("/EmployeeController")
public class EmployeeController extends HttpServlet {
private EmployeeService service = null;
public void init() {
service = new EmployeeServiceImpl();
}
code under doPost()
-------------------
// read form
String name = request.getParameter("name");
String id = request.getParameter("id");
String sal = request.getParameter("sal");
//reading identifiers from form
Enumeration enumeration = request.getParameterNames();
int empid=0;
if (id != null) {
empid = Integer.parseInt(id);
}
double empsal=0.0;
if (sal != null) {
empsal = Double.parseDouble(sal);
}
// create pojo
Employee employee=null;
if (id != null && sal != null && name != null) {
employee= new Employee();
employee.setEmpID(empid);
employee.setEmpName(name);
employee.setEmpSal(empsal);
}
int status = 0;
while (enumeration.hasMoreElements()) {
String btn = (String) enumeration.nextElement();
if (btn.equalsIgnoreCase("save")) {
status = service.insert(employee);
PrintWriter out =response.getWriter();
out.println(status + "records inserted");
out.close();
}
if (btn.equalsIgnoreCase("update")) {
status = service.update(employee);
PrintWriter out = response.getWriter();
out.println(status + " records updated");
out.close();
}
if (btn.equalsIgnoreCase("delete")) {
status = service.delete(empid);
PrintWriter out = response.getWriter();
out.println(status + " records deleted");
out.close();
}
if (btn.equalsIgnoreCase("select")) {
Employee employee2 = service.selectEmployee(empid);
PrintWriter out = response.getWriter();
out.println("EmpName " + employee2.getEmpName());
out.println("EmpId " + employee2.getEmpID());
out.println("EmpSal " + employee2.getEmpSal());
out.close();
}
}
i)JSE(java standard edition(core java)).
ii)JEE(Java Enterprise Edition(Advanced java)).
This is used to develop web applications.
iii)JME(java micro eiditon).
This is used to develop mobile apps.
oop[object oriented programming]
--------------------------------
An oop consists of the following features
i)object
ii)class
iii)encapsulation
iv)abstraction
v)inheritnace
vi)polymorphism
vii)Message passing
viii)dynamic binding
object
------
An object is a real world entity.
An object is an instance of a class i,e it allocates memory for a class.
syntax
------
ClassName referenceName=new ClassName();
An object consists of
i)Properties
ii)Actions
Properties
----------
Properties are used to identify an object.
ex:
name
color
height
weight
etc
Actions are used to perform a task.
ex:
sleeping()
eating()
reading()
etc
ex:
Person-->object
Properties--> name
color
height
weight
Actions---->sleeping()
---->reading()
---->eating()
we represnt properties in a program using variables.
ex:
Sting name;
String color;
etc
we represent actions in a program using methods.
void read()
{
//...
//..
}
void display()
{
//..
//..
}
class
-----
A class is blue print of an object.
A class describes about object.
A class is collection of variables and methods.
syntax
------
acessmodifier class ClassName
{
variables;
methods;
}
steps for implementing class and object
---------------------------------------
step1:declare a class
accessmodifier class ClassName{
//variables
//methods
}
step2:create object for a class.
ClassName referenceName=new ClassName();
step3:Accessing members(variables and methods) of a class
referenceName.membername
Pojo[Plain old java object]
---------------------------
It is simple java class which follows certain standards.
It consists of private properties and public setter and getter
methods.
It have a zero argumment default constructor.
It should implement Serializable interface.
setter and getter methods
-------------------------
A setter is used set value to the property of a pojo.
syntax
------
public void setPropertyName(datatype varname)
{
this.varname=varname
}
getter method
-------------
It returns the value of a property.
syntax
------
public returntype getPropertyName()
{
return varname;
}
ex:
Customer[pojo]
name
cid
mobile
address
age
name[setter and getter]
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
abstract class
--------------
we declare a class as abstract by using the keyword abstract.
syntax
------
accessmodifier abstract class ClassName
{
//statements
}
If we want to declare an abstract method in a class then that class must be declared as abstract.
In an abstract class we can declare both concrete methods and abstract methods.
It is not mandatory to declare abstract methods in an abstract class.
Abstract class cannot be instantiated(cant create object)
The abstract methods of an abstract class must be overridden in a sub class.
Program
-------
package com.satya.jse;
abstract class A
{
abstract void m1();
abstract void m2();
}
class B extends A{
@Override
void m1() {
System.out.println("m1");
}
@Override
void m2() {
System.out.println("m2");
}
}
public class AbstractTest {
public static void main(String[] args) {
B b=new B();
b.m1();
b.m2();
}
}
we can make an application loosely coupled by using the famous jse principle "A super class refernce can refer to a sub class object whereas a sub class refernce cannot refer to super class object."
public static void main(String[] args) {
Shape triangle=new Triangle();
triangle.area();
Shape circle=new Circle();
circle.area();
}
Multiple inheritance using interfaces
-------------------------------------
Deriving a subclass from 2 or more super classes is known as multiple inheritance.
Multiple inheritance is not directly supported in java using classes however we can implement multiple inheritance using interfaces in java.
syntax
------
interface I1
{
//
}
interface I1
{
//
}
.
.
class SubClassName implements I1,I2,...
{
//
}
package com.satya.jse;
interface I22 {
void m1();
void m2();
void m3();
}
abstract class I1I2Impl implements I22 {
@Override
public void m1() {
System.out.println("m1");
}
}
class SubClass extends I1I2Impl {
@Override
public void m2() {
System.out.println("Druva");
}
@Override
public void m3() {
System.out.println("Kaidi150");
}
}
public class MulTest {
public static void main(String[] args) {
I22 i=new SubClass();
i.m1();
i.m2();
i.m3();
}
}
JEE[java enterprise edition]
----------------------------
A Jee is used to develop web applications.
A web(internet) Application is application which runs on a network
ex:
banking Applications,
insurance applications,
medical applications etcJ.
JEE is collection of Api's
API[Application programming interface]
An Api is collection of packages
Package:
A package is collection of
classes
interfaces
enum
Jdbc[java database connectivity]
--------------------------------
We can maintain data in the following ways
i)variable
ii)objects
iii)files
iv)database
Variables,objects are used to maintain data temporarily.
Files,databases are used to maintain data perminently.
Files
-----
Evnn though we can maintain perminently using files ,there are certain limitations with files.
i)Maintainence become difficult with files i'c performing operations like
insert
update
delete
becomes difficult.
ii)Files are not secured.
iii)Files can used for only maitaining data of small scale applications like simplegames,super market s/w etc
iv)Files doesn't support medium scale and large scale applications.
Database
--------
A database is coolection of tables.
A table is collection of rows(touples).
A row is collection of fields(cols).
we use a language sql to perform operations on a database
sql[structure query language]
we use 2 types of sql commands
i)DDL[data definition language]
ii)DML[data manipuation language]
DDL is used to perform
i)create
ii)alter
iii)drop operations
create
------
create command is used to create database/table/view/index/sequence.
syntax of table
----------------
create table tablename(col1 datatype primary key,col2 datatype,.....);
ex:
create a table employee
-----------------------
name--varchar(size)
id--int
sal--double
dept--varchar(size)
desi--varchar(size)
create table employee(
id int primary key,
name varchar(20),
sal double,
dept varchar(20),
desi varchar(20));
primary key
-----------
A primary key is a constraint/condition applied on a column,
A primary key ensures that the data of a column is unique and not null.
syntax
------
colname datatype primary key.
ex:
id int primary key.
alter
-----
alter command alter the structure of a table by
adding a column
modifying a column
dropping a column
add a new colum to a table
--------------------------
syntax
------
alter table tablename
add colname datatype
ex:
alter table employee
add address varchar(30);
Modifying column of a table
---------------------------
alter table tablename
modify colname datatype
ex:
alter table employee
modify sal float;
dropping column of a table
--------------------------
alter table tablename
drop colname;
ex:
alter table employee
drop address;
drop
----
This command is used to drop a database/table/view/index/sequence.
syntax
------
drop table tablename;
ex:
drop table employee;
Data Manipulation language
--------------------------
A DML is used to manipulate data in a table.
we have the following dml command
insert
update
select
delete
insert
------
An insert command will insert a row into a table.
syntax
------
insert into tablename values(value1,value2,.....);
ex:
insert into employee values(1,'manohar',1000.00,'training','trainer');
update
------
update is used to update a col or cols of a table.
syntax
------
update tablename set colname=value where condition;
ex:
update tablename set colname=value where condition;
or
update tablename set colname1=value,colname2=value,... where condition;
ex:
update employee set sal=3000.00,desi='sr.trainer' where id=1;
select
------
A select command is used to select or retrive data from a table.
syntax1
-------
selecting a single column from a table.
ex:
select name from employee;
syntax2
-------
selecting partial row from a table.
select col1,col2,.... from tablename;
ex:
select name,sal from employee;
syntax3
-------
select *from employee;
delete
------
delete is used to delete data from cols of a row or to delete a row itself.
syntax
------
delete from tablename;
ex:
delete from employee;
Jdbc
----
A jdbc is an api used to connect to a database from a java application(program).
We can execute sql queries,stored procedures,functions etc from java program using jdbc.
A jdbc api provides 2 types of packages.They are
i)java.sql.*;
ii)javax.sql.*;
Application Architecture types
i)2 tier
ii)3 tier
iii)n tier
2 tier architecture
-------------------
A 2 tier architecture typically comprises of 2 layers
i)client[Java Program/browser].
ii)server(database/application).
client --------->database.
JP/B
3 tier architecture
-------------------
A 3 tier architecture typically comprises of 3 layers
i)client[Java Program/browser].
ii)application server
ii)database server(database/application).
client------>applicationserver-------->database.
n tier architecture
-------------------
An n tier architecture consits of mutiple servers in the middle layer.
client--->AS1--->AS2......----database server.
Jdbc Api
--------
A jdbc api consists of the follwing interfaces and classes
i)Connection(java.sql.*)(I)
ii)Statement(")(I)
iii)PreparedStatement(")(I)
iv)CallableStatement(")(I)
v)ResultSet(")(I)
vi)DatabaseMetaData(")(I)
vii)ResultSetMetaData(")(I)
viii)RowSet(javax.sql.*)(i)
ix)SavePoint(")(I)
x)SQLException(java.sql.*)(c)
xi)DriverManager(class).
Driver
------
A driver is a class which is used to establish connection with a database.It is also called as connection software.
A driver is also called a conversion s/w i,e which converts java method calls to database function calls.
There are 4 types of drivers.They are
i)Type1---Jdbc-Odbc bridge driver.
ii)Type2--Java-Native Api driver.
iii)Type3--Middleware driver
iv)Type4--Thin driver
Jdbc-odbc bridge driver
-----------------------
A jdbc-odbc bridge driver converts java method calls to odbc function calls,an odbc driver converts odbc function calls to database function calls.
Advantages
----------
i)It is simple to use.
Disadvantages
-------------
i)Platform dependent[windows]
ii)Low performance[becuase types driver requires no of conversions)
iii)Database client library must be installed on client machine.
iv)Driver must be installed in client machine.
Type2--Java-Native Api driver
-----------------------------
Advantages
----------
It has better performance than type1 driver
Disadvantages
-------------
We need to install database client libraries on client machine.
Platform dependent.
Type3 --Middleware driver[pure java driver]
-------------------------------------------
Advantages
----------
It is a pure java driver
Platform independent.
Provides best performance
No need installing database client libaries on client machine
It supports middleware applications.
DisAdvantages
-------------
It requires network support.
It has latency(time delay) issue[because java calls are converted to middle ware calls]
It is expensive.
It requires database specific code because middleware server interacts with different databases.
Type4-Thin driver
-----------------
Advantages
----------
It is a pure java driver.
Best performance.
It converts java calls to database calls directly that is why we call this driver as thin driver.
Opensource.
Disadvantage
------------
Database dependent i,e we should a seperate driver for each database.
steps to connect database using jdbc
------------------------------------
step1:Loading driver
we load driver into memory by using a static method called forName available in java.lang.Class.
syntax
------
Class.forName("driver classname");
ex:
type1--sun.jdbc.odbc.JdbcOdbcDriver.
type2--oracle.jdbc.driver.OracleDriver.
type4--oracle.jdbc.driver.OracleDriver.
type4-com.mysql.jdbc.Driver.
ex:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
forName
-------
It is a static method in java.lang.Class.
It throws a checked exception ClassNotFoundException
It returns an object of java.lang.Class.
step2:Establishing connection with db
DriverManager[class]
--------------------
Establish connection with a db using driver.
It is available in java.sql.*
getConnection()
---------------
It is a static factory method available in DriverManager class.
syntax
------
public static Connection getConnection("url","username","password");
url-->uniform resource locator
Type4 oracle driver
-------------------
jdbc:oracle:thin:@localhost:1521:XE
jdbc-->connectivity.
oracle-->db type.
thin-->driver type.
localhost-->ip address of localhost[127.0.0.1].
1521-->port number on which database is running.
XE-->instance name.
username--system
password--manager
It returns Connection object.
syntax
------
Connection con=DriverManager.getConnection("url","username","password');
Connection
----------
Connection is an interface available java.sql.*;
A Connection interface holds connection object.
A Connection produces factory of Objects.
Connection interface methods
----------------------------
public Statement createStatement()
public PreparedStatement prepareStatement()
public CallableStatement prepareCall()
public void setAutoCommit()
public void commit()
public void rollback()
public void getMetaData()
public void close()
driver is a -------.
we have ----types of drivers
type1 is also called as----
type2 is also called as----
type3 is also called as----
type4 is also called as----
------method is used to load driver
forName is available in ------
syntax to load driver
DriverManger is --------
DriverManager establish connection with db using-----method.
getConnection is method------
getConnection returns ------ object
getConnection accepts---,---,---- parameters
url has----,----,----,-----,-----,-----
Connection is ------
Connection provides -------- of objects.
Connection holds------object.
step3:Performing database operations.
we can perform 2 types of operations with a database
i)select operations(select)
ii)Non select operations(insert,update,delete,create etc)
In jdbc we can perform either select or non select operations using the following interfaces.
i)Statement.
ii)PreparedStatement.
Statement
---------
Statement is an interface available in java.sql.* package.
A statement interface consists of following methods
i)executeUpdate().
ii)executeQuery().
iii)execute().
iv)close().
executeUpdate()
---------------
This method is used to perform non-select operations (insert,update,delete,ddl operations)with a database from jdbc program.
It returns an integer value.
It throws a checked exception SQLException.
syntax
------
public int executeUpdate(String sql) throws SQLException;
executeQuery()
--------------
It is used to execute select operation with a database from a jdbc program.
It returns ResultSet object.
It throws SQLException.
syntax
------
public ResultSet executeQuery(String sql)throws SQLException.
execute()
---------
It is used to perform both select/non-select operations.
It returns boolean value.
Throws checked exception SQLException.
syntax
------
public boolean execute(String sql) throws SQLException;
close()
-------
closes Statement object.
syntax
------
public void close() throws SQLException;
creating object for Statement object
------------------------------------
we can create object for Statement interface by using the factory method createStatement() available in Connection interface.
createStatement() returns Staement object.
It throws SQLException.
syntax
------
public Statement createStatement() throws SQLException;
Statement statement=con.createStatement();
step4: close statement
statement.close();
step5:close Connection
con.close();
write a jdbc program to create a table in a db
----------------------------------------------
class Test
{
public static void main(String args[])
{
//step1:loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:XE";
String username="system";
String password="manager";
//step2:establish connection
Connection con=DriverManager.getConnection(url,username,password);
//step3:creating Statement
Statement statement=con.createStatement();
String sql="create table employee(name varchar2(30),id number(10) primary key,sal number(10,5))";
int res=statement.executeUpdate(sql);
System.out.println("table created");
statement.close();
con.close();
}
}
}
}
stepts to create a project and execute a program in eclipse
-------
step1:creating project
1--open eclipse.
2--Go to File.
3--new.
4--Java Project.
5--ProjectName---JdbcProject
6-->select use default jre.
7-->finish.
step2:creating package
Goto Package explorer-->Expand JdbcProject-->
select src-->right click-->new-->package-->
Name--com.manohar.satya.jdbc
step3:Adding a class to a package
Goto package-->select com.manohar.satya.jdbc-->right click-->new-->class-->
Name--JdbcCreateDemo.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.*;
public class JdbcCreateDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
//step2:creating connection
Connection connection=DriverManager.getConnection(url,user,pass);
//step3:creating Statement
Statement statement=connection.createStatement();
String sql="create table employee(name varchar2(30),id number(10) primary key,sal number(10,5))";
int res=statement.executeUpdate(sql);
System.out.println("table created"+res);
statement.close();
connection.close();
}
}
Verifying table in database
---------------------------
Open "Run Sql Command Line"
sql>connect
sql>user-name--system
sql>password--manager
sql>connected
sql>desc employeee
name
id
sal
Program2
--------
package com.manohar.satya.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcInsertDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1:loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
//step2:creating connection
Connection connection=DriverManager.getConnection(url,user,pass);
//step3:create Stamenet
Statement statement=connection.createStatement();
String sql="insert into employee values('manohar',1001,2000.00)";
int status=statement.executeUpdate(sql);
System.out.println(status+" record(s) are inserted");
statement.close();
connection.close();
}
}
Initializing values from keyboard
---------------------------------
we use a class called Scanner to input values from keyboard.
It is available in the package java.util.*;
Methods
-------
byte--nextByte()
short--nextShort()
int--nextInt()
long--nextLong()
float--nextFloat()
double--nextDouble()
boolean--nextBoolean()
String--next()
nextLine()
Inputting String,int
Scanner s=new Scanner(System.in);
Sop("enter a");
int a=s.nextInt();
Sop("enter b");
String str=s.next();
Program
-------
package com.manohar.satya.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class JdbcDynamicInsertDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//create Scanner object
Scanner scanner=new Scanner(System.in);
System.out.println("Enter name");
String name=scanner.next();
System.out.println("Enter id");
int id=scanner.nextInt();
System.out.println("Enter sal");
double sal=scanner.nextDouble();
//step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2
Connection connection = DriverManager.getConnection(url, user, pass);
// step3
Statement statement = connection.createStatement();
String sql="insert into employee values('"+name+"',"+id+","+sal+")";
int res = statement.executeUpdate(sql);
System.out.println(res+"record(s) are inserted");
statement.close();
connection.close();
}
}
Program
-------
System.out.println("Enter id");
int id = scanner.nextInt();
System.out.println("Enter sal");
double sal = scanner.nextDouble();
String sql = null;
if (id % 2 == 0) {
sql = "update employee set sal=" + sal + " where id=" + id + "";
int res = statement.executeUpdate(sql);
System.out.println(res + "record(s) are inserted");
}
else {
System.out.println("Enter an even id");
}
Performing select operation with jdbc
-------------------------------------
steps:
step1:Loading driver
Class.forName("driverName");
step2:Establishing connection with db
Connection connection=DriverManager.getConnection(url,username,password);
step3:Creating Statement object.
Statement statement=connection.createStatement();
Step4:create select query
String sql="select *from tablename";
step5:creating ResultSet.
ResultSet rs=statement.executeQuery(sql);
step6:Iterate ResultSet
step7:close ResultSet
rs.close();
step8:close Statement
statement.close();
step9:close connection
connection.close();
ResultSet
---------
ResultSet is an interface available in java.sql.* package;
If we want to execute a select query we use executeQuery() method from Statement interface.
An executeQuery method returns ResultSet object after executing an sql query with the database by wrapping(putting) the records fetched from the database into ResultSet object.
How to get ResultSet object
---------------------------
ResultSet rs=statement.executeQuery(sql);
The above diagram depicts the flow of select query execution.
1--executeQuery() issues select query with database.
2--Reads the records from the table and wraps all the records into ResulSet object at java side
3--The address of ResultSet object is initialized to ResultSet reference "rs".
Definition
----------
A ResultSet is a cursor which is used to iterate the data fetched from a database.
Method summary
--------------
public boolean next()
This method moves cursor to next row of a ResultSet
By default the cursor will be positioned above first record of ResultSet
next method position a cursor to a row and return true if the record is available in the ResultSet otherwise returns false.
public byte getByte(int index);
or
public byte getByte(String column_name);
This method returns an integer value from the column of ResultSet.
public short getShort(int index);
or
public short getShort(String column_name);
This method returns an integer value from the column of ResultSet.
public int getInt(int index);
or
public int getInt(String column_name);
This method returns an integer value from the column of ResultSet.
public long getLong(int index);
or
public long getLong(String column_name);
This method returns an integer value from the column of ResultSet.
public float getFloat(int index);
or
public float getFloat(String column_name);
This method returns a decimal value from the column of ResultSet.
public double getDouble(int index);
or
public double getDouble(String column_name);
This method returns a decimal value from the column of ResultSet.
public String getString(int index);
or
public String getString(String column_name);
This method returns a string value from the column of ResultSet.
public String getBoolean(int index);
or
public String getBoolean(String column_name);
This method returns a boolean value from the column of ResultSet.
Note:
while trying to get a value from a column of a ResultSet we should use a getXXX() method based on the type of column in ResultSet i'e
if column is varchar2 use getString() method
if column is number use getInt()/getLong()/getByte()/getShort()
if column is decimal use getFloat()/getDouble()
if column is boolean use getBoolean() method
so on.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.*;
public class JdbcSelectDemo {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2
Connection connection = DriverManager.getConnection(url, user, pass);
// step3
Statement statement = connection.createStatement();
String sql = "select *from employee";
//step4
ResultSet rs= statement.executeQuery(sql);
while(rs.next()){
String name=rs.getString("name");
int id=rs.getInt("id");
double sal=rs.getDouble("sal");
System.out.println(name+" "+id+" "+sal);
}
rs.close();
statement.close();
connection.close();
}
}
Note:
we can get a value from the column of a ResultSet by using the index or name of the column.
syntax
------
public datatype getXXX(int index);-->returns value based on index.
public datatype getXXX(String name);-->returns value based on column_name.
The index of a column in ResultSet by default starts from 1 and then 2 and so on.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.*;
public class JdbcDynamicInsertDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2
Connection connection = DriverManager.getConnection(url, user, pass);
// step3
Statement statement = connection.createStatement();
String sql = "select name from employee";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("name");
if (name.startsWith("a") ||
name.startsWith("e")
|| name.startsWith("i") ||
name.startsWith("o")
|| name.startsWith("u")) {
System.out.println(name);
}
}
rs.close();
statement.close();
connection.close();
}
}
Introducing pojo approach in jdbc
---------------------------------
Pojo[Plain old java object]
---------------------------
It is simple java class which follows certain standards.
It consists of private properties and public setter and getter
methods.
It should have a zero argumment default constructor.
It should implement Serializable interface.
setter and getter methods
-------------------------
A setter is used set value to the property of a pojo.
syntax
------
public void setPropertyName(datatype varname)
{
this.varname=varname
}
getter method
-------------
It returns the value of a property.
syntax
------
public returntype getPropertyName()
{
return varname;
}
create a jdbc project--->JdbcPojo.
create packages under src
com.manohar.satya.jdbc.dto
Employee.java
com.manohar.satya.client
EmployeeClient
Employee.java
-------------
package com.manohar.satya.jdbc.dto;
public class Employee {
//instance variables
private String empName;
private int empID;
private double empSal;
//setters and getters
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double empSal) {
this.empSal = empSal;
}
}
EmployeeClient.java
-------------------
package com.manohar.satya.jdbc.client;
import java.sql.*
import com.manohar.satya.jdbc.dto.Employee;
public class EmployeeClient {public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
// jdbc properties
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:Establishing connection
Connection connection = DriverManager.getConnection(url, user, pass);
// step3:creating Statement
Statement statement = connection.createStatement();
// creating Employee object
Employee employee = new Employee();
// setting values
employee.setEmpID(1001);
employee.setEmpName("dddd");
employee.setEmpSal(2000.00);
String sql = "insert into employee values('" + employee.getEmpName()
+"',"+employee.getEmpID()+","+employee.getEmpSal()+ ")";
int status=statement.executeUpdate(sql);
System.out.println(status+"record(s) is inserted");
statement.close();
connection.close();
}
}
Moving jdbc properties to a properties file
-------------------------------------------
Jdbc properties
driver
url
username
pass
A properties file is used to declare data in the form of key and value pairs.
It should have an extension .properties
ex:jdbc.properties
How to create properties file in eclipse
----------------------------------------
open eclipse
-->goto project
-->src
-->right click
-->new
-->file
Name as-->jdbc.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=system
pass=manager
Properties
----------
Properties is a predefined class available in java.util.* package.
Properties class is use to store,update and read properties from a properties file.
Method
------
load(Reader reader);
load(InputStream stream);
loads properties from properties file into a proerties object.
save()
store()
write properties into proerties file.
getProperty()--read a property from a Properties object.
steps to read jdbc properties from a properties files------------------------------------------
-----
step1:open properties using FileInputStream
FileInputStream in=new FileInputStream("filepath");
ex:
FileInputStream in=new FileInputStream("D:\\JavaNewWorkShop\\AdvancedJavaBatch\\JdbcSelect\\src\\jdbc.properties");
step2:create object for Properties class.
Properties p=new Properties();
step3:
loading properties from properties file to Properties object.
p.load(in);
step4:read properties from Properties object using getProperty() method
syntax
------
String varname=p.getProperty("Propertyname");
ex:
String driver=p.getProperty("driver");
step5:
close file
in.close();
Note:FileInputStream() constructor throws FileNotFoundException(checked).
load() method throws IOException.
Note:we can perform write/read operations on a file using the following classes
Write operation
---------------
FileOutStream
FileWriter
Read operation
--------------
FileInputStream
FileReader
Program to perform select operation using jdbc
----------------------------------------------
package com.manohar.satya.jdbc.client;
import java.io.*;
import java.sql.*;
import java.util.*;
import com.manohar.satya.jdbc.pojo.Employee;
public class EmployeeClient {
public static void display(Employee employee){
System.out.println("The name is "+employee.getEmpName());
System.out.println("The id is "+employee.getEmpID());
System.out.println("The sal is "+employee.getEmpSal());
}
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException //step1:open properties
FileInputStream in=new FileInputStream("D:\\JavaNewWorkShop\\AdvancedJavaBatch\\JdbcSelect\\src\\jdbc.properties");
//step2:create Properties object
Properties properties=new Properties();
//step3:load properties
properties.load(in);
//stp4:getting properties.
String driver=properties.getProperty("driver");
String url=properties.getProperty("url");
String pass=properties.getProperty("pass");
String user=properties.getProperty("user");
//jdbc process
//step1:load driver
Class.forName(driver);
//step2:creating connection
Connection connection=DriverManager.getConnection(url,user,pass);
//step3:creating Statement
Statement statement=connection.createStatement();
String sql="select *from employee";
ResultSet rs=statement.executeQuery(sql);
Employee employee=new Employee();
while(rs.next()){
String name=rs.getString("name");
int id=rs.getInt("id");
double sal=rs.getDouble("sal");
employee.setEmpID(id);
employee.setEmpName(name);
employee.setEmpSal(sal);
display(employee);
}
in.close();
rs.close();
statement.close();
connection.close();
}
}
PreparedStatement
-----------------
It is a child interface of Statement available java.sql.*;
A PreparedStatement uses pre-compiled query,if we are executing same query repeatedly.
Whenever we execute a query with database from jdbc,the following operations are performed at database side
i)Query compilation
ii)Query execution
if we use Statement to execute a query,if it is same or different query,every time query compilation and query execution happens whereas if we use PreparedStatement ,query is compiled only for one time,if we are executing the same query repeatedly otherwise if we are executing different queries,query compilation and execution happens for both Statement and PreparedStatement every time.
We can get PreparedStatement object by using the method prepareStatement() available in Connection interface.
syntax
------
public PreparedStatement prepareStatement(String sql);
A prepareStatement() throws SQLException.
How to get PreparedStatement object.
------------------------------------
PreparedStatement statement=connection.prepareStatement(sql);
PreparedStatement suports parameter binding.
Binding values to query parameters/positional parameters of a query is known as parameter binding.
Positional parameters are repersentd with question mark(?),by default every question mark has indexing and the indexing starts with one(1) and then two(2) and so on.
we set values to the positional parameters by using setters available in PreparedStatement interface.
Method summary
--------------
public int executeUpdate()
public ResultSet executeQuery()
public boolean execute()
public void close()
public void setString(int index,String value);
public void setByte(int index,byte value);
public void setShort(int index,short value);
public void setInt(int index,int value);
public void setLong(int index,long value);
public void setFloat(int indexfloat value);
public void setDouble(int index,double value);
public void setBoolean(int index,boolean value);
Program
-------
step1:create Employee Pojo
public class Employee {
//instance variables
private String empName;
private int empID;
private double empSal;
//setters and getters
}
stpe2:create properties file.
jdbc.properties
---------------
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=system
pass=manager
step3:create JdbcClient
public class JdbcClient {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//opening file
FileInputStream in=new FileInputStream("D:\\JavaNewWorkShop\\AdvancedJavaBatch\\PreparedStatement\\src\\jdbc.properties");
//creating Properties
Properties properties=new Properties();
//loading properties
properties.load(in);
//getting properties
String driver=properties.getProperty("driver");
String url=properties.getProperty("url");
String user=properties.getProperty("user");
String pass=properties.getProperty("pass");
//jdbcproperties
Class.forName(driver);
//Connection
Connection connection=DriverManager.getConnection(url,user,pass);
//sql query
String sql="insert into employee values(?,?,?)";
//creating object for pojo
Employee employee=new Employee();
employee.setEmpName("abc");
employee.setEmpID(1002);
employee.setEmpSal(30000.00);
//PreparedStatement
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,employee.getEmpName());
statement.setInt(2,employee.getEmpID());
statement.setDouble(3,employee.getEmpSal());
int status=statement.executeUpdate();
System.out.println(status+"records are inserted");
in.close();
statement.close();
connection.close();
}
}
CallableStatement
-----------------
A CallableStatement is used to call stored procedures and functions from a database in a java program.
It is child interface of Statement available in java.sql.*;
Methods
-------
public int executeUpdate();
publlic ResultSet executeQuer();
public boolean execute();
public void close();
We get CallableStatement object by using method prepareCall() available in Connection interface.
syntax
------
public CallableStatement prepareCall(sql);
How to get CallableStatement object.
-----------------------------------
CallableStatement statement=connection.prepareCall(sql);
It throws SQLException.
Stored Procedure
----------------
A stored procedure is used to implement business logic at database side.
Storedprocedure reduces burden on Application developer.
How create sp
-------------
create or replace procedure proceduerName
(var1 paramtype datatype,
var2 paramtype datatype,
....,
....,
varn paramtype datatype)
is
begin
//statements
end;
/
parameter types in a procedure
------------------------------
In a sp we have 3 types of parameters
i)input.
ii)output.
iii)input/output.
input parameters
----------------
These are used to accept values sent from an appliacation and persist data in a table.
we use keyword "in" to declare input parameters.
syntax
------
varname in datatype;
ex:
name in varchar2;
output parameters
-----------------
These are used to return values(result) from database to a appliaction.
we use keyword "out" to declare output parameters.
syntax
------
varname out datatype;
ex:
name out varchar2;
input/output parameters
-----------------------
These acts as both input and output parameters.
we use keyword "inout" to declare input/output parameters.
syntax
------
varname inout datatype;
ex:
name inout varchar2;
creating a stored procedure to insert employee record in a table
----------------------------------------------
create or replace procedure insertProc
(name in varchar2,
id in int,
sal in float)
is
begin
insert into employee values(name,id,sal);
end;
/
Now goto database and execute query at database.
open RunSqlCommanLine
sql>copy paste procedure here
..
..
..
Procedure created.
Points to remember
------------------
------is used to execute sp,functions in jdbc.
CallableStatement is a child of -------.
-----method is used to create -------object.
prepareCall method is available in-------.
----,---,----,--- are imp methods of CS.
sp is used implement------
----parametertypes are there in sp.
----keyword is used to declare input parameters.
----keyword is used to declare output parameters.
----keyword is used to declare input/output parameters.
How to call a stored procedure
-------------------------------
syntax
------
call procedureName(?,?,.....);
ex:
call insertProc(?,?,?);
CallableStatement also supports parameterbinding i,e we can set values to the positional parameters using setter methods.
we have following setter methods in CallableStatement.
public void setString(int index,String value);
public void setByte(int index,byte value);
public void setShort(int index,short value);
public void setInt(int index,int value);
public void setLong(int index,long value);
public void setFloat(int indexfloat value);
public void setDouble(int index,double value);
public void setBoolean(int index,boolean value);
A CallableStatement provides getters also to get the values returned by output parameters of a stored procedure.
we use the following getters from CS.
public byte getByte(int index);
public short getShort(int index);
public int getInt(int index);
public long getLong(int index);
public float getFloat(int index);
public double getDouble(int index);
public String getString(int index);
public boolean getBoolean(int index);
Program(insert a record into an employee table using sp)
-------
step1:create pojo
public class Employee {
private String empName;
private int empID;
private double empSal;
//setters and getters
}
step2:create jdbc.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=system
pass=manager
step3:JdbcClient
public class JdbcClient
{
p s v m(Strin args[])
{
//code is same as above program upto here
//creating scanner
Scanner scanner=new Scanner(System.in);
// creating object for pojow
Employee e = new Employee();
System.out.println("enter name");
e.setEmpName(scanner.next());
System.out.println("enter id");
e.setEmpID(scanner.nextInt());
System.out.println("enter sal");
e.setEmpSal(scanner.nextDouble());
//creating sql
String sql="{call insertProc(?,?,?)}";
CallableStatement statement=connection.prepareCall(sql);
statement.setString(1,e.getEmpName());
statement.setInt(2,e.getEmpID());
statement.setDouble(3,e.getEmpSal());
boolean status=statement.execut();
System.out.println(status+"inserted");
in.close();
statement.close();
connection.close();
}
}
creating sp to retrive name,sal from employee table
by passing id as input.
---------------------------------------------------
create or replace procedure selectProc
(name1 out varchar2,
id1 in int,
sal1 out float)
is
begin
select name,sal into name1,sal1 from employee where id=id1;
end;
/
How to read output parameters in a jdbc program
-----------------------------------------------
We read output parameters at java side by using CallableStatement.
We should register output parameters with CallableStatement by using method registerOutParameter()
syntax
------
public void registerOutParameter(int index,Types.type);
Types
-----
Types is predefined class available in java.sql.* package which provides different datatypes.
Types class provides compatability between java datatypes and database datatypes.
Program to read out parameters from a sp
----------------------------------------
step1:create Pojo
public class Employee
{
private String empName;
private int empID;
private double empSal;
//setters and getters
}
step2:create jdbc.properties
driver
url
user
pass
step3:create JdbcSpClient.
public class JdbcSpClient
{
public static void main(String args[])
{
//code same as above program until here
//creating sql
String sql="{call selectProc(?,?,?)}";
//creating scanner
Scanner scanner=new Scanner(System.in);
// creating object for pojow
Employee e = new Employee();
System.out.println("enter id");
e.setEmpID(scanner.nextInt());
CallableStatement statement=connection.prepareCall(sql);
statement.setInt(2,e.getEmpID());
statement.registerOutParameter(1,Types.VARCHAR);
statement.registerOutParameter(3,Types.FLOAT);
boolean status=statement.execute();
System.out.println(statement.getString(1));
System.out.println(statement.getFloat(3));
in.close();
statement.close();
connection.close();
}
}
differences between storedprocedures and functions
--------------------------------------------------
storedprocedure functions
i)used to implement busines i)used to perform
logic. calculations.
ii)It consists of input/output ii)It consists of
parameters. only input parameters.
iii)returns 0 or more values iii)returns only one
value.
iv)we can call a function iv)we cannot call
from a stored procedure. stored procedure from
a function.
v)We can implement exception v)No exception hanling in sp. handling.
functions
---------
Functions are used to implement calculations.
syntax
------
create or replace function function_name
(var1 in type,var2 in type,.....)
return type
is
//variable section
begin
//logic
return var;
end;
/
function to find sum of two numbers.
create or replace function sum1
(num1 in int,num2 in int)
return int
is
num3 int;
begin
num3:=num1+num2;
return num3;
end;
/
How to call a function
----------------------
syntax
------
?=call function_name(?,?,..)
ex:
?=call sum1(?,?)
Program to call a function from jdbc program
--------------------------------------------
step1:Jdbcpropperties
same as above program
step2:JdbcFunctionClient
public class JdbcFunctionClient{
public static void main(String args[])
{
//upto here code is same as above program
//creating sql
String sql="{?=call sum1(?,?)}";
CallableStatement statement=connection.prepareCall(sql);
statement.setInt(2,10);
statement.setInt(3,20);
statement.registerOutParameter(1,Types.INTEGER);
statement.execute();
System.out.println(statement.getInt(1));
in.close();
statement.close();
connection.close();
}
}
Program to read names from database and sort names
--------------------------------------------------
step1:jdbc properties
//same as above program
step2:create JdbcStringSortClient
public class JdbcStringSortClient {
public static void main(String[] args) throws IOException,ClassNotFoundException, SQLException {
//upto here code is same as above program
// sql query
String sql = "select name from employee";
// PreparedStatement
PreparedStatement statement = connection.prepareStatement(sql);
//creating ResultSet
ResultSet rs = statement.executeQuery();
//creating String array
String s[] = new String[10];
//iterating ResultSet and copying to String array
int j = 0;
while (rs.next()) {
String name = rs.getString(1);
s[j] = name;
j++;
}
String sortedStri=sort(s);
for(String s1:sortedString){
System.out.println(s1);
}
in.close();
rs.close();
statement.close();
connection.close();
}
public static String[] sort(String s[]){
String temp;
for(int i=0;i<s.length;i++){
for(int j=i+1;j<s.length;j++)
{
if(s[i].compareTo(s[j])>0){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
return s;
}
}
Note:pass the size to String array based on rows in the tables.
Transaction Management
----------------------
Transaction:
Performing unit of task is known as transcation.
A transaction should follow ACID properties
A-atomic.
C-consistancy.
I-Isolation.
D-durable.
A transaction is said to atomic when a transaction is committed only if it is succesfully executed otherwise never commit a transaction.
we implement transaction management by using the following methods available in Connection interface.
public void setAutoCommit(boolean);
public void commit();
public void rollback();
setAutoCommit():It is used to enable or disable a commit mode.
By default commit mode is enabled in jdbc.
ex:
connection.setAutoCommit(false);
commit():
It is used to make changes perminent in the database.
rollback():
It is used to rollback a trasanction if any execption is raised while executing transaction.
Program
-------
package com.manohar.satya.jdbc.client;
import java.sql.*;
public class JdbcTransactionClient {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
// step1
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
Connection connection=null;
Statement statement=null;
// step2
try {
connection = DriverManager.getConnection(url, user, pass);
// step:disable auto commit
connection.setAutoCommit(false);
// step3
statement = connection.createStatement();
String sql = "insert into employee values('fff',456,40000.00)";
statement.executeUpdate(sql);
connection.commit();
}
catch (Exception exception)
{
exception.printStackTrace();
connection.rollback();
}
finally{
statement.close();
connection.close();
}
}
}
}
Layers in java
--------------
We divide a java application into 3 layers
i)Presentation layer.
ii)Business/application layer.
iii)Database layer/DAO layer.
we implement presentation/User interface logic in presentation layer.
we implement business logic in application layer
we implement database logic in dao layer.
A layered approach divides the responsibilities as per requirement of a project which makes the maintenance of project simple and easy.
Developing DAO layer
--------------------
DAO[Data Access object]
-----------------------
A DAO is a design pattern which is used to seperate database logic from business and presentaion logic.
Execution flow
--------------
Client---->service--->DAO---->(database).
creating a DAO layer
--------------------
DAO is reusable java class also people call this as design pattern.
While defining a dao layer take
i)one interface.
ii)one class.
interface is declared with all the abstract methods required in DAO operations.
A DAO consists of the following methods
i)public int save(Employee employee);
This is used to insert a row into a employee table.
ii)public int update(Employee employee);
This is used to update a row in an employee table.
iii)public int delete(Employee employee);
This is used to delete a row from an employee table.
iv)public Employee get(int id);
This is used to select a row from employee table and and set it to a pojo and returns pojo.
v)public Employee[] getAll();
It is used to select all the rows from employee table and store into Employee[] array and returns it.
creating interface EmployeeDAO.java
-----------------------------------
public interface EmployeeDAO {
public int save(Employee e);
public int update(Employee e);
public int delete(Employee e);
public Employee get(int id);
public Employee[] getAll();
}
Implementing EmployeeDAO in EmployeeDAOImpl.java
------------------------------------------------
public class EmployeeDAOImpl implements EmployeeDAO {
//declaring references
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet resultSet = null;
private Employee employee=null;
private Employee employee1[]=null;
//declaring jdbc properties
public static final String url = "jdbc:oracle:thin:@localhost:1521:XE";
public static final String user = "system";
public static final String pass = "manager";
@Override
public int save(Employee e) {
int status=0;
try {
Class.forNam("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "insert into employee values(?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1,e.getEmpName());
statement.setInt(2,e.getEmpID());
statement.setDouble(3,e.getEmpSal());
status=statement.executeUpdate();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally {
try {
statement.close();
connection.close();
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
return status;
}
@Override
public int update(Employee e) {
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "update employee set sal=? where id=?";
statement = connection.prepareStatement(sql);
statement.setDouble(1, e.getEmpSal());
statement.setInt(2, e.getEmpID());
status = statement.executeUpdate();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
try {
statement.close();
connection.close();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
return status;
}
@Override
public int delete(Employee e) {
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "delete from employee where id=?";
statement = connection.prepareStatement(sql);
statement.setInt(1, e.getEmpID());
status = statement.executeUpdate();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try {
statement.close();
connection.close();
}
catch(SQLException e1)
{
e1.printStackTrace();
}
}
return status;
}
@Override
public Employee get(int id) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "select from employee where id=?";
statement = connection.prepareStatement(sql);
statement.setInt(1,id);
//creating ResultSet
resultSet=statement.executeQuery();
//create Employee object
employee=new Employee();
while(resultSet.next()){
String name=resultSet.getString("name");
int id1=resultSet.getInt("id");
double sal=resultSet.getDouble("sal");
//setting to pojo
employee.setEmpID(id1);
employee.setEmpName(name);
employee.setEmpSal(sal);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
try {
resultSet.close();
statement.close();
connection.close();
}
catch(SQLException e1)
{
e1.printStackTrace();
}
}
return employee;
}
@Override
public Employee[] getAll() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, pass);
String sql = "select *from employee";
statement = connection.prepareStatement(sql);
//creating Employee Array
employee1=new Employee[12];
for(int i=0;i<employee1.length;i++){
employee1[i]=new Employee();
}
//creating ResultSet
resultSet=statement.executeQuery();
int i=0;
while(resultSet.next()){
String name=resultSet.getString("name");
int id1=resultSet.getInt("id");
double sal=resultSet.getDouble("sal");
//setting to pojo
employee1[i].setEmpID(id1);
employee1[i].setEmpName(name);
employee1[i].setEmpSal(sal);
i++;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try {
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
return employee1;
}
}
creating service layer
-----------------------
create 2 entities
i)one Service interface
ii)one ServiceImpl class.
creating EmployeeService.java(I)
--------------------------------
copy the methods of EmployeeDAO interface to EmployeeService.
package com.manohar.satya.service;
import com.manohar.satya.model.Employee;
public interface EmployeeService {
public int save(Employee e);
public int update(Employee e);
public int delete(Employee e);
public Employee get(int id);
public Employee[] getAll();
}
//step2:create EmployeeServiceImpl.java and implement //EmployeeService.java
package com.manohar.satya.service;
import com.manohar.satya.dao.EmployeeDAO;
import com.manohar.satya.dao.EmployeeDAOImpl;
import com.manohar.satya.model.Employee;
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO dao = null;
public EmployeeServiceImpl() {
dao = new EmployeeDAOImpl();
}
@Override
public int save(Employee e) {
int staus = dao.save(e);
return staus;
}
@Override
public int update(Employee e) {
int status = dao.update(e);
return status;
}
@Override
public int delete(Employee e) {
int status = dao.delete(e);
return status;
}
@Override
public Employee get(int id) {
Employee employee = dao.get(id);
return employee;
}
@Override
public Employee[] getAll() {
Employee employee[] = dao.getAll();
return employee;
}
}
creating Model Employee.java
----------------------------
public class Employee {
private String empName;
private int empID;
private double empSal;
//setters and getters
}
creating client layer[EmployeeClient.java]
------------------------------------------
public class EmployeeClient {
public static void main(String[] args) {
// step1
EmployeeService service = new EmployeeServiceImpl();
Scanner scanner = new Scanner(System.in);
//case1:insert employee
Employee employee1=new Employee();
//setting data
System.out.println("Enter id");
employee1.setEmpID(scanner.nextInt());
System.out.println("Enter name");
employee1.setEmpName(scanner.next());
System.out.println("Enter sal");
employee1.setEmpSal(scanner.nextDouble());
//saving pojo int
status=service.save(employee1);
System.out.println(status+"inserted successfully!!!!!!");
// case2:update employee
Employee employee2 = new Employee();
//setting data
System.out.println("Enter id");
employee2.setEmpID(scanner.nextInt());
System.out.println("Enter sal");
employee2.setEmpSal(scanner.nextDouble());
// saving pojo
int status2=service.update(employee2);
System.out.println(status2 + "updated successfully!!!!!!");
// case3:delete employee
Employee employee3 = new Employee();
//setting data
System.out.println("Enter id");
employee3.setEmpID(scanner.nextInt());
// deleting pojo
int status3 = service.delete(employee3);
System.out.println(status3 + " deleted successfully!!!!!!");
// case4:get employee
System.out.println("Enter id");
int id=scanner.nextInt();
//get pojo
Employee employee = service.get(id);
System.out.println(employee.getEmpID());
System.out.println(employee.getEmpName());
System.out.println(employee.getEmpSal());
// case5:Get All employees
Employee employee[] = service.getAll();
//iteration using for each
for (Employee e : employee) {
System.out.println(e.getEmpID());
System.out.println(e.getEmpName());
System.out.println(e.getEmpSal());
}
//iteration using for loop
for (int i=0;i<employee.length;i++) {
System.out.println(employee[i].getEmpID());
System.out.println(employee[i].getEmpName());
System.out.println(employee[i].getEmpSal());
}
}
}
ResultSetMetaData interface
---------------------------
It is used to get Metadata of a table in a database.
Metadata means data about data.
Here we get
column_name
column_type
column_count
etc of a table using ResultSetMetaData.
It is available in java.sql.* package.
Method summary
--------------
public int getColumnCount();
public String getColumnName(int);
public String getColumnTypeName(int);
we get ResultSetMetaData object by using the method getMetaData() available in ResultSet interface.
syntax
------
public ResultSetMetaData getMetaData() throws SQLException;
How to create ResultSetMetaData object.
-----------------------------------------
ResultSetMetaData data=reference.getMetaData();
here reference is ResultSet type.
Program
-------
public class JdbcResultSetMetaDataDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql query
String sql = "select *from employee";
// PreparedStatement
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
//creating ResultSetMetaData
ResultSetMetaData data=rs.getMetaData();
System.out.println(data.getColumnCount());
System.out.println(data.getColumnName(2));
System.out.println(data.getColumnTypeName(3));
rs.close();
statement.close();
connection.close();
}
}
}
DatabaseMetaData interface
--------------------------
A DatabaseMetaData provides metadata of a database like
databasename
databaseversion
drivername
driver_version
etc
It is available in the package java.sql.*;
Method summary
--------------
public String getDatabaseProductName() throws java.sql.SQLEception;
public String getDatabaseProductVersion() throws java.sql.SQLException;
public String getDriverName() throws java.sql.SQLException;
public String getDriverVersion() throws java.sql.SQLException;
etc
we get DatabaseMetaData object by using the method getMetaData() available in Connection interface.
syntax
------
public DatabaseMetaData getMetaData() throws SQLException;
How to create DatabaseMetaData object
-------------------------------------
DatabaseMetaData data=reference.getMetaData();
Here reference is Connection type.
Program
-------
package com.manohar.satya.jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JdbcResultSetMetaDataDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
DatabaseMetaData data = connection.getMetaData();
System.out.println(data.getDatabaseProductName());
System.out.println(data.getDatabaseProductVersion());
System.out.println(data.getDriverName());
System.out.println(data.getDriverVersion());
connection.close();
}
}
storing and retrieving image from a table.
storing and retrieving file from a table.
Java Streams
------------
Stream is flow of bits.
There are 2 types of streams.
i)character streams.
ii)Binary streams.
Character streams
-----------------
This is used to handle character type of data.Also encoding is applied for character streams.
Ex:Reader/Writer classes.
Binary Streams
--------------
This is used to handle numeric type of data. Encoding is not applied for Binary streams.
Ex:InputStream/OutputStream classes.
To store an image into a table we use a datatype called BLOB.
BLOB-->Binary Large object.
-->It is to hold binary streams.
create a table to store an image
--------------------------------
create table img(id int primary key,image blob);
How to store image into table using jdbc
----------------------------------------
To store image into a table we use the method setBinaryStream() available in PreparedStatement.
syntax
------
public void setBinaryStream(int,InputStream) throws SQLException;
public void setBinaryStream(int,InputStream,long) throws SQLException;
File path:
C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JdbcImageDemo {
public static void main(String[] args) throws ClassNotFoundException,
SQLException, IOException {
//open image file
FileInputStream in=new FileInputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulips.jpg");
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
//sql
String sql="insert into img values(?,?)";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setInt(1,1);
statement.setBinaryStream(2,in,in.available());
int status=statement.executeUpdate();
System.out.println(status+" inserted");
in.close();
statement.close();
connection.close();
}
}
selecting image from a table
----------------------------
To select an image from a file we use the method getBlob() available in ResultSet.
syntax
------
public Blob getBlob(int index);
or
public Blob getBlob(String colname);
getBlob() returns Blob object.
To initialize Blob object we use the class Blob available in java.sql.*.
ex:
Blob b=rs.getBlob(2);
To store image into file we have to convert Blob to byte array.
we use the method getBytes() to convert Blob to byte array available in
Blob class.
syntax
------
public byte[] getBytes(int,int);
ex:
byte bb[]=b.getBytes(1,(int)b.length());
Here parameter1 is the index of image in image column i,e 1 st image,2nd image etc
Parameter2 is length() of image,length() returns long,we should type cast to int type.
Write byte array to file using FileOutputStream.
ex:
FileOutputStream out=new FileOutputStream("D:\\tulips.jpg");
out.write(bb);
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcImageSelectDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
String sql="select *from img";
PreparedStatement statement=connection.prepareStatement(sql);
ResultSet rs=statement.executeQuery();
while(rs.next()){
int id=rs.getInt("id");
Blob blob=rs.getBlob("image");
//convert blob to bytes
byte b[]=blob.getBytes(1,(int) blob.length());
FileOutputStream out=new FileOutputStream("d:\\tulips.jpg");
out.write(b);
out.close();
}
rs.close();
statement.close();
connection.close();
System.out.println("sucess");
}
}
Servlets
--------
client
------
A client is a machine or a software which is used to make a request to a server.
A client s/w can be a browser like google chrome,mozilla firefox etc
server
------
A server is a software or a machine which accepts request from a client and process the request and sends back response.
Server s/w can be like apache tomcat,weblogic etc.
webcomponent
------------
It is a server side program which provides service to a client.
They are of 2 types
i)static webcomponents.
ii)dynamic webcomponents.
static webcomponent
-------------------
A static webcomponent is not interactive and readonly programs.
ex:
html,xml,css etc
dynamic webcomponents
---------------------
A dynamic webcomponent is interactive and responsive programs.
ex:
javascript,vbscript,servlet,jsp,asp etc
WebApplication
--------------
A webapplication is collection of webcomponents.
A webApplication consists of
html
xml
css
javascript
servlets
jsp
etc
webcontainer
------------
A webcontainer is a program which provides environment to execute servlets and jsp.
A webcontainer manages life cycle of a servlet.
A webcontainer provides multithreading support.
A webcontainer provides load balancing.
etc
Servlet
-------
A servlet is a server side dynamic webcomponent which is used to process dynamic request of a client.
A Servlet is an interface in JEE from which every servlet will be inherited directly or indirectly.
we use the following packages to work with servlets.
i)javax.servlet.*
ii)javax.servlet.http.*
Servlet interface
-----------------
It is a root interface of all servlets in jEE.
It is available in the package javax.servlet.*;
It has 5 methods
public abstract void init(ServletConfig) throws
ServletException;
public abstract ServletConfig getServletConfig()
public abstract void service(ServletRequest,ServletResponse) throws ServletException,IOException
public abstract java.lang.String getServletInfo();
public abstract void destroy();
Here the methods init(),service().destroy() are life cycle methods.
Software requirements
---------------------
i)browser.
ii)server.
iii)IDE.
steps to create a servlet program
---------------------------------
step1:Implement servlet interface in a class
syntax
------
accessmodifier class ClassName implements Servlet
{
}
ex:
public class HelloServlet implements Servlet
{
public void init(ServletConfig config) throws ServletException
{
//
}
public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException
{
//
}
public void destroy()
{
}
public ServletConfig getServletConfig()
{
}
public String getServletInfo()
{
}
}
init() method
-------------
An init() method is used to perform initialization operations on a servlet.
i)It is used to load configuration details of servlet into ServletConfig object.
ii)A ServletConfig is an interface available in javax.servlet.*;
iii)A ServletConfig object hold configuration details of a servlet.
iv)We declare configuration details of a servlet in an xml file called as web.xml file.
v)While calling init() WebContainer creates ServletConfig object and loads configuration details into ServletConfig object.
init() is also used for initalizing variables and objects of a Servlet.
init() method is executed only for one time in the entire life cycle of servlet.
init() method throws ServletException if the execution of init() is not completed within given time or if any internal exception is raised.
service()
---------
A service() provides service to a client.
Every time client make a request to server,the service method is called.
syntax
------
public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException;
A service method consists of 2 parameters
i)ServletRequest
ii)ServletResponse
The above 2 interfaces are available in javax.servlet.*;
ServletRequest
--------------
A ServletRequest is an interface available in javax.servlet.*.
A ServletRequest object is used to hold data sent by client at server side.
ServletResponse
---------------
A ServletResponse is an interface available in javax.servlet.*.
A ServletResponse object is used to hold data sent to client from server side.
Note:
ServletConfig,ServletRequest,ServletResponse are managable by webcontainer.
destroy()
---------
destroy is used to destroy servlet objects.
It is called only for one time in time in the entire life cycle of servlet.
syntax
------
public void destroy();
getServletConfig()
------------------
This method returns ServletConfig object.
syntax
------
public ServletConfig getServletConfig();
getServletInfo()
----------------
This method returns servlet information like author,date created etc.
syntax
------
public String gerServletInfo();
step1:
------
creating a Servlet to display HelloWorld onto browser.
-----------------------------------------------------
open Notepad and write HelloWorldServlet class
import javax.servlet.*;
import java.io.*;
public class HelloWorldServlet implements Servlet
{
public void init(ServletConfig config) throws ServletException
{
System.out.println("init");
}
public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("Hello World!!!!!!");
out.close();
}
public void destroy()
{
System.out.println("destroy");
}
public ServletConfig getServletConfig()
{
return null;
}
public String getServletInfo()
{
return null;
}
}
save as
HelloWorldServlet.java
To compile a Servlet program from command prompt we should set path for a jar file servlet-api.jar.
We can download jar or we can get from tomcat installation folder.
Path for servlet-api.jar in tomcat
----------------------------------
C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar
How to set servlet-api.jar to classpath and path
------------------------------------------------
Goto Mycomputer-->right click system properties-->Advanced System settings-->environment variables-->under user variables-->
name-->classpath
value-->C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;
similarly set for path
name-->path
value-->C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;
Now compile HelloWorldServlet.java
javac HelloWorldServlet.java
step4:creating deployment directory
-----------------------------------
It is project structure for a web application to deploy in a webserver.
RootFolder[HelloWorldProject]
|-->*.jsp
|-->*.html
|-->*.images
WEB-INF
|-->src
|-->*.java
|-->classes
|-->*.classes
|-->lib
|-->*.jars
|web.xml
we keep *.java files in src folder.
we keep *.class files in classes folder.
we keep *.jars in lib folder.
web.xml
-------
It is a deployement descriptor which consists of configuration details of Servlet,jsp,filter.
Quick Learning of Xml
---------------------
xml-->Extensible Mark up language.
Xml is used to perform data transportation between different techonologies like java,.net,php etc
Xml holds data.
Xml is tag based language like html.
Xml consists of user defined tags.
It is platform independent.
It can have attributes which increases readability of xml tag.
It is w3c recommendation.
strcuture
---------
<root-tag>
<child-tag>
<chid1-tag>value</child1-tag>
<chid2-tag>value</child2-tag>
<chid3-tag>value</child3-tag>
</child-tag>
<child-tag>
<chid1-tag>value</child1-tag>
<chid2-tag>value</child2-tag>
<chid3-tag>value</child3-tag>
</child-tag>
<child-tag>
<chid1-tag>value</child1-tag>
<chid2-tag>value</child2-tag>
<chid3-tag>value</child3-tag>
</child-tag>
..
..
..
</root-tag>
The starting tag in xml is called root tag.
The inner tags are child-tags.
Every tag opened must be closed with(/).
ex:
<tag>value</tag>
structure of web.xml
--------------------
<web-app>
<servlet>
<servlet-name>servletname</servlet-name>
<servlet-class>FullyQualifiedNameOfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletname</servlet-name>
<url-pattern>/url</url-pattern>
</servlet-mapping>
</web-app>
web.xml
-------
<web-app>
<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/helloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
step5:installing Apache tomcat.
download apcahe-tomcat server from google
https://tomcat.apache.org/download-80.cgi
click on "32-bit/64-bit Windows Service Installer (pgp, md5, sha1)"
Double click on downloaded apache-tomcat executable file and click on next->next-->... to finish installation.
step6:Deploying a WebProject into a webServer.
Deploying is a process of moving a project from localdrive to webserver (in ameerpet).
Deploying is a process of moving a project from development server to production server (in hitec city).
Path of deployment directory in my local machine
D:\Satya_technologies\JavaPrograms\
Goto this directory copy the project "HelloWorldProject" and paste it under the following path in tomcat.
C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps
step7:
Start tomcat server
Goto the path
C:\Program Files\Apache Software Foundation\Tomcat 8.5\bin
double click on "Tomcat8".
How to check server is started or not
-------------------------------------
Type url http://localhost:8070
It will bring up tomcat administrator console.
How to run webApplication
-------------------------
Open browser and the type the following url
http://localhost:8070/HelloWorldProject/helloWorldServlet
localhost-->ip address of local mahcine
-->In a Project ip address changes depends on server.
8070-->port number
HelloWorldProject-->Project name[context path]
helloWorldServlet-->url-pattern of a servlet.
Execution flow of HelloWorldServlet
-----------------------------------
i)Client[browser] makes a request to webserver for a servlet.
2)Webserver will check the type of request and forward it to Webcontainer if it is a dynamic request.
3,4)Webcontainer will goto web.xml and search for url-pattern of a servlet sent by user and starts processing the required servlet.
5)Container starts the proceesing servlet by loading servlet from hard disk to ram.
6)Container instatiates servlet.
7,8)Container creates ServletConfig object and the calls init method and perform required initialization operations.
9,10,11)Container creates ServletRequest and ServletResponse objects and then calls service method by passing request and response objects as parameters to service method.
12)Resonse is sent back to client.
13)If the webApplication is shutdown or server is shut down then the destroy method of servlet is called.
Creating a Web project[HelloWorldProject] in eclipse
----------------------------------------------------
Goto File-->New-->dynamic Web project--->
ProjectName-->HelloWorldProject
Provide configuration Tomcat with eclipse as shown below.
Goto Target Runtime-->
Browse NewRuntime-->select Appropriate version of Tomcat among the given versions-->
next-->
under tomcat installation directory-->
browse-->select installaton path ot tomcat-->
C:\Program Files\Apache Software Foundation\Tomcat 8.5-->finish-->finish
Project structure in eclipse
----------------------------
Add Servlets or any *.java files under JavaResources-->src-->
Add *.html,*.jsp,*.images under WebContent folder.
Add *.jars under lib folder.
How to Add servlet
------------------
Goto JavaResources-->src-->create a package-->
com.manohar.satya.servlets
Right clik on package-->new-->servlet-->
ClassName-->HelloWorldServlet
SuperClassName-->Empty
click on next-->next-->finish.
How to run a web project in eclipse
-----------------------------------
Select Project[HelloWorldProject]-->right click-->Run As-->Run on server.
Type the following url in the browser
-------------------------------------
http://localhost:8070/HelloWorldProject/HelloWorldServlet.
Note:
In the above project we are not providing configuration details of servlet in web.xml because instead of web.xml an annotaion @WebServlet was introduced in servlets.Here the annotation is used to configure servlet.
The url in the annotation is the url-pattern which is used to make a call to a servlet from a client machine.
syntax
------
@WebServlet("/url-pattern")
public class ClassName implements Servlet
{
//
}
Note:
If we are using @WebServlet annotation ,then mapping of url sent by client is done container by searching for servlets in src folder,which ever annotation is mapping with url,the servlet class under that annotation is processed by the container.
If none of the servlets is matching with url then server returns 404 error.
Form processing using servlets
------------------------------
html
----
hyper text mark up language.
i)It is used to design webpages.
ii)It is user friendly.
iii)tag based language.
iv)case insensitive
v)It has attributes.
vi)It is w3c.
Program structure of html
-------------------------
<html>
<head>
<title>....</title>
..
..
</head>
<body>
..
..
..
</body>
</html>
heading tags
------------
we have 6 types of heading
<h1>text</h1>
<h2>text</h2>
<h3>text</h3>
<h4>text</h4>
<h5>text</h5>
<h6>text</h6>
creating a web application to process a login form
--------------------------------------------------
create a new project-->LogingFormProject
-->Goto WebContent folder-->Add a html-->
Name as-->login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
</body>
</html>
Add servlet-->LoginServlet.java
Goto-->JavaResources-->src-->
create a new package-->com.manohar.login
Add a new servlet LoginServlet.java under package.
code under service() method
----------------------------
//reading form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
//displaying form
PrintWriter out=response.getWriter();
out.println(name);
out.println(pass);
out.close();
How to run Project
------------------
Goto Project-->LoginForm-->select project-->right click-->run as-->run on server
Type the following url in browser
localhost:8070/LoginFormProject/login.html
Login.html
-----------
-----------
Name:|manohar |
------------
------------
Password:|********* |
------------
submit
Output on Browser
-----------------
--------------------------------------------
|localhost:8070/LoginFormProject/login.html|
--------------------------------------------
Manohar
satya
ArmstrongProject
----------------
Add html-->armstring.html
<form action="./ArmStrongServlet">
Enter number:<input type="text" name="no" />
<input type="submit" value="armstrong" />
</form>
Add ArmStrongServlet.java
code under service method
-------------------------
//reading form
String n=request.getParameter("no");
int x=Integer.parseInt(n.trim());
int r,sum=0,temp;
temp=x;
while(x!=0){
r=x%10;
sum=sum+r*r*r;
x=x/10;
}
//
PrintWriter out=response.getWriter();
//validation
if(sum==temp){
out.println("No is Armstrong "+temp);
}
else{
out.println("No is not Armstrong "+temp);
}
out.close();
create LoginProject
-------------------
Add login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add LoginServlet.java
---------------------
@WebServlet("/LoginServlet")
public class LoginServlet implements Servlet {
//variable declaration
String s[] = null;
ArrayList list=null;
public void init(ServletConfig arg0) throws ServletException {
//initiaizing string array
s = new String[2];
s[0] = "prabhas";
s[1] = "anushka";
//initializing ArrayList
list=new ArrayList();
list.add("virat");
list.add("anushka");
}
..
..
code under service() method
---------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
// validation1
if (name.trim().equalsIgnoreCase("manohar") && pass.trim().equalsIgnoreCase("manohar")) {
out.println("<h1>Login sucess</h1>");
}
else {
out.println("<h1>Login not sucess!!!Please enter valid credentials</h1>");
}
//validation2
if (name.trim().equalsIgnoreCase(s[0]) && pass.trim().equalsIgnoreCase(s[1])) {
out.println("<h1>Login sucess</h1>");
}
else {
out.println("<h1>Login not sucess!!!Please enter valid credentials</h1>");
}
//validation3
String n=(String) list.get(0);
String p=(String) list.get(1);
if (name.trim().equalsIgnoreCase(n) && pass.trim().equalsIgnoreCase(p)) {
out.println("<h1>Login sucess</h1>");
} else {
out.println("<h1>Login not sucess!!!Please enter valid credentials</h1>");
}
out.close();
getParameter()
-------------
This method is used to get data(parameters) from a form.
It is available in ServletRequest interface.
Method signature
----------------
public String getParameter(String);
How to read a parameter from a form
-----------------------------------
syntax
------
String varname=request.getParameter("identifier");
Types of servlets
-----------------
There are 2 types of servlets in Servlet API
i)GenericServlet
ii)HttpServlet
GenericServlet
--------------
It is implementation class of Servlet interface.
It is abstract class because service of GenericServlet is abstract.
The serive() method in GenericServlet is abstract because it is developer responsibility to override service() method according to project requirements.
GenericServlet supports all the protocols like http,ftp,tcp/ip,smtp etc
It is available in the package javax.servlet.* package.
GenericServlet also implements 2 interfaces
i)Serializable
ii)ServletConfig
Methods of GenericServlet
-------------------------
public javax.servlet.GenericServlet();
public void destroy();
public java.lang.String getInitParameter(java.lang.String);
This method is used to read initialization parameters from web.xml file.
public java.util.Enumeration<java.lang.String> getInitParameterNames()
public javax.servlet.ServletConfig getServletConfig();
return ServletConfig object.
public javax.servlet.ServletContext getServletContext();
return ServletContext object.
public java.lang.String getServletInfo();
returns Servlet information.
public void init(javax.servlet.ServletConfig) throws javax.ser
tion;
performs initialization of servlet.
public void init() throws javax.servlet.ServletException;
performs initialization of servlet.
public void log(java.lang.String);
performs logging
public void log(java.lang.String, java.lang.Throwable);
performs logging.
public abstract void service(javax.servlet.ServletRequest, javtResponse) throws javax.servlet.ServletException, java.io.IOException
provides service to client.
public java.lang.String getServletName();
returns Servlet name.
Life cycle methods of Generic Servlet
-------------------------------------
A GenericServlet consists of 4 life cycle methods.
i)init(ServletConfig)
ii)init()
iii)service(ServletRequest req,ServletResponse)
iv)destroy()
why 2 init() method in GenericServlet
init(ServletConfig):
This method is always called tomcat to perform initialization task,it is also called as container's init() method.
init()
This method is used by developer to perform initialization task.
Execution flow of GenericServlet
--------------------------------
when a client makes a request to GenericServlet the following steps are implemented by container to process servlet.
step1:loading servlet into memory.
step2:Instantiating Servlet
step3:creating ServletConfig object
step4:invoke parameterized init() method by passing ServletConfig as a parameter.
step5:Parameterized init() will invoke default init() method.
step6:creating objects for ServletRequest,ServletResponse objects and invokes service() method by passing these objects as parameters to service().
step7:destroy method is called.
Create a Project FruitProject to demonstrate generic servlet.
Add servlet-->FruitServlet.java
How to Add Generic servlet.
Goto src-->package->right click-->new-->servlet-->
name as-->FruitServlet
Superclass-->javax.servlet.GenericServlet
click on finish.
FruitServlet.java
-----------------
@WebServlet("/FruitServlet")
public class FruitServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
ArrayList<String> list=null;
public void init(){
list=new ArrayList<String>();
}
code under service() method
---------------------------
//reading form
String s1=request.getParameter("f1");
String s2=request.getParameter("f2");
String s3=request.getParameter("f3");
String s4=request.getParameter("f4");
String s5=request.getParameter("f5");
//adding data to collection
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
//Iterating collections
Iterator<String> iterator=list.iterator();
PrintWriter out=response.getWriter();
while(iterator.hasNext()){
out.println(iterator.next());
}
out.close();
}
fruit.html
----------
<form action="./FruitServlet" method="get">
Enter Fruit1:<input type="text" name="f1"/><br>
Enter Fruit2:<input type="text" name="f2"/><br>
Enter Fruit3:<input type="text" name="f3"/><br>
Enter Fruit4:<input type="text" name="f4"/><br>
Enter Fruit5:<input type="text" name="f5"/><br>
<input type="submit" value="Dsiplay"/>
initialization parameters in servlets
-------------------------------------
Initialization parameters are name and value pairs declared in web.xml using a tag <init-param>.
syntax
------
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
we should declare <init-param> tag as a child tag to <servlet> tag.
we declare properties like credentials,jdbc properties,network proprties etc as initialization parameters.
How to read initialization parameters
-------------------------------------
we read initialization parameters by using ServletConfig interface.
ServletConfig
-------------
It is an interface available in javax.servlet.* package.
It is used to read configuration details of servlet declared in web.xml or @WebServlet annotation.
Method summary
--------------
public String getServletName();
returns servlet name.
public ServletContext getServletContext();
returns ServletContext object.
public String getInitParameter(java.lang.String);
gets initialization parameters from web.xml file.
public Enumeration<java.lang.String> getInitParameterNames(
);
gets all names of initialization parameters in the form of Enumeration.
How to get initialization parameters from web.xml
-------------------------------------------------
String varname=config.getInitParameter("identifier");
creating a webproject to demonstrate initialization parameters.----------------------------------------
-----------
create a dynamicwebproject-->LoginServlet
Add web.xml file under-->webcontent-->WEB-INF-->web.xml
code under web.xml
------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.manohar.servlets.LoginServlet</servlet-class>
<init-param>
<param-name>user</param-name>
<param-value>manohar</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>java</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Add a servlet-->LoginServlet.java
override parameterized init() and read initialization parameters from web.xml file using methid getInitParameter().
public class LoginServlet extends GenericServlet {
// declaring instance variables
String userName = null;
String passWord = null;
@Override
public void init(ServletConfig config) throws ServletException {
// reading initialization parameters from web.xml
userName = config.getInitParameter("user");
passWord = config.getInitParameter("password"); System.out.println(userName);
System.out.println(passWord);
}
code under service method
-------------------------
// reading form
String user = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
if (user.equalsIgnoreCase(userName) && pass.equalsIgnoreCase(passWord)) {
out.println("<h1>Login Success</h1>");
}
else {
out.println("<h1>Login UnSuccessful!!!Please enter valid credentials</h1>");
}
}
Type the following url in browser to run the application
http://localhost:8070/ServletConfigProject/login.html
Approach2 to read initialization parameters
-------------------------------------------
This time we don't need override init(ServletConfig) but we can also get ServletConfig object by using the getServletConfig() which is overridden in GenericServlet.
How to get ServletConfig object
-------------------------------
syntax
------
ServletConfig config=getServletConfig();
code under service method
-------------------------
//get ServletConfig object
ServletConfig config=getServletConfig();
String userName=config.getInitParameter("user");
String passWord=config.getInitParameter("password");
// reading form
String user = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
if (user.equalsIgnoreCase(userName) && pass.equalsIgnoreCase(passWord)) {
out.println("<h1>Login Success</h1>");
}
else {
out.println("<h1>Login UnSuccessful!!!Please enter valid credentials</h1>");
}
Important points to remember
----------------------------
i)we know that ServletConfig is used to maintain configuration details of a Servlet
How many config objects are created for a servlet
-------------------------------------------------
For each servlet one config object is created,no of config created in a project is dependent on no of servlets in the project.
--------------------------------------------
|No of servlets=No of Servletconfig objects|
--------------------------------------------
we should declare initialization parameters for each servlet seperately.
when should we declare parameters as initialization parameters
If the propertied changes from one servlet to another servlet while configuring in web.xml file,in such case we declare initialization parameters for each servlet seperately.
Context parameters
------------------
If we want to maintain application wide data then we should use context parameters.
we configure context parameters in web.xml file by using <context-param> tag.
context parameters are declared in the form of name(key) and value pairs.
syntax
------
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
ServletContext
--------------
It is an interface available in javax.servlet.* package.
It is used to maintain application wide data.
ServletContext object is common for all the servlets in a project.
Method summary
--------------
public String getInit
Parameter(String);
get context parameters from web.xml
public void setAttribute(String,Object);
stores an object into ServletContext object.
public Object getAttribute(String);
returns object from ServletContext.
public void removeAttribute(string);
remove an object from ServletContext.
ServletContext object holds data in the form of name and value pairs.
How to get ServletContext object
--------------------------------
we get ServletContext object by using the getServletContext() available in ServletConfig interface/ServletRequest interface.
syntax
------
ServletContext context=request.getServletContext();
create a project-->ServletContextProject
Add web.xml
-----------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>user</param-name>
<param-value>manohar</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>manohar</param-value>
</context-param>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.manohar.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Add servlet-->LoginServlet.java
code under service method
-------------------------
//get ServletConfig object
ServletContext context=request.getServletContext();
//reading context parameters
String userName=context.getInitParameter("user");
String passWord=context.getInitParameter("pass");
// reading form
String user = request.getParameter("user");
String pass = request.getParameter("pass");
//
PrintWriter out = response.getWriter();
if (user.equalsIgnoreCase(userName) && pass.equalsIgnoreCase(passWord))
{
out.println("<h1>Login Success</h1>");
}
else {
out.println("<h1>Login UnSuccessful!!!Please enter valid credentials</h1>");
}
login.html
----------
<form action="./login" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Project url to run application
------------------------------
http://localhost:8070/ServletContextProject/login.html
Differences between ServletConfig and ServletContext
----------------------------------------------------
ServletConfig ServletContext
i)It is an interface It is an interface available in available in
javax.servlet.* javax.servlet.*
ii)This used to read This is used to
initialization parameters context parameters.
of a servlet.
3)Per each servlet One Context object
one config object per project.
is created.
4)we use method we use method getInitParameter() getInitParameter()
to read initialization to read context
parameters parameters
5)we use the we the tag <context-param>
<init-param> to declare context to declare initialization parameters
parameters in web.xml
6)we use the method we use the method
getServletConfig() getServletContext()
to get ServletConfig to get ServletContext
available in Servlet object available in
interface ServletConfig /ServleRequest interfaces.
How many implicit objects are created by Container to process a servlet?
ServletConfig
ServletContext
ServletRequest
ServletResponse
Note:For each client request one request and response object is created by container.
Creating Employee Management System
-----------------------------------
create a project struture
-------------------------
JavaResource
src
com.manohar.controller
LoginController.java
EmployeeController.java
com.manohar.model
Employee.java
com.manohar.service
EmployeeService.java
EmployeeServiceImpl.java
com.manohar.dao
EmployeeDAO.java
EmployeeDAOImpl.java
creating a web application to insert an employee record into a table using Servlet with jdbc connectivity.
step1:create a table employee
empname
empid primary key
empsal
step2:
create a html-->AddEmployee.html
action="./AddServlet"
EmpID
EmpName
EmpSal
step3:
create a pojo
com.manohar.model
Employee.java
empName
empID
empSal
step4:
create Servlet-->AddServlet.java
code under service
------------------
//read form
//convert id to int.
//convert sal to double.
//implement jdbc steps to insert a record into employee //table.
AddEmployee.html
----------------
<form action="./AddEmployeeServlet">
Enter Name:<input type="text" name="name"/><br>
Enter ID:<input type="text" name="id"/><br>
Enter Salary:<input type="text" name="sal"/><br>
<input type="submit" value="Save"/><br>
</form>
Add Pojo-->Employee.java
package com.manohar.model;
public class Employee {
private String empName;
private int empID;
private double empSal;
//setters and getters
}
Add AddEmployeeServlet.java
---------------------------
code under service method
-------------------------
//read form
String name=request.getParameter("name");
String id=request.getParameter("id");
String sal=request.getParameter("sal");
int empid=Integer.parseInt(id);
double empsal=Double.parseDouble(sal);
//setting properties to pojo
Employee employee=new Employee();
employee.setEmpID(empid);
employee.setEmpName(name);
employee.setEmpSal(empsal);
Connection connection=null;
PreparedStatement statement=null;
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
try{
//jdbc steps
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection(url, user, pass);
//sql
String sql="insert into employee values(?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,employee.getEmpName());
statement.setInt(2, employee.getEmpID());
statement.setDouble(3,employee.getEmpSal());
int status=statement.executeUpdate();
response.getWriter().println(status+"records inserted");
}
catch (Exception e) {
}
finally{
try {
statement.close();
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
creating service layer
----------------------
Add EmployeeService.java(interface)
EmployeeServiceImpl.java(class)
EmployeeService.java
--------------------
public interface EmployeeService {
public int insert(Employee employee);
public int update(Employee employee);
public int delete(int empid);
public Employee selectEmployee(int empid);
}
EmployeeServiceImpl.java
------------------------
public class EmployeeServiceImpl implements EmployeeService{
private EmployeeDAO dao=null;
public EmployeeServiceImpl(){
dao=new EmployeeDAOImpl();
}
@Override
public int insert(Employee employee) {
int status=dao.insert(employee);
return status;
}
@Override
public int update(Employee employee) {
int status=dao.update(employee);
return status;
}
@Override
public int delete(int empid) {
int status=dao.delete(empid);
return status;
}
@Override
public Employee selectEmployee(int empid) {
Employee employee=dao.selectEmployee(empid);
return employee;
}
}
creating DAO Layer
------------------
Add EmployeeDAO.java
EmployeeDAOImpl.java
EmployeeDAO.java
----------------
public interface EmployeeDAO {
public int insert(Employee employee);
public int update(Employee employee);
public int delete(int empid);
public Employee selectEmployee(int empid);
}
EmployeeDAOImpl.java
--------------------
public class EmployeeDAOImpl implements EmployeeDAO {
private Connection connection = null;
private PreparedStatement statement = null;
public int insert(Employee employee) {
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
String sql = "insert into employee values(?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1, employee.getEmpName());
statement.setInt(2, employee.getEmpID());
statement.setDouble(3, employee.getEmpSal());
status = statement.executeUpdate();
statement.close();
connection.close();
}
catch (Exception e) {
System.out.println(e);
}
return status;
}
public int update(Employee employee) {
System.out.println("update");
String sql = "update employee set name=?,sal=? where id=?";
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
statement = connection.prepareStatement(sql);
statement.setInt(3, employee.getEmpID());
statement.setString(1, employee.getEmpName());
statement.setDouble(2, employee.getEmpSal());
status = statement.executeUpdate();
statement.close();
}
catch (Exception e) {
System.out.println(e);
}
return status;
}
public int delete(int empid) {
String sql = "delete from employee where id=?";
int status = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
statement = connection.prepareStatement(sql);
statement.setInt(1, empid);
status = statement.executeUpdate();
statement.close();
} catch (Exception e) {
System.out.println(e);
}
return status;
}
public Employee selectEmployee(int empid) {
String sql = "select *from employee where id=?";
Employee employee = new Employee();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
statement = connection.prepareStatement(sql);
statement.setInt(1, empid);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
employee.setEmpID(rs.getInt("id"));
employee.setEmpName(rs.getString("name"));
employee.setEmpSal(rs.getDouble("sal"));
}
statement.close();
} catch (Exception e) {
System.out.println(e);
}
return employee;
}
}
HttpSession
-----------
It is an interface available in javax.servlet.http.* package.
It is an object which hold data in the form key and value pairs.
HttpSession is very useful in implmenting SessionManagement/SessionTracking.
Method summary
--------------
public long getCreationTime();
public String getId();
public long getLastAccessedTime();
public ServletContext getServletContext();
public void setMaxInactiveInterval(int);
public int getMaxInactiveInterval();
public HttpSessionContext getSessionContext();
public Object getAttribute(java.lang.String);
public Object getValue(java.lang.String);
public Enumeration<java.lang.String>
getAttributeNames();
public String[] getValueNames();
public void setAttribute(String,Object);
public void putValue(String,Object);
public void removeAttribute(String);
public void removeValue(String);
public void invalidate();
public boolean isNew();
How to get session object
--------------------------
we get HttpSession object by using method getSession() available in HttpServletRequest interface.
public HttpSession getSession();
This method checks if a Session object is already associated with request and returns that object otherwise create a new Session object and return that.
public HttpSession getSession(true);
It is same as default getSession() if the parameter to getSession is true
if the parameter is false then this method checks if a Session object is already associated with request and returns that object otherwise returns null,here no new Session object is created.
syntax
------
HttpSession session=request.getSession();
creating a webApplication to demonstrate Session object
-------------------------------------------------------
login.html
----------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
LoginServlet.java
-----------------
code under doGet()
------------------
//reading form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
//create Session object
HttpSession session=request.getSession();
session.setAttribute("name",name);
session.setAttribute("pass",pass);
//create dispatcher
RequestDispatcher dispatcher=request.getRequestDispatcher("WelcomeServlet");
dispatcher.include(request,response);
WelcomeServlet.java
-------------------
code under doGet()
------------------
//get Session object
HttpSession session=request.getSession();
String u=(String) session.getAttribute("name");
String p=(String) session.getAttribute("pass");
//create PW
PrintWriter out=response.getWriter();
out.println("The name is "+u);
out.println("The pass is "+p);
out.close();
Session Tracking
----------------
when ever a client make a request to a server,the server will process the request and send the response,once the response is sent back server will forget about client information because of the stateless nature of http.
Suppose we are performning an online transaction where it requires number of request and response cycles to complete transaction,in this situation server has to remember client information.so to maintain client information at server side we need session management/Tracking.
Session Tracking is a mechanism of maintaining client information by server either at server side or client side.
we implement Session Tracking using the following techniques.
i)HttpSession
ii)Cookies.
iii)urlrewriting
iv)hidden form fields.
HttpSession
-----------
whenever a client makes a request to a server,the server will check whether the request is a new or not,if the request is a new request,server will create a new Session object and allocate this session object for the client to process subsequent request and response cycles.
Along with Session object one Session id is also created for each session,this id is used to identify a client by server.
For the first time server will process the request of client and sent back the response to client along with id and from next onwards while client is making request it will send sessionid along with request
client --->req1 -----> server
<---res1+sessionid<-----
req2+sessionid----->
<---res2+sessionid<-----
...
...
Setting time out for a session
------------------------------
we can set a timeout for a session in 2 ways
i)programmatic approach.
ii)declarative approach(xml).
Programmatic approach
---------------------
we provide session time out period programattically by using the method setMaxInactiveInterval() available in HttpSession interface.
Method signature
----------------
public void setMaxInactiveInterval(int);
Here time is represented in seconds.
code:
HttpSession session=request.getSession();
session.setMaxInactiveInterval(120);
Declarative approach
-------------------
we represent session timeout using the following tags in web.xml file
<webapp>
<session-config>
<session-timeout>value</session-timeout>
</session-config>
..
..
</webapp>
This process setting time out using xml is called declarative approach.
Here the timeout period is represented in minutes.
create a webapplication to demonstarte session-timeout
------------------------------------------------------
Add login.html
--------------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add a Servlet-->LoginServlet.java
code under doGet()
------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
// create Session object
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
if (session.isNew())
{
out.println(session.getId()+"<br>");
}
else
{
out.println(session.getId()+"<br>");
}
session.setAttribute("name", name);
session.setAttribute("pass", pass);
session.setMaxInactiveInterval(120);
// create dispatcher
RequestDispatcher dispatcher = request.getRequestDispatcher("WelcomeServlet");
dispatcher.include(request, response);
Add a servlet-->WelcomeServlet.java
code under doGet
----------------
// get Session object
HttpSession session = request.getSession();
String u = null;
String p = null;
PrintWriter out = response.getWriter();
if (session != null) {
u = (String) session.getAttribute("name");
p = (String) session.getAttribute("pass");
out.println(session.getId()+"<br>");
}
//
long l1 = session.getCreationTime();
long l2 = session.getLastAccessedTime();
// create PW
out.println("The name is " + u);
out.println("The pass is " + p);
out.println("The session created time " + new Date(l1));
out.println("The session accessed time " + new Date(l2));
out.close();
Invalidating a session
----------------------
we invalidate a session by using method invalidate() available in HttpSession interface.
syntax
------
public void invalidate();
code:
HttpSession session=request.getSession();
session.invalidate();
Cookie
------
A cookie is technique used to implement Session Tracking.
A cookie is a small text file which maintains data in the form of key and value pairs.
A cookie is created by a server and maintained at client side
A Cookie is a class available in javax.servlet.http.* package.
Constructor summary
-------------------
public Cookie(String,String)
create a cookie with key and value pair
Method summary
--------------
public void setMaxAge(int);
set expiry time to cookie.
public int getMaxAge();
gets expiry time of cookie
public String getName();
returns name of cookie.
public void setValue(String);
set a value to cookie.
public String getValue();
get a value from a cookie.
Types of cookies
----------------
There are 2 types of cookies
i)Session Cookie(temporary cookie)
ii)Persistnat cookie(perminent)
Session cookie
--------------
whenever there is a session(transaction) happening between a client and server,to identify the client by server cookie is used.
If cookie is maintained in browser memory temporarily untill the session is completed,such kind of cookie is called session cookie.
Execution flow of cookies between client and server
--------------------------------------------------
when a client make a request to a server,server will check whether the request is new,if a new a request is coming from client then server will create a cookie and send the response to the client along with cookie as shown in diagram.
From next time onwards client will send a cookie along with request so that server can identify client in the subsequent request and resonse cycles.
In this way session tracking is implemented using cookie.
How to create a cookie
----------------------
we can create cookie by using parameterized constructor.
syntax
------
Cookie cookie=new Cookie(String,String);
ex:
Cookie cookie=new Cookie("user","user");
Adding cookie to response
-------------------------
Once after we create cookie we should add cookie to response by using the method addCookie() available in HttpServletResonse.
Method signature
----------------
public void addCookie(Cookie);
syntax
------
resonse.addCookie(cookie);
step3:reading cookie coming from client request.
-----
we read cookies coming with a request from a client by using the method getCookies available in HttpServletRequest.
Method signature
----------------
public Cookie[] getCookies();
syntax
------
Cookie cookie[]=request.getCookies();
for(Cookie c1:cookie)
{
String name=c1.getName();
String value=c1.getValue();
..
..
..
}
creating a web application to demonstrate session cookie
--------------------------------------------------------
Add->login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add-->LoginServlet.java
code under doGet() method
-------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
//created cookie
Cookie cookie1=new Cookie("user",name);
Cookie cookie2=new Cookie("pass",pass);
//adding cookie to response
response.addCookie(cookie1);
response.addCookie(cookie2);
PrintWriter out=response.getWriter();
out.println("<form action='./WelcomeServlet'>");
out.println("<input type='submit' value='Go'/>");
out.println("</form>");
out.close();
Add-->WelcomeServlet.java
-------------------------
code under doGet()
------------------
Cookie cookie[] = request.getCookies();
PrintWriter out = response.getWriter();
for (Cookie c : cookie) {
String name = c.getName();
String value = c.getValue();
out.println("Nam is "+name+"<br>");
out.println("value is "+value+"<br>");
}
Execution Flow
--------------
step1:client make a request to LoginServlet
step2:Servler will execute LoginServlet,create cookie and set username and password to cookies and add them to response,along with cookies,server also sent dynamic form to client which will make a request to WelcomeServlet.
step3:
Once we click on Go button request is sent to welcomeServlet and reads cookies sent with the request and displays.
Persistent cookie
-----------------
A cookie with life time is known as persistant cookie.
A persistent cookie is stored into a browser memory perminently(i,e untill time expires).
Persistent cookie=Session cookie+expiry time.
How to set expiry time to Cookie
--------------------------------
we set expiry time to cookie by using the method setMaxAge() available in Cookie class.
syntax
------
cookie.setMaxAge(int);
Here we should represent time in seconds.
Application
-----------
In the above code add expiry time for cookies as shown in below
code
----
//created cookie
Cookie cookie1=new Cookie("user",name);
Cookie cookie2=new Cookie("pass",pass);
//setting expiry time to cookie
cookie1.setMaxAge(120);
cookie2.setMaxAge(120);
Note:
We can find persistant cookies in browser(Internet explorer) memory in the following path.
Goto Browser-->tools-->internet options-->browsing history-->settings-->view files.
Disadavantes of cookies
-----------------------
i)Cookies can deleted from browser,if such is the case session tracking may fail.
ii)Cookie is a text file and storing confidential information in cookies is not secured.
Note:
A cookie internally has a session id which is implicitly included by server at the time of cookie creation.
Session id helps server in session Tracking.
Url Rewriting
-------------
If we are using cookie to implement session tracking there is a possibility of deleting cookies from browser memory,in such situation session tracking may fail to avoid this urlrewriting is used.
Url rewriting is a technique of appending parameters with an url.
syntax
------
url?key1=value1&key2=value2&.......
sendRedirect()
--------------
It is a method which is used to navigate from one servlet to another servlet by informing to browser(through browser).
This method is available in HttpServletResponse interface.
syntax
------
response.sendRedirect("url?key1=value1&key2=value2&....");
Creating webapplication to demonstrate urlrewrting
--------------------------------------------------
Add-->login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add-->LoginServlet.java
-----------------------
code under doGet()
------------------
//read form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
//
String url="./WelcomeServlet?user="+name+"&pass="+pass+" ";
response.sendRedirect(url);
Add-->WelcomeServlet.java
-------------------------
code under doGet()
------------------
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println("Welcome "+name);
out.println("your password "+pass);
out.close();
Hidden form fields
------------------
It is a state management technique where data is transeferred between client and server in hidden i,e implicitly.
How to declare a hidden form field
----------------------------------
We declare a hidden form field by using the tag shown below
<input type="hidden" name="" value=""/>
creating a webApplication to demonstrate hidden form fields
------
Add-->login.html
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add-->LoginServlet.java
code under doGet()
-----------------
//read form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println("<form action='./WelcomeServlet'/>");
out.println("<input type='hidden' name='user' value="+name+"/><br>");
out.println("<input type='hidden' name='pass' value="+pass+"/><br>");
out.println("<input type='submit' value='GetData'/>");
out.println("</form>");
out.close();
Add-->WelcomeServlet.java
code under doGet()
------------------
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println("Welcome "+name);
out.println("your password "+pass);
out.close();
Note:
How to remove a cookie from a client
------------------------------------
we can delete a cookie from a client by server by passing time as 0(zero)
cookie.setMaxAge(0);
}
storing and selecting file with database
----------------------------------------
We use character streams to handle files.
We use a datatype clob[character large object] to store a file into a table.
create a table to store a file
--------------------------------
create table filetable(id int primary key,files clob);
How to store file into table using jdbc
----------------------------------------
To store file into a table we use the method setCharacterStream() available in PreparedStatement.
syntax
------
public void setCharacterStream(int,Reader) throws SQLException;
public void setCharacterStream(int,Reader,long) throws SQLException;
File path:
D:\Test.java
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FileStoreDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
// open file
FileReader in = new FileReader("D:\\Test.java");
// jdbc propertoes
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql
String sql = "insert into filetable values(?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,1);
statement.setCharacterStream(2,in);
int status=statement.executeUpdate();
System.out.println(status+"inserted");
in.close();
statement.close();
connection.close();
}
}
selecting file from a table
----------------------------
To select a file from a file we use the method getClob() available in ResultSet.
syntax
------
public Clob getClob(int index);
or
public Clob getClob(String colname);
getClob() returns Clob object.
To initialize Clob object we use the class Clob available in java.sql.*.
ex:
Clob b=rs.getClob(2);
To read file we have to convert Clob to Reader.
we use the method getCharacterStream() to convert Clob to Readeravailable in
Clob class.
syntax
------
public Reader getCharacterStream();
ex:
Reader reader=clob.getCharacterStream();
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FileStoreDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql
String sql = "select *from filetable";
PreparedStatement statement = connection.prepareStatement(sql);
//
ResultSet set=statement.executeQuery();
Reader reader=null;
FileWriter out=null;
while(set.next()){
int id=set.getInt(1);
Clob clob=set.getClob(2);
reader=clob.getCharacterStream();
out=new FileWriter("d:\\Manohar.java");
int val;
while((val=reader.read())!=-1){
System.out.print((char)val);
out.write((char)val);
}
}
reader.close();
out.close();
set.close();
statement.close();
connection.close();
}
}
ResultSet is of 2 types
i)unidirectional[Forward only'
ii)Bi directional[Forward and backward]
By deafult ResultSet is Forward only and Readonly cursor.
When you create a ResultSet there are three attributes you can set to make ResultSet bidirectional and updatable.
These are:
Type
Concurrency
Holdability
There are three ResultSet types:
ResultSet.TYPE_FORWARD_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
The changes in database doesn't impact ResultSet.
ResultSet.TYPE_SCROLL_SENSITIVE
The changes in database will impact ResultSet.
Concurrency
-----------
It specifies type of operation we are performing
i)read_only
ii)Updatable
Holdability
-----------
This specfies whether to close ResultSet after committing changes or not.
Method Description
-------------------
absolute()
Moves the ResultSet to point at an absolute position.
The position is a row number passed as parameter to the absolute() method.
afterLast()
Moves the ResultSet to point after the last
row in the ResultSet.
beforeFirst()
Moves the ResultSet to point before the first row in the ResultSet.
first()
Moves the ResultSet to point at the first row in the ResultSet.
last()
Moves the ResultSet to point at the last row in the ResultSet.
next()
Moves the ResultSet to point at the next row in the ResultSet.
previous()
Moves the ResultSet to point at the previous row in the ResultSet.
relative()
Moves the ResultSet to point to a position relative to its current position.
The relative position is passed as a parameter to the relative method, and can be both positive and negative.
Moves the ResultSet
How to get Scrollable and updatable ResultSet
---------------------------------------------
We to get Scrollable and updatable ResultSet then while creating Statement or PreparedStatement object we have pass the 3 attributes
i)type
ii)concurency
ii)Holdability
syntax
------
PreparedStatement statement=connection.prepareCall(Sql,type,concurrency,holdability);
ex:
PreparedStatement statement=connection.prepareCall(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE ,ResultSet.HOLD_CURSORS_OVER_COMMIT);
Methods to update ResultSet
---------------------------
The following methods are used to update columns of a table through ResultSet.
public void updateString(int index,String value);
public void updateString(String colname,String value);
public void updateInt(int index,int value);
public void updateInt(String colname,int value);
public void updateByte(int index,byte value);
public void updateByte(String colname,byte value);
public void updateShort(int index,short value);
public void updateShort(String colname,short value);
public void updateLong(int index,long value);
public void updateLong(String colname,long value);
public void updateFloat(int index,float value);
public void updateFloat(String colname,float value);
public void updateDouble(int index,double value);
public void updateDouble(String colname,double value);
public void updateBoolean(int index,boolean value);
public void updateBoolean(String colname,boolean value);
public void updateRow();
This method is used to update a row in a table,once we set values using updateXXXX() methods,we should call updateRow() method.
Program
-------
package com.manohar.satya.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JdbcResultSetMetaDataDemo {
public static void main(String[] args) throws ClassNotFoundException,SQLException, IOException {
// step1:load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String user = "system";
String pass = "manager";
// step2:creating connection
Connection connection = DriverManager.getConnection(url, user, pass);
// sql
String sql="select name,id,sal from employee";
PreparedStatement statement = connection.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
ResultSet rs = statement.executeQuery();
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt("id");
if (id == 20) {
rs.updateString("name", "Manohar");
rs.updateInt("id", 200);
rs.updateDouble("sal", 2000.00);
rs.updateRow();
}
System.out.println(rs.getInt("id"));
}
rs.afterLast();
while (rs.previous()) {
System.out.println(rs.getInt("id"));
}
rs.first();
System.out.println(rs.getInt("id"));
rs.absolute(5);
System.out.println(rs.getInt("id"));
rs.relative(-2);
System.out.println(rs.getInt("id"));
rs.last();
System.out.println(rs.getInt("id"));
in.close();
rs.close();
statement.close();
connection.close();
}
}
RowSet[inteface]
----------------
i)It is simplified form of ResultSet.
ii)It is available in javax.sql.*;
iii)It followd Pojo[Java bean] pattern i,e it consists of setters and getters.
iv)A RowSet has the following child interfaces.
CachedRowSet
FilteredRowSet
JdbcRowSet
JoinRowSet
SyncResolver
WebRowSet
JdbcRowSet[interface]
---------------------
This is similar to ResultSet,it is wrapper of a ResultSet interface.
To instantiate any RowSet interface we need the following entities
i)RowSetFactory[javax.sql.*]
ii)RowSetProvider[javax.sql.*]
RowSetFactory
-------------
It provides factory methods to instantiate different RowSet interfaces like JdbcRowSet,CachedRowSet.
Method summary
--------------
public CachedRowSet createCachedRowSet()
Creates a new instance of a CachedRowSet.
public FilteredRowSet createFilteredRowSet()
Creates a new instance of a FilteredRowSet.
public JdbcRowSet createJdbcRowSet()
Creates a new instance of a JdbcRowSet.
public JoinRowSet createJoinRowSet()
Creates a new instance of a JoinRowSet.
public WebRowSet createWebRowSet()
Creates a new instance of a WebRowSet.
RowSetProvider
--------------
It is a class which provides static factory methods to instantiate RowSetFactory interface.
Methods
-------
public RowSetFactory newFactory() throws SQLException;
How to get JdbcRowSet object
-----------------------------
step1
-----
RowSetFactory factory=RowSetProvider.newFactory();
step2:
------
JdbcRowSet set=factory.createJdbcRowSet();
JdbcRowSet
----------
It provides setters and getters to perform jdbc operations on a database.
Methods
-------
public void setUrl(Stri
ng);
public void setUsername(String);
public void setPassword(String);
public void setCommand(String);
public void setXXX(datatype);
public String getString(int);
public String getString(String);
public String getInt(int);
public String getInt(String);
public datatype getXXX(int);
public datatype getXXX(String);
public boolean next()
publlic execute() throws SQLException
Write a jdbc program to get rows from a table and iterate them using RowSet.
package com.manohar.satya.jdbc;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
public class JdbcRowSetDemo {
public static void main(String[] args) throws SQLException {
//step1
RowSetFactory factory=RowSetProvider.newFactory();
//step2
JdbcRowSet set=factory.createJdbcRowSet();
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String pass="manager";
set.setUrl(url);
set.setUsername(user);
set.setPassword(pass);
set.setCommand("select *from employee");
set.execute();
while(set.next()){
String name=set.getString(1);
System.out.println(name);
}
}
}
Note:
It is not necessary to load jdbc driver in jdbc4.0 version.
Servlet Collaboration
---------------------
Communication between two servlets is known as ServletCollaboration.
we can navigate from one servlet to another using the following techniques.
i)RequestDispatcher
ii)Hyperlink
iii)sendRedirect
we can exchange data from one Servlet to another by using attributed approach.
we use the following methods to perform read,write,remove operations between 2 servlets.
i)setAttribute()
sets data to a scope.
ii)getAttribute()
gets data from a scope
iii)removeAttribute()
remove data from a scope.
what is a scope?
A scope is can be defined as the extent of service that can be provided by an Object.
we have 3 differet scope's in servlet.
i)request scope
ii)application scope(ServletContext)
iii)Session scope.
request scope is useful to exachange data between 2 servlets in one request and response cycle.
application scope is useful to exchange data between 2 servlets untill a project is running.
Session scope is useful to exchange data between 2 servlets with in a given a session.
we can write,read,remove data with all the above scopes using above 3 methods.
setAttribute()
--------------
It is used to set data to a scope.
Method signature
----------------
public void setAttribute(String,Object);
How set data to a scope
-----------------------
syntax
------
reference.setAttribute(String,Object);
Here reference is reference of request\application\session
ex:
request.setAttribute("user","manohar");
getAttribute()
--------------
It returns object from a scope.
Method signature
----------------
public Object getAttribute(String);
How to get data a scope
-----------------------
syntax
------
reference.getAttribute(String);
ex:
request.getAttribute("user");
removeAttribute()
-----------------
removes an object from a scope.
Method signature
----------------
public void removeAttribute(String);
syntax
------
request.removeAttribute(String);
ex:
request.removeAttribute("user");
RequestDispatcher
-----------------
It is an interface used to navigate from one servlet to another servlet.
It is available in javax.servlet.* package.
we have 2 types of dispatching techniques.
i)include.
ii)forward.
include mechanism
-----------------
In this technique,if we have 2 servlets Servlet1,Servlet2,
when a client makes a request,the request is sent to servlet1 and from there servlet1 dispatches a request to servlet2 using include() method,here once servlet2 process the request,the response is sent back to servlet1 and finally servlet1 will send back response to client.
forward mechanism
-----------------
In this technique,if we have 2 servlets Servlet1,Servlet2,
when a client makes a request,the request is sent to servlet1 and from there servlet1 dispatches a request to servlet2 using foward() method,here once servlet2 process the request,the response is sent back to client directly from servlet2 without giving any notification servlet1.
How to get RequestDispatcher object.
-----------------------------------
we get RequestDispatcher object by using the getRequestDispatcher() available in ServletRequest iinterface.
Method signature
----------------
public RequestDispatcher getRequestDispatcher(String url);
syntax
------
RequestDispatcher dispatcher=request.getRequestDispatcher(String);
ex:
RequestDispatcher dispatcher=request.getRequestDispatcherS("WelcomeServlet");
How to call include() method
----------------------------
syntax
------
dispatcher.include(request,response);
How to call forward() method
----------------------------
syntax
------
dispatcher.forward(request,response);
creating a webapplication to navigate from one Servlet to another servlet
Requirement
-----------
validate a login form and naviagate to WelcomeServlet if validation is successful otherwise navigate to ErrorServlet.
login.html
----------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
create LoginServlet.java
------------------------
code under service method
-------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
// creating Dispacher Objects
RequestDispatcher dispatcher1 = request.getRequestDispatcher("WelcomeServlet");
RequestDispatcher dispatcher2 = request.getRequestDispatcher("ErrorServlet");
if (name.trim().equalsIgnoreCase("manohar") && pass.trim().equalsIgnoreCase("manohar")) {
dispatcher1.include(request, response);
}
else
{
dispatcher2.include(request, response);
}
create WelcomeServlet.java
--------------------------
code under service() method
---------------------------
PrintWriter out=response.getWriter();
out.println("Login Success");
out.close();
create ErrorServlet.java
------------------------
code under service() method
---------------------------
PrintWriter out=response.getWriter();
out.println("Login UnSuccess!!!Please valid credentials");
out.close();
Url
---
http://localhost:8070/LogingProject/login.html
creating a webapplication to validate credentials and share them from LoginServlet to WelcomeServlet using request sacope.Also using Map to set credentials and share to WelcomeServlet.
login.html
----------
copy from above program
create LoginServlet.java
------------------------
code under service() method
---------------------------
// reading form
String name = request.getParameter("user");
String pass = request.getParameter("pass");
// creating Dispacher Objects
RequestDispatcher dispatcher1 = request.getRequestDispatcher("WelcomeServlet");
RequestDispatcher dispatcher2 = request.getRequestDispatcher("ErrorServlet");
//creating HashMap
HashMap<String,String> map=new HashMap<String,String>();
if (name.trim().equalsIgnoreCase("manohar") && pass.trim().equalsIgnoreCase("manohar")) {
//setting user to request attribute. request.setAttribute("user",name);
request.setAttribute("pass",pass);
//setting credentials to Map
map.put("user",name);
map.put("pass",pass);
//setting object to request scope
request.setAttribute("map",map);
dispatcher1.include(request, response);
}
else
{
dispatcher2.include(request, response);
}
create WelcomeServlet.java
--------------------------
code under service
------------------
PrintWriter out=response.getWriter();
//reading String
String user=(String) request.getAttribute("user");
String pass=(String) request.getAttribute("pass");
//reading Map
Map<String,String> map=(Map<String, String>) request.getAttribute("map");
out.println("Welcome "+user);
out.println("Your password is "+pass);
out.println("Welcome "+map.get("user"));
out.println("Your password "+map.get("pass"));
out.close();
create ErrorServlet.java
------------------------
code under service
------------------
PrintWriter out=response.getWriter();
out.println("Login UnSuccess!!!Please enter valid credentials");
out.close();
HttpServlet
-----------
It is a child class of GenericServlet.
It supports only Http(protocol).
It provides certain http methods
doGet()
doPost()
doPut()
doXXXX()
HttpServlet is an abstract class.
why HttpServlet is an abstract ?
All the methods in HttpServlet are concrete methods,but these methods doesn't have proper logic implementation so
HttpServlet is declared as abstract,so that it is restricted from instantiation.
HttpServlet is available in javax.servlet.http.* package.
Heirarchy
---------
Servlet
^
|
GenericServlet
^
|
HttpServlet
Method summary
--------------
protected void doGet(HttpServletRequest,HttpServletResponse) throws ServletException,IOException;
protected long getLastModifie(HttpServletRequest);
protected void doHead(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doPost(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doPut(HttpServletRequest,
HttpServletResponse) throws ServletException, java.io.IOException;
protected void doDelete(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doOptions(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void doTrace(HttpServletRequest, HttpServletResponse) throws ServletException,IOException;
protected void service(HttpServletRequest,HttpServletResponse) throws ServletException,IOException;
public void service(ServletRequest,ServletResponse) throws ServletException,IOException;
Life cycle methods of HttpServlet
---------------------------------
init(ServletConfig)//Servlet
init()//GenericServlet
protected void service()//HttpServlet
public void service()//GenericServlet
doXXX()//HttpServlet
destroy()//Servlet
Excecution Flow of HttpServlet life cycle process
-------------------------------------------------
If any client make a request HttpServlet for first time the following life cycle operations take place.
step1:loading servlet.
Step2:Instantiating Servlet.
Step3:creating ServeletConfig object and invokes parameterized init method by passing ServletConfig object as a parameter
public void init(ServletConfig);
step4:Parameterized init() method calls default init()
public void init();
step5:creating ServletRequest and ServletResponse objects and then invokes service method of GenericServlet by passing request and response objects as parameters.
public void service(ServletRequest,ServletResponse)
step6:public service() will invoke protected service() method HttpServlet by passing requset and respnse objects as parameters,here casting is applied to convert ServletRequest to HttpServletRequest similarly for resonse also.
step7:protected service() will invokes doXXX() methods of a HttpServlet by passing HttpServletRequest,HttpServletResponse objects as parameters.
step8:destroy method called if the project is shutdown or a servlet is undeployed by administrator,which is used to
perform cleanup operations on a HttpServlet.
create a LoginProject to process login form using HttpServlet
Add login.html
--------------
<form action="./LoginServlet" method="get">
UserName:<input type="text" name="user"/><br>
PassWord:<input type="password" name="pass"/><br>
<input type="submit" value="Login"/><br>
</form>
Add a HttpServlet-->LoginServlet.java
Goto src-->package-->com.manohar.servlets-->right click on package-->new-->Servlet-->ServletName-->LoginServlet
SuperClass-->HttpServlet
-->next-->next-->select required doXXX() to override in sub class-->finish
code under doGet() method
-------------------------
//read form
String name=request.getParameter("user");
String pass=request.getParameter("pass");
PrintWriter out=response.getWriter();
out.println(name);
out.println(pass);
out.close();
url
---
http://localhost:8070/HttpLoginProject/login.html
employee.html
-------------
<form action="./EmployeeController" method="post">
Enter Name:<input type="text" name="name"/><br>
Enter ID:<input type="text" name="id"/><br>
Enter Salary:<input type="text" name="sal"/><br>
<input type="submit" name="save" value="Save"/><br>
<input type="submit" name="update" value="update"/><br>
<input type="submit" name="delete" value="delete"/><br>
<input type="submit" name="select" value="select"/><br>
</form>
EmployeeController.java
-----------------------
@WebServlet("/EmployeeController")
public class EmployeeController extends HttpServlet {
private EmployeeService service = null;
public void init() {
service = new EmployeeServiceImpl();
}
code under doPost()
-------------------
// read form
String name = request.getParameter("name");
String id = request.getParameter("id");
String sal = request.getParameter("sal");
//reading identifiers from form
Enumeration enumeration = request.getParameterNames();
int empid=0;
if (id != null) {
empid = Integer.parseInt(id);
}
double empsal=0.0;
if (sal != null) {
empsal = Double.parseDouble(sal);
}
// create pojo
Employee employee=null;
if (id != null && sal != null && name != null) {
employee= new Employee();
employee.setEmpID(empid);
employee.setEmpName(name);
employee.setEmpSal(empsal);
}
int status = 0;
while (enumeration.hasMoreElements()) {
String btn = (String) enumeration.nextElement();
if (btn.equalsIgnoreCase("save")) {
status = service.insert(employee);
PrintWriter out =response.getWriter();
out.println(status + "records inserted");
out.close();
}
if (btn.equalsIgnoreCase("update")) {
status = service.update(employee);
PrintWriter out = response.getWriter();
out.println(status + " records updated");
out.close();
}
if (btn.equalsIgnoreCase("delete")) {
status = service.delete(empid);
PrintWriter out = response.getWriter();
out.println(status + " records deleted");
out.close();
}
if (btn.equalsIgnoreCase("select")) {
Employee employee2 = service.selectEmployee(empid);
PrintWriter out = response.getWriter();
out.println("EmpName " + employee2.getEmpName());
out.println("EmpId " + employee2.getEmpID());
out.println("EmpSal " + employee2.getEmpSal());
out.close();
}
}
No comments:
Post a Comment