Adv Java Material PDF
Adv Java Material PDF
Ratan
1|Page
Ratanit Adv.Java Mr. Ratan
JDBC
Parts of the java: Core java & adv java are not official terms.
As per the sun micro system standard the java language is divided into three types.
1) J2SE/JSE(java 2 standard edition) corejava,jdbc
2) J2EE/JEE(java 2 enterprise edition) servlets,Jsp,EJB,JMS,web-services XML,JNDI
3) J2ME/JME(java 2 micro edition)
Adv java
2|Page
Ratanit Adv.Java Mr. Ratan
When we develop the application by using technology, the code is duplicated & length increased
but when we develop the application by using framework it reduce the code duplication & length
of the code because framework having more predefined support.
Web-applications
Developed by using j2ee(servlets & jsp) technology : structs JSF framework
No-main method contains life cycle methods(init() service() destroy() ) called by server
Used extension .war
Enterprise applications
Developed by using EJB technology & spring frame work
Used extension .ear
Distributed applications
Developed by using RMI , web-services v, Micro services
Used extension .aar application archive file
Mobile applications
Developed by using android ,IOS
Different types of mobile apps
Native apps: Installed & doesn’t required internet Conn to run : candy crush
Hybrid apps : installed & required internet connection to run : facebook
Web apps : run through web browser
Used extension .apkandroid application package
3|Page
Ratanit Adv.Java Mr. Ratan
ODBC vs JDBC :
Even today C and C++ application are connecting with oracle database using a set of function
given by Oracle Corporation in a orcl.h header file.
But problem with the above communication is a front end application become as a database
dependent application because every database vendor give its own set of function for communication.
To overcome the database dependent problem ODBC (Open database connectivity) community
formed by Microsoft corporation.
ODBC community has provided ODBC API, to connect with any database in a database
independent manner.
ODBC:
1. ODBC is given by Microsoft Corporation it is a database dependent & platform dependent.
2. It is written in C-language.
JDBC :
1. It is platform & database independent.
2. It is written in java.
JDBC Overview :
JDBC specifications:-
Jdbc specifications are given by Sun micro systems.
It is a pdf document (JRS java requirement specifications)
JDBC API:-
API given by Sun Micro Systems.
It contains more interfaces & few classes.
These interfaces & classes are present two packages (java.sql , javax.sql).
These two packages are present in rt.jar file.
The jar file location is:C:\Program Files\Java\jre1.8.0_65\lib\rt.jar (extract the jar file check the two
packages classes & interfaces).
JDBC implementations:-
Implementations are given by database vendors in the form of jar file.
Oracle 10g ----> ojddbc14.jar
Oracle 11g ----> ojdbc 6.jar , ojdbc5.jar
Oracle 12c ----> ojdbc6.jar, ojdbc7.jar
MySql ---> Mysql-connector.jar
Extract the jar file we will get all implementations classes .and to check these class file code use java
de-compiler software.
4|Page
Ratanit Adv.Java Mr. Ratan
5|Page
Ratanit Adv.Java Mr. Ratan
Web-application architecture:
Client Server
Client: Who sends the request & takes the response is called client.
ex: InternetExploral, MozillaFrefox, opera, chrome ……. Etc
Server: The server contains the applications & it performs fallowing actions.
a. It takes the request from the client.
b. It identifies the requested resource.
c. It processes the request (Request Processing).
d. It generates the response based on client request.
ex: Tomcat,GlassFish,WebLogic,JBOSS,WebSphere …… etc
Database: Database is used to store the details like client details, application details……etc.
ex :- Oracle,MySql ….etc
6|Page
Ratanit Adv.Java Mr. Ratan
J2se:- Used to develop the standalone applications it contains main method executed by JVM.
J2EE:- Used to web applications it does not contains main method, it contains life cycle methods (init()
service() destroy() ) called by servers.
2. Callback methods: these methods are automatically called by server or JVM or other method..etc
Main ---> called by JVM
Init () service() destroy() ---> called by server
Finalize ---> called by Garbage Collector
Run () method ----> called by start()
Note: All the JDBC main classes and interfaces present in two packages
java.sql package : Basic Concepts
javax.sql : Advanced features like connection pooling.
7|Page
Ratanit Adv.Java Mr. Ratan
Step 2: Based on operating system & process used download the software.
8|Page
Ratanit Adv.Java Mr. Ratan
Registration free: register first then give the username & password.
Username:
Password:
The Oracle Express Edition installation automatically comes with "system" & "sys" accounts.
During installation, we have to enter common password for both accounts. The standard password is
"manager". However you can give different password.
Connect to SQL prompt: in search type runSQL command line we will get below window.
Or
9|Page
Ratanit Adv.Java Mr. Ratan
10 | P a g e
Ratanit Adv.Java Mr. Ratan
If your system type is 32-bit, then download "Windows (x86, 32-bit), MSI Installer"
If your system type is 64-bit, then download "Windows (x86, 64-bit), MSI Installer"
Download "http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/3.0.10/mysql-
connector-java-3.0.10-stable-bin.jar"
Connection details:
driverClassName= com.mysql.jdbc.Driver
url= jdbc:mysql://localhost:3306/ratan
username= root
password= root
11 | P a g e
Ratanit Adv.Java Mr. Ratan
12 | P a g e
Ratanit Adv.Java Mr. Ratan
mysql> INSERT INTO products VALUES (1001, 'PEN', 'Pen Red', 5000, 1.23);
13 | P a g e
Ratanit Adv.Java Mr. Ratan
2) Statement : it is used to send the queries to database side nothing but execute the query.
3) PreparedStatement: it is used to execute the query but number of steps are reduced
performance will be increased.
5) ResultSet : it is used to store the data coming from database like table data.
10) DataSource
11) PooledConnection
The above two interfaces are used to manage the Connection pooling concept.
14 | P a g e
Ratanit Adv.Java Mr. Ratan
Driver:-
1) Jdbc driver is software it enables the java application to interact with database.
2) Driver is interface between the java application and the particular database.
3) Driver is acting as a translator between the java application and particular database. And it
Is converting java formatted SQL queries into the Database supported SQL queries.
D
Java DBA(data
supported R base engine)
Java Oracle
format (API) (API)
I
query.
V
R
Types of the drivers:-
1) Type-1 driver (JDBC-ODBC Bridge Driver)
2) Type-2 driver (Native API driver)
3) Type-3 driver (Network protocol Driver)
4) Type-4 driver (Thin Driver)
DBC API:-
Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC
API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has
defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
Drivers in JDBC:-
To use the jdbc Driver in java application we must register that driver into Driver manager service.
DriverManager service is built in service to manage set of jdbc drivers.
Use the fallowing code to register jdbc driver into DriverManager service.
Step1:-creating driver Object
sun.jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();
step2:registering driver into driver manager service.
DriverManager.registerDriver(obj);
In present application To load the driver class into application we are using fallowing code,
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
The above statements loads driver class and it register driver class into DriverManager
service with the help of static block present in JdbcOdbcDriver class.
15 | P a g e
Ratanit Adv.Java Mr. Ratan
16 | P a g e
Ratanit Adv.Java Mr. Ratan
1. Type-1 Driver:
This driver the access to database using ODBC driver. And this driver is introduced by sun micro
systems with the interdependency on Microsoft product ODBC driver.
Advantages :
Type-1 Driver is highly recommended for Standalone applications.
Disadvantages :
If we want to use Type-1 Driver in our Jdbc applications then we must install the
Microsoft provided ODBC native library in our machine.
In case of Type-1 Driver, to interact with database we have to perform 2 types of
conversions i.e. from Java to Odbc and Odbc to the respective database.Due to
this reason Type-1 driver is slower Driver,it will reduce performance of the Jdbc
applications.
Type-1 Driver is not suitable for web applications.
Type-1 Driver is suggestible for simple Jdbc applications, but not suggestible for
complex
Jdbc applications.
2. Type-2 driver:-
If we want to use Type-2 Driver in our Jdbc applications then we have to install thedatabase
vendor provided Native library.
When compared with Type-1 Driver Type-2 Driver is more portable Driver because itshould not
require Microsoft provided Native library. When compared with Type-1 Driver Type-2 Driver is
faster Driver because it should not require two time conversions.
Type-2 Driver is suggestible for only standalone applications, but not suggestible forweb
applications.
3. Type-3 driver:-
a. Type-3 Driver is also called as Middleware Database Access Driver or NetworkDriver.
b. Type-3 Driver will provide very good environment to interact with multiple number of
databases from multiple clients at a time.
c. This driver translates the JDBC calls into the middleware vendors protocols, which is then
translated to a DBMS protocol by a middleware server. The middleware provides
connectivity to many different databases.
4. Type-4 driver:-
a. Type-4 Driver is also called as Thin Driver or Pure Java Driver.
b. Type-4 Driver was designed purely on the basis of Java technology.
c. Type-4 Driver is more portable Driver when compared with Type-1, Type-2 and Type-3
Drivers because Type-4 Driver should not require Odbc Native library, Database vendor
provided Native library and Application Server provided Middleware components.
d. Type-4 Driver is frequently used Driver in Application Development.
e. Type-4 Driver is recommended for any type of Java, J2EE applications i.e. both
standalone applications and enterprise applications.
f. Type-4 Driver is faster Driver when compared with all the remaining Drivers because
Type-4 Driver should not require 2 times conversions in order to interact with database
from Java applications.
17 | P a g e
Ratanit Adv.Java Mr. Ratan
Type-1 driver:-
Driver class name sun.jdbc.odbc.JdbcOdbcDriver
Driver URL pattern jdbc:odbc:DSNname
Example : jdbc:odbc:rattan
In the aboveexample we are using DSN name is: Ratan
Type-4 driver:-
Driver class name oracle.jdbc.driver.OracleDriver
Driver URL pattern jdbc:oracle:thin:@localhost:1521:xe where xe=logical name of the database
localhost represent the current machine in the project level using ip address
If we are using express edition the logical name is xe
If we are using enterprise edition the logical name is orcl
It is possible to change the logical name of the database
18 | P a g e
Ratanit Adv.Java Mr. Ratan
Example : In below example we are using throws keyword to delegate the exception but here after
exception code is not executed.
class Test
{ void m1() throws ArithmeticException
{ System.out.println(“connection opening=”+10/0);
System.out.println("after exception code database closing");
}
public static void main(String[] args) throws ArithmeticException
{ new Test().m1();
}
}
Example : In below example method is delegating exception and caller method is handling
exception but after exception code is not executed.
class Test
{ void m2() throws ArithmeticException
{ System.out.println(“connection opening=”+10/0);
System.out.println("after exception code database closing");
}
void m1()
{ try{ m2(); } catch(ArithmeticException ae){ae.printStackTrace();}
}
public static void main(String[] args)
{ new Test().m1();
}
}
Note: In above two examples after exception code is resource releasing (like database closing
operations) that code is not executed hence we will get the resource problems.
19 | P a g e
Ratanit Adv.Java Mr. Ratan
To load the driver .class file byte code into memory user forName() method, it is a static
method present in Class class hence access this method by using class name.
public static java.lang.Class forName(java.lang.String) throws ClassNotFoundException;
getConnection() method throws SQLException() and it is a checked exception so must handle that
exception by using try-catch blocks or throws keyword.
20 | P a g e
Ratanit Adv.Java Mr. Ratan
21 | P a g e
Ratanit Adv.Java Mr. Ratan
1-Way to load jar file : paste the ojdbc14.jar file in jre/lib/ext folder
22 | P a g e
Ratanit Adv.Java Mr. Ratan
The above 2-ways are not recommended because in real-time projects we are using eclipse IDE
to develop the application so we will use build path to set the jar file.
3- way to load the jar file : Build path
23 | P a g e
Ratanit Adv.Java Mr. Ratan
24 | P a g e
Ratanit Adv.Java Mr. Ratan
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step 1: load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
In above example we have to build path the jar file based on which version of database we are using.
In above example we are using throws, in this case when exception raised program terminated
abnormally there may be chance of resources are not released.
To overcome above problem to release the resources normally use the finally block this code always
executed to release the resources.
Note: In application level when we have resource releasing option it is recommended to use finally block.
25 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
26 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
27 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
try
{ Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("table created successfully....="+a);
statement = connection.createStatement();
String q1="create table emp(eid number primary key,ename varchar2(30),esal number)";
int a = statement.executeUpdate(q1);
System.out.println("table created successfully....="+a);
Thread.sleep(20000);//20 sec
28 | P a g e
Ratanit Adv.Java Mr. Ratan
Application 5 : In below example we are using type-1 driver hence we have to set DSN name.
29 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Output:- if we are using type-1 driver (we have to set DSN name use dsn name)
*****connection creation process******
*****table creation process******
table is create successfully = -1
table dropped successfully = -1
Output:- if we are using type-1 driver (we have to set DSN name use dsn name)
*****connection creation process******
*****table creation process******
table is create successfully = 0
table dropped successfully = 0
30 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Set.close();
statement.close();
connection.close();
System.out.println("connection is closed");
}
}
In the line-1 pass the updating group sql statement check the output.
In the line-1 pass the selection group sql statement check the output.
31 | P a g e
Ratanit Adv.Java Mr. Ratan
Scanner class present in java.util package and it is introduced in 1.5 versions & it is used to take
dynamic input from the end-user.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("*****emp details*****");
System.out.println("emp no----->"+eno);
System.out.println("emp name---->"+ename);
System.out.println("emp sal------>"+esal);
s.close();
}
}
s.close();
}
}
Example :- Application taking dynamic input from the keyboard by using scanner class.
32 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("connection created successfully..........");
while(true)
{ System.out.println("enter emp id");
int eid = scanner.nextInt();
statement.executeUpdate(q2);
System.out.println("values are inserted successfully do you want one more(yes/no)");
String option = scanner.next();
if(option.equals("no"))
{ break;
}
}
connection.close();
scanne.close();
System.out.println("connection closed successfully…..");
}
}
Java.sql.PreparedStaement:
33 | P a g e
Ratanit Adv.Java Mr. Ratan
2) Whenever we are executing the query the database side the fallowing operations will be performed.
a. Query tokenization
b. Query parsing
c. Query optimization
d. Query execution
3) If we using Statement interface to execute query every time the above operations (query
compilation) are performed it effects on performance of the application.
4) To overcome the above limitation use preparedstatement. When we use the preparedstatement the
query compilation done only once it improves the performance of the application.
5) In case of preparedstatement the query compilation done only once then DBE prepare query plan
with unique id, later just set the data execute the query it improves performance of the application.
Note : if we want to execute the query only once simple use statement object but if we want execute the
same query ‘n’ number of times use prepared statement.
34 | P a g e
Ratanit Adv.Java Mr. Ratan
In PreparedStatement only '?' symbol are allow, no other symbols are allowed.
'?' is only for replacing value but not for table name or column names.
'?' symbol are not allowed in DDL operation.
'?' symbol is called parameter or replacement operator or place-resolution operator.
Its value will be set by calling the setter methods of PreparedStatement.
To set values to the positional parameters we will use setter method of PreparedStatement.
public void setXxx(int param_index, xxx value)
preparedStatement.setInt(1, 111);
preparedStatement.setString(2, “ratan”);
preparedStatement.setDouble(3, 10000.45);
preparedStatement.setInt(1, eid);
preparedStatement.setString(2, ename);
preparedStatement.setDouble(3, esal);
35 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
while(true)
{ System.out.println("enter emp id");
int eid = scanner.nextInt();
preparedStatement.close();
scanner.close();
connection.close();
System.out.println("connection closed successfully....");
}
}
Application-2 : PreparedStatement with updating query.
36 | P a g e
Ratanit Adv.Java Mr. Ratan
PreparedStatement preparedStatement =
connection.prepareStatement("update emp set esal=esal+? where esal>?");
preparedStatement.setInt(1, 100);
preparedStatement.setInt(2, 2000);
int a = preparedStatement.executeUpdate();
System.out.println(a);
preparedStatement.setInt(1, 2000);
37 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/vishnu","root","root");
System.out.println("connection created successfully with mysql..........");
while(set.next())
{ System.out.println(set.getInt(1)+"--"+set.getString(2)+"--"+set.getDouble(3));
}
System.out.println("operations are completed");
}
}
In above we are using mysql driver class so this driver class implementation given by mysql database
vendor in the form of the jar file
Mysql-connector.jar
In eclipse ide must set the build path configurations otherwise in project folder create the lib folder
manually and copy the jar file and paste the jar file in lib folder the refresh the project.
38 | P a g e
Ratanit Adv.Java Mr. Ratan
Test.java
package com.dss;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class TestDb
{ public static void main(String[] args)
throws ClassNotFoundException, SQLException, IOException
{ FileInputStream inputStream = new FileInputStream("abc.properties");
Properties properties = new Properties();
properties.load(inputStream);
Class.forName(properties.getProperty("driver"));
Connection connection =DriverManager.getConnection(properties.getProperty("url"),
properties.getProperty("username"), properties.getProperty("password"););
System.out.println("Connection created successfully.....");
connection.close();
System.out.println("connection is closed");
}
}
Java.sql.ResultSet:-
39 | P a g e
Ratanit Adv.Java Mr. Ratan
1. ResultSet is an interface present in the java.sql package and it is used to hold the values which
are coming from data base.
2. When we create the ResultSet object the resultset cursor is pointing to before first record.
3. The default ResultSet object is CONCUR_READ_ONLY and TYPE_FORWARD_ONLY .
ResultSet's Type:-
Forward cursor:-
ResultSet.TYPE_FORWARD_ONLY (default):
By using this ResultSet it is possible to moves forward only from the first row to the last
row via the next() method.
Scrollable cursor:-
ResultSet.TYPE_SCROLL_SENSITIVE:
The ResultSet reflects changes made by others to the underlying data source while it
remains opened.
ResultSet.TYPE_SCROLL_INSENSITIVE:
The ResultSet does NOT reflect change made by others to the underlying data source
while it is opened, hence, insensitive to changes.
ResultSet's Concurrency:-
ResultSet.CONCUR_READ_ONLY (default):
The ResultSet is read-only. You cannot update the underlying database via the ResultSet.
ResultSet.CONCUR_UPDATABLE:
The ResultSet object can be updated via the updateXxx() methods. Change in ResultSet is
reflected in the underlying database.
While creating statement object we have to specify the result set type. And type is the first argument &
concurrency is the second argument.
Type & concurrency is the static constants of ResultSet so access the static constants by using ResultSet.
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
40 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521","system","ratan");
System.out.println("connection created successfully with Oracle..........");
The default ResultSet object is forward only and read only hence it is not possible to perform
previous() method we will get the exception.
But the same application if we are using Mysql the output will be printed it means the behavior
of the ResultSet object is changed from database to database but the generic way it is always
recommended to set the type & concurrency based on the operation we are performing.
41 | P a g e
Ratanit Adv.Java Mr. Ratan
ResultSet Cursor methods:- when we create ResultSet object is first created, the cursor is
positioned before the first row.
Next():-
Moves the cursor forward one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned after the last row.
public abstract boolean next() throws java.sql.SQLException;
Previous():
Moves the cursor backward one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned before the first row.
public abstract boolean previous() throws java.sql.SQLException;
First():-
Moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now
positioned on the first row and false if theResultSet object does not contain any rows.
public abstract boolean first() throws java.sql.SQLException;
Last():-
Moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet object does not contain any rows.
public abstract boolean last() throws java.sql.SQLException;
beforeFirst():-
Positions the cursor at the start of the ResultSet object, before the first row. If
the ResultSet object does not contain any rows, this method has no effect.
public abstract void beforeFirst() throws java.sql.SQLException;
afterLast():
Positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet object
does not contain any rows, this method has no effect.
public abstract void afterLast() throws java.sql.SQLException;
absolute(int row):- Positions the cursor on the row specified by the parameter row.
42 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("connection created successfully..........");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
set.afterLast();
while(set.previous())
{ System.out.println(set.getInt(1)+"--"+set.getString(2)+"--"+set.getDouble(3));
}
set.first();
System.out.println(set.getInt(1));
set.last();
System.out.println(set.getInt(1));
set.absolute(3);
System.out.println(set.getInt(1));
43 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/vishnu","root","root");
System.out.println("connection created successfully with mysql..........");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
set.moveToInsertRow();
set.updateInt (1, 55);
set.updateString (2, "ratan");
set.updateFloat (3,2000);
set.insertRow();
set.beforeFirst();
44 | P a g e
Ratanit Adv.Java Mr. Ratan
Example : Java.sql.ResultSetMetaData
It is used to get the metadata of the particular table like
a. Number of column in table
b. Data type of the column
c. Size of the column…etc
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/vishnu","root","root");
System.out.println("connection created successfully with mysql..........");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.println(metaData.getColumnCount());
System.out.println(metaData.getColumnTypeName(2));
System.out.println(metaData.getColumnDisplaySize(2));
System.out.println(metaData.getColumnName(2));
45 | P a g e
Ratanit Adv.Java Mr. Ratan
Example :- Java.sql.DataBaseMetaData:-
DataBaseMetaData is used to get the metadata of the particular table .Database username,
Drivername,atabase version………………..etc
abc.properties:
username=system
password=ratan
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
TestDb.java
package com.dss;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class TestDb
{ public static Connection createConnection()
{ Connection connection = null;
try { Properties properties = new Properties();
properties.load(new FileInputStream("abc.properties"));
Class.forName(properties.getProperty("driver"));
connection = DriverManager.getConnection(properties.getProperty("url"),
properties.getProperty("username"),properties.getProperty("password"));
} catch (IOException | ClassNotFoundException | SQLException e) {
e.printStackTrace(); }
return connection;
}
}
TestDb1.java
package com.dss;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
public class TestDb1 {
public static void main(String[] args) throws SQLException {
Connection connection = TestDb.createConnection();
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("Database name : "+metaData.getDatabaseProductName());
System.out.println("Database version : "+metaData.getDatabaseProductVersion());
System.out.println("Database useranme: "+ metaData.getUserName());
System.out.println("Database url:"+metaData.getURL());
System.out.println("Database driver:"+metaData.getDriverName());
System.out.println("Database driver version:"+metaData.getDriverVersion());
connection.close();
System.out.println("connection closed successfully.....");
}
}
46 | P a g e
Ratanit Adv.Java Mr. Ratan
Example 1:-
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
class SearchFrame extends Frame implements ActionListener
{ Label l;
TextField tf;
Button b;
Connection con;
Statement st;
ResultSet rs;
SearchFrame()
{ try
{ this.setVisible(true);
this.setSize(500,400);
this.setBackground(Color.pink);
this.setTitle("JDBC - AWT Application");
this.setLayout(new FlowLayout());
l=new Label("productId");
tf=new TextField(15);
b=new Button("Search");
b.addActionListener(this);
this.add(l);
this.add(tf);
this.add(b);
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
st=con.createStatement();
}
catch (Exception e)
{ e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae)
{ try
{ rs=st.executeQuery("select * from emp where eno='"+tf.getText()+"'");
repaint();
}
catch (Exception e)
{ e.printStackTrace();
}
47 | P a g e
Ratanit Adv.Java Mr. Ratan
}
public void paint(Graphics g)
{ try
{
Font f=new Font("arial",Font.BOLD,30);
g.setFont(f);
boolean b=rs.next();
if(b==true)
{ g.drawString("emp id....."+rs.getInt(1),50,100);
g.drawString("emp Name....."+rs.getString(2),50,150);
g.drawString("emp sal....."+rs.getInt(3),50,200);
}
else
{ g.drawString("emp does not exists",50,150);
}
}
catch (Exception e)
{ e.printStackTrace();
}
}
}
class Test
{ public static void main(String[] args)
{ new SearchFrame();
}
}
48 | P a g e
Ratanit Adv.Java Mr. Ratan
Example:-
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class MyFrame extends Frame implements ActionListener
{ Button b1,b2;
Connection con;
ResultSet rs;
Statement st;
String label;
MyFrame()
{ try{
this.setVisible(true);
this.setSize(500,500);
this.setBackground(Color.red);
b1=new Button("NEXT");
b2=new Button("PREVIOUS");
this.setLayout(new FlowLayout());
this.add(b1);
this.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ratan","system","manager");
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=st.executeQuery("select * from emp");
}
catch(Exception e)
{ System.out.println(e);
}
}
public void actionPerformed(ActionEvent e)
{ label=e.getActionCommand();
repaint();
}
public void paint(Graphics g)
{ try{
if (label.equals("NEXT"))
{ boolean b=rs.next();
if (b==true)
{ g.drawString("emp number"+rs.getInt(1),50,100);
g.drawString("emp name"+rs.getString(2),50,200);
g.drawString("emp sal"+rs.getInt(3),50,300);
}
else
{ g.drawString("no record",50,500);
}
}
49 | P a g e
Ratanit Adv.Java Mr. Ratan
if (label.equals("PREVIOUS"))
{ boolean b=rs.previous();
if (b==true)
{ g.drawString("emp number"+rs.getInt(1),50,100);
g.drawString("emp name"+rs.getString(2),50,200);
g.drawString("emp sal"+rs.getInt(3),50,300);
}
else
{ g.drawString("no record",50,500);
}
}
}
catch(Exception e)
{ System.out.println(e); }
}
};
class Test
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
50 | P a g e
Ratanit Adv.Java Mr. Ratan
Transaction Management:-
Transaction represents a single unit of work.
The ACID properties describes the transaction management well.
ACID stands for
Atomicity
Consistency
Isolation
Durability.
51 | P a g e
Ratanit Adv.Java Mr. Ratan
Suppose a movie ticket booking at online is a transaction. This task contains four operation.
Verify the seats
Reserve the seats
Payment
Issue tickets
If all the above four operations are done successfully then a transaction is finished
successfully. In the middle, if any one operation is failed then all operation are canceled and
finally a transaction is failed.
Types of Transaction:
1. Local Transaction
2. Distributed or global transaction
Local Transaction:- A local transaction means, all operation in a transaction are executed
against one database.
For example; If transfer money from first account to second account belongs to same bank then
transaction is local transaction.
Global Transaction:- A global transaction means, all operations in a transaction are executed
against multiple database.
For Example; If transfer money from first account to second account belongs to different banks
then the transaction is a global transaction.
Note: Jdbc technology performs only local transactions. For global transaction in java we need
either EJB or spring framework.
Note: The operation in a transaction management may be executed on same table or different
table but database should be same.
Note: In transaction management DDL(create ,alter drop) commands are not allowed.
52 | P a g e
Ratanit Adv.Java Mr. Ratan
Java.sql.SavePoint :-
To manage the transactions in JDBC we have to use SavePoint interface. And it is introduced in
JDBC3.0 verison.
By default when we run the query in database the database is permanently updated because the
database auto commit mode is by default true.
To perform the transaction we have to set auto commit is false then it is possible to manage the
transaction by using commit and rollback operations.
To change connection’s auto commit mode we have to use the following method from
Connection.
public void setAutoCommit(boolean b)throws SQLException
If b==true then the connection will be in auto commit mode else the connection will be in non-
auto commit mode.
Example : con.setAutoCommit(false);
If we change connection’s auto commit mode then we have to perform either commit or rollback
operations to complete the transactions.
To perform commit and roll back operations we have to use the following methods from Connection.
public void commit()throws SQLException
public void rollback()throws SQLException
Note: In case of connection’s non-auto commit mode, when we submit SQL query to the connection then
connection will send that SQL query to Database Engine and make the Database Engine to execute that
SQL query and store the results on to the database table temporarily. In this case, Database Engine may
wait for commit or rollback signal from client application to complete the transactions.
Note:Multiple savepoints can exist within a single transaction. Savepoints are useful for implementing
complex error recovery in database.
It is possible to place multiple savepoints in single source file but it is possible to rollback up to
only one savepoint at a time.
53 | P a g e
Ratanit Adv.Java Mr. Ratan
Example:-
To do transaction management in Jdbc, we need to follow the below steps.
Step 1: Disable auto commit mode of Jdbc
Step 2: Put all operation of a transaction in try block.
Step 3: If all operation are done successfully then commit in try block, otherwise rollback in catch block.
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
class TestDb
{ public static void main(String[] args) throws ClassNotFoundException, SQLException
{ Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con
=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("connection created successfully…….");
Statement stmt=con.createStatement();
con.setAutoCommit(false);
try
{ stmt.executeUpdate("insert into emp values(111,'ratan',10000)");
stmt.executeUpdate("update emp set esal=esal+100 where esal>1000");
stmt.executeUpdate("delete from emp where eid=222");
con.commit();
System.out.println("Transaction is success");
}//end of try
catch (Exception e)
{ con.rollback();
System.out.println("Trasaction is failed");
}
con.close();
System.out.println("connection is closed");
} //end of main
} //end of class
54 | P a g e
Ratanit Adv.Java Mr. Ratan
Example :
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
class TestDb
{ public static void main(String[] args) throws ClassNotFoundException, SQLException
{
Savepoint savepoint = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con
=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("driver is loaded");
Statement stmt=con.createStatement();
con.setAutoCommit(false);
try
{ stmt.executeUpdate("insert into emp values(555,'ratan',10000)");
savepoint = con.setSavepoint();
stmt.executeUpdate("update emp set esal=esal+100 where esal>1000");
stmt.executeUpdate("delete from emp where eid===111");//error
con.commit();
System.out.println("Transaction is success");
}//end of try
catch (Exception e)
{ con.rollback(savepoint);
System.out.println("Trasaction is failed");
}
con.close();
System.out.println("connection is closed");
} //end of main
} //end of class
55 | P a g e
Ratanit Adv.Java Mr. Ratan
Example-1 :-
package com.dss;
import java.sql.SQLException;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class TestDb {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
rowSet.setUsername("system");
rowSet.setPassword("ratan");
56 | P a g e
Ratanit Adv.Java Mr. Ratan
Example -2:
package com.dss;
import java.sql.SQLException;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class TestDb {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
rowSet.setUsername("system");
rowSet.setPassword("ratan");
Example 3:-
rowSet.setCommand("select * from emp");
rowSet.execute();
System.out.println("EmpId \t EmpName \t EmpSal");
while (rowSet.next()) {
System.out.println(rowSet.getInt(1) + "\t" + rowSet.getString(2) + "\t" + rowSet.getDouble(3));
}
Output:-
EmpId EmpName EmpSal
111 ratan 20000.0
222 anu 40000.0
333 dileep 50000.0
57 | P a g e
Ratanit Adv.Java Mr. Ratan
Java.sql.CallableStatement:
Stored procedures:-
1. Stored procedures are pre compiled queries available at database side.
2. Procedure will take the input & produce the output.
3. Stored procedure return value is optional.
4. Procedure can have both input and output parameters(IN & OUT)
5. Procedure is able to call functions.
Syntax:-
create or replace procedure procedure_name([param-list])
as
------------ Global declarations
BEGIN
------------ Database logic
END procedure_name;
/
(press enter to save and compile the procedure)
Functions:-
1. Functions are pre compiled queries available at database side.
2. Functions will take the input & produce the output.
3. Function must return the value.
4. Function can have only IN(input) parameter.
5. From the functions we are unable to call procedures.
58 | P a g e
Ratanit Adv.Java Mr. Ratan
Syntax:-
create or replace function function_name([param-list]) return data_type
as
------------ Global declarations
BEGIN
------------ Database logic
return value;
END function_name;
IN :- it is a input value to procedure or function call & set the input value by using setXXX().
OUT : - it is a output value of procedure or function & get the output value by using getXXX().
INOUT :- it is parameter of both input and output values set the input value by using setXXX() and get
the value by using getXXX().
59 | P a g e
Ratanit Adv.Java Mr. Ratan
Step 1: Create the callable statement object by using prepareCall() method of Connection interface.
When JVM encounters the above instruction JVM will pick up procedure call and send to
Database Engine, where Database Engine will parse the procedure call and prepare a query
plan with the positional parameters, as a result CallableStatement object will be created at
Java application.
Step 2:- If we have IN type parameters in CallableStatement object then set values to IN type
parameters.
public void setXxx(int param_position, xxx value)
Step 3:- If we have OUT type parameter in CallableStatement object then we have to register
OUT type parameter with a particular data type.
Where data_type may be the constants from Types class : BYTE, SHORT, INTEGER,FLOAT ...etc
ex: callableStatement.registerOutParameter(2,Types.FLOAT);
Step 4:- Make Database Engine to pick up the values from Query plan and to execute the
respective procedure or function.
public void execute()throws SQLException
ex : callableStatement.executeUpdate();
Step 5:- Get the values from OUT type parameters available in CallableStatement object.
After executing the respective procedure or function the respective values will be stored
in OUT type parameters in CallableStatement object from stored procedure or functions.
Toaccess the OUT type parameter values we have to use the following method.
ex: callableStatement.getFloat(2)
60 | P a g e
Ratanit Adv.Java Mr. Ratan
abc.properties
username=system
password=ratan
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
JDBC code to create the connection: (Reading data from properties file)
package com.dss;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
Class.forName(properties.getProperty("driver"));
connection = DriverManager.getConnection(properties.getProperty("url"),
properties.getProperty("username"),properties.getProperty("password"));
}
catch (ClassNotFoundException|SQLException | IOException e) {
e.printStackTrace();
}
return connection;
}
}
61 | P a g e
Ratanit Adv.Java Mr. Ratan
Example -1
Procedure Creation :
create or replace procedure getSal(id IN number, sal OUT number)
as
BEGIN
select esal into sal from emp where eid=id;
END getSal;
/
package com.dss;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
callableStatement.close();
connection.close();
System.out.println("Connection closed successfully....");
}
}
62 | P a g e
Ratanit Adv.Java Mr. Ratan
Example -2:
Procedure Creation :
package com.dss;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("connection created successfully.....");
callableStatement.setInt(1, 111);
callableStatement.setString(2, "ratan");
callableStatement.setInt(3, 50000);
callableStatement.executeUpdate();
System.out.println("operations are completed");
connection.close();
System.out.println("connection is closed");
}
}
63 | P a g e
Ratanit Adv.Java Mr. Ratan
Example 3:
procedure creation
create or replace procedure getDetails(id IN number, o1 OUT number,o2 OUT varchar,o3 OUT number)
as
BEGIN
select eid,ename,esal into o1,o2,o3 from emp where eid=id;
END getDetails;
/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
callableStatement.setInt(1, 999);
callableStatement.registerOutParameter(2, Types.INTEGER);
callableStatement.registerOutParameter(3, Types.VARCHAR);
callableStatement.registerOutParameter(4,Types.FLOAT);
callableStatement.executeUpdate();
System.out.println(callableStatement.getInt(2));
System.out.println(callableStatement.getString(3));
System.out.println(callableStatement.getFloat(4));
connection.close();
System.out.println("connection is closed");
}
}
64 | P a g e
Ratanit Adv.Java Mr. Ratan
Example 4:
Procedure Creation :
create or replace procedure getEmps(emps OUT SYS_REFCURSOR, sal IN number)
as
BEGIN
open emps for
select * from emp where esal>sal;
END getEmps;
/
package com.dss;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
CallableStatement callableStatement =
connection.prepareCall("{call getEmps(?,?)}");
callableStatement.setDouble(2, 10000);
callableStatement.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
callableStatement.execute();
ResultSet rs=(ResultSet)callableStatement.getObject(1);
System.out.println("EID ENAME ESAL");
System.out.println("--------------------");
while (rs.next())
{ System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3));
}
callableStatement.close();
connection.close();
System.out.println("Connection closed successfully....");
}
}
65 | P a g e
Ratanit Adv.Java Mr. Ratan
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
callableStatement.setInt(1, 111);
callableStatement.setString(2, "ratan");
callableStatement.setInt(3, 1000);
callableStatement.addBatch();
callableStatement.setInt(1, 222);
callableStatement.setString(2, "anu");
callableStatement.setInt(3, 2000);
callableStatement.addBatch();
callableStatement.executeBatch();
System.out.println("operations are completed");
connection.close();
System.out.println("connection is closed");
}
}
66 | P a g e
Ratanit Adv.Java Mr. Ratan
Example -5
Execution of functions:
create or replace function getAvg(id1 IN number, id2 IN number) return number
as
sal1 number;
sal2 number;
BEGIN
select esal into sal1 from emp where eid=id1;
select esal into sal2 from emp where eid=id2;
return (sal1+sal2)/2;
END getAvg;
/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
callableStatement.executeUpdate();
System.out.println("Result="+callableStatement.getFloat(1));
System.out.println("operations are completed");
connection.close();
System.out.println("connection is closed");
}
}
67 | P a g e
Ratanit Adv.Java Mr. Ratan
Example-6:
Function creation :
create or replace function getEmployees(sal IN number) return SYS_REFCURSOR
as
Employees SYS_REFCURSOR;
BEGIN
open Employees for
select * from emp where esal>sal;
return Employees;
END getEmployees;
/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
callableStatement.execute();
ResultSet set=(ResultSet) callableStatement.getObject(1);
System.out.println("EID ENAME ESAL");
System.out.println("--------------------");
while (set.next())
{ System.out.println(set.getInt(1)+" "+set.getString(2)+" "+set.getFloat(3));
}
connection.close();
System.out.println("connection is closed");
}
}
68 | P a g e
Ratanit Adv.Java Mr. Ratan
Batch Updations :
If the number of round trips is increased between an application and database, then it will
reduce the performance of an application. To overcome these problems we use Batch Processing.
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("connection created successfully..........");
Scanner scanner = new Scanner(System.in);
statement.executeUpdate(q1);
statement.executeUpdate(q2);
statement.executeUpdate(q3);
statement.executeUpdate(q4);
statement.executeUpdate(q5);
69 | P a g e
Ratanit Adv.Java Mr. Ratan
Example :-
If the number of round trips is increased between an application and database, then it will reduce the
performance of an application. To overcome these problems we use Batch Processing.
In above context if the number of queries are increased number of network round trips are increased
it decreases performance of the application.
To overcome above limitation use batch updation concept.
In batch updating take the all the queries into single unit like batch by using addBAtch() method.
public abstract void addBatch(java.lang.String) throws java.sql.SQLException;
Execute the batch by using executeBatch() method of Statement interface,
public abstract int[] executeBatch() throws java.sql.SQLException;
when we execute the query by using executeBatch() at a time the batch is send to database side
then database engine will execute all queries at a time and it will send the result to jdbc application in
the form of int[] contains all the results.
Note: If we include selection group SQL query in a batch then JVM will raise an Exception like
ava.sql.BatchUpdateException: invalid batch command: invalid SELECT batch command.
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDb {
public static void main(String[] args) throws ClassNotFoundException, SQLException,
InterruptedException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");
System.out.println("connection created successfully..........");
70 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
PreparedStatement preparedStatement =
connection.prepareStatement("update emp set ename=? where eid=?");
preparedStatement.setString(1, "Chitanya");
preparedStatement.setInt(2, 999);
preparedStatement.addBatch();
preparedStatement.setString(1, "Nalanda");
preparedStatement.setInt(2, 888);
preparedStatement.addBatch();
int[] a = preparedStatement.executeBatch();
for(int aa:a)
{ System.out.println(aa);
}
connection.close();
System.out.println("connection is closed");
}
}
71 | P a g e
Ratanit Adv.Java Mr. Ratan
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
callableStatement.setInt(1, 111);
callableStatement.setString(2, "ratan");
callableStatement.setInt(3, 1000);
callableStatement.addBatch();
callableStatement.setInt(1, 222);
callableStatement.setString(2, "anu");
callableStatement.setInt(3, 2000);
callableStatement.addBatch();
callableStatement.executeBatch();
System.out.println("operations are completed");
connection.close();
System.out.println("connection is closed");
}
}
72 | P a g e
Ratanit Adv.Java Mr. Ratan
Connection Pooling:-
The connection pool mechanism used to establish the pool of connections before client make the
request.
The connection pool contains logical connection.
The connections are retrieved from the pool use the connection finally return back to the pool.
Connection pooling means that connections are reused rather than created each time a
connection is requested.
The advantages of connection pooling is improves the performance.
Javax.sql.CommonDataSource(jdk1.6)
Physical connection :-
These type of connections are established either using the driverManager or DataSource.
The connection established directly to database when the client is requested & it is destroyed
when the operations are completed.
Connection.close() destroyed the connection.
Logical connection:-
Logical or pooled connections those connection objects are created & maintained by pool
manager.
When you send the request to connection pool just it will give the logical connection if the
connections are available.
If the connections are reached to maximum limit the request is queued.
Once the connection use is completed then it is return back to pool. But not destroyed or
garbage collected.
The connection objects destruction & maintained by pool manager.
Connection.close() method return the connection to pool.
Javax.sql.DataSource:-
1. For local transaction.
2. Must be implemented by Third-Party CP vendor such as DBCP, C3P0, Proxool, etc
a. Java.sql.Connectionds.getConnection(); //Gets Logical connection from CP.
3. con.close(); //Returns logical connection back to CP.
Javax.sql.XADataSource:-
1. For Distributed Transactions
2. Must be implemented by Third-Party CP vendor.
3. Javax.sql.XAConnection ds.getXAConnection(); //Gets logical connection from cp
4. con.close(); //Returns logical connection back to CP.
Javax.sql.ConnectionPoolDataSource:-
1. Must be implemented by JDBC Driver Vendor such as Oracle, MSSQL, MYSQL, etc.
2. Javax.sql.PooledConnection cpds.getPooledConnection();
//Establish Physical connections with DB.
73 | P a g e
Ratanit Adv.Java Mr. Ratan
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
74 | P a g e
Ratanit Adv.Java Mr. Ratan
If we want to implement Connection pooling in Jdbc application we have to use the following steps.
75 | P a g e
Ratanit Adv.Java Mr. Ratan
Example:-
import java.sql.*;
import javax.sql.*;
import oracle.jdbc.pool.*;
public class ConnectionPoolDemo
{ public static void main(String[] args) throws Exception
{ OracleConnectionPoolDataSource ds=new OracleConnectionPoolDataSource();
ds.setURL("jdbc:oracle:thin:@localhost:1521:xe");
ds.setUser("system");
ds.setPassword("ratan");
PooledConnection pc=ds.getPooledConnection();
Connection con=pc.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp");
System.out.println("EID ENAME ESAL");
System.out.println("------------------------------");
while (rs.next())
{ System.out.println(rs.getInt(1)+" "+rs.getString(2)+""+rs.getFloat(3));
}
}
}
76 | P a g e
Ratanit Adv.Java Mr. Ratan
Note:In java forward slash (/) allowed but not backword slash at time of writing the path.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
pst.setString(1,"ratan");
pst.setBinaryStream(2,fis,(int)f.length());
pst.executeUpdate();
System.out.println("Image inserted Successfully");
connection.close();
}
}
77 | P a g e
Ratanit Adv.Java Mr. Ratan
Example :-
package com.dss;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
pstmt.setString(1,"ratan");
// read the data from database
ResultSet rs=pstmt.executeQuery();
rs.next();
InputStream is=rs.getBinaryStream(1);
rs.close();
//writing image to hard disk
FileOutputStream fos=new FileOutputStream("f:/img001.gif");
int k;
while((k=is.read())!=-1)
{ fos.write(k);
}
System.out.println("picture is ready open F:drive");
fos.close();
connection.close();
}
}
78 | P a g e
Ratanit Adv.Java Mr. Ratan
Creation of table :
Create table ftable(id number,name clob);
Example :
package com.dss;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
preparedStatement.executeUpdate();
preparedStatement.close();
connection.close();
System.out.println("connection closed successfully.....");
}
}
79 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
pstmt.setInt(1,111);
ResultSet rs=pstmt.executeQuery();
rs.next();
Reader is=rs.getCharacterStream(1);
rs.close();
FileWriter fw=new FileWriter("f:/abc.txt");
int k;
while((k=is.read())!=-1)
{ fw.write(k);
}
System.out.println("file is ready to open F:drive");
fw.close();
connection.close();
System.out.println("connection closed successfully.....");
}
}
80 | P a g e
Ratanit Adv.Java Mr. Ratan
1. What is JDBC?
2. What is the present & initial version of java?
3. What is the difference between JDBC & ODBC?
4. What are the layers in web application?
5. What do you mean by deployment?
6. What do you mean by client & server?
7. What are the client side technologies & server side technologies?
8. What is the difference between technology & framework?
9. What do you mean by persistence logic?
10. What is the JDBC driver?
11. JDBC applications are standalone applications or web application?
12. What are the steps to design first application?
13. When we will get SQLException?
14. SQLException is checked or unchecked exception?
15. How many ways are there to handle checked exception?
16. What do you mean by factory method?
17. What is the difference instance method & static method?
18. When we will use extends & implements ?
19. How to take the input from the keyboard?
20. What is the difference between try-catch blocks and throws keyword?
21. How many drivers are available explain?
22. How to load the driver class into memory?
23. How to register driver into DriverManager service?
24. What do you mean by DriverManager service?
25. How to get Connection?
26. What are the key interfaces of JDBC?
27. What is the type-1 driver class-name & url pattern?
28. How to load the driver?
29. What is the purpose of Statement object?
30. What is the difference between DDL & DML & TCL?
31. Who will execute the database queries?
32. Explain stored procedures and functions in oracle?
33. What is the difference between class-path & bud path?
34. What is the logical name of the database and is it possible to change the logical name or not?
35. Explain about IN OUT INOUT parameters?
36. For every query execution 4-steps are performed what are those?
37. What is the purpose of the PreparedStatement?
38. What is the difference between Statement & PreparedStatement?
39. How to store the data coming from database?
40. What is the purpose of database?
41. What is the jar file of Oracle driver implementation?
42. What is the jar file of MySql driver implementation?
43. What is the oracle driver class-name & url pattern?
44. What is the mysql driver class-name & url pattern?
45. What is the difference between class-path & build path?
46. What is the purpose of DSN?
47. How to set the DSN name?
48. What are the statements present in JDBC?
81 | P a g e
Ratanit Adv.Java Mr. Ratan
82 | P a g e
Ratanit Adv.Java Mr. Ratan
83 | P a g e
Ratanit Adv.Java Mr. Ratan
84 | P a g e
Ratanit Adv.Java Mr. Ratan
Servlets
Servlet is a part of the J2EE & these are executed by Servlet container (web container).
The present version of the servlet is Servlet 4.0 introduced in 2017 may compatable with jdk8.
The servlets predefined support in the form of fallowing packages.
o javax.servlet
o javax.servlet.http
o javax.servlet.annotation
Servlet Versions History:
85 | P a g e
Ratanit Adv.Java Mr. Ratan
86 | P a g e
Ratanit Adv.Java Mr. Ratan
87 | P a g e
Ratanit Adv.Java Mr. Ratan
When we develop the application by using technology, the code is duplicated & length increased
but when we develop the application by using framework it reduce the code duplication & length
of the code because framework having more predefined support.
Web-applications
Developed by using j2ee(servlets & jsp) technology : structs JSF framework
No-main method contains life cycle methods(init() service() destroy() ) called by server
Used extension .war
Enterprise applications
Developed by using EJB technology & spring frame work
Used extension .ear
Distributed applications
Developed by using RMI , web-services v, Micro services
Used extension .aar application archive file
Mobile applications
Developed by using android ,IOS
Different types of mobile apps
Native apps: Installed & doesn’t required internet Conn to run : candy crush
Hybrid apps : installed & required internet connection to run : facebook
Web apps : run through web browser
Used extension .apkandroid application package
88 | P a g e
Ratanit Adv.Java Mr. Ratan
Web applications:-
In above diagram the web components are either Java servlets, JSP pages..etc
The six steps are listed below.
1. Client sends the Http request to the web server.
2. The HttpServletRequest object is delivered to the web component.
3. The web components are interacting with database to generate dynamic content.
4. The web components are interacting with java beans to generate dynamic content.
5. The web componenet generate the response in HttpServletResponse object.
6. The web server converts the HttpServletResponse into HTTP response and returns it to the client.
Notice that Java Servlet technology is the foundation of all the web application technologies.
89 | P a g e
Ratanit Adv.Java Mr. Ratan
Container:-
90 | P a g e
Ratanit Adv.Java Mr. Ratan
Web server:
Web server contains web container it support web application
Web container = servlet container + jsp engine
Servlet container is also known as : CATALINA , servlet engine
Jsp engine is also known as : jasper
Ex: jetty
Application Server:
Application server contains both web container & EJB container support both web-
applications & EJB applications
Ex: glassfish, web logic , tomcat ..etc
91 | P a g e
Ratanit Adv.Java Mr. Ratan
Tomcat installation:
Step 1: download the tomcat latest version
92 | P a g e
Ratanit Adv.Java Mr. Ratan
Protocols:
There are two types of protocols
1. Transport protocol : transport purpose : Http , Https ,FTP
2. Messaging protocol : talking about data : SOAP
There are seven Http request types but commonly used request types are get & post.
93 | P a g e
Ratanit Adv.Java Mr. Ratan
When the server is sending response to client browser first Http protocol will take that response
the it will prepare response format contains header & body fields.
The header filed contains response message headers.
The body field contains actual response.
Request Format:
Response Format:
94 | P a g e
Ratanit Adv.Java Mr. Ratan
Public area:
The area which is in outside of WEB-INF folder and inside the application folder is treated as
public area. If we deploy any resource under public area then client is able to access that resource by
using its name directly.
Private area:
In web application directory structure, WEB-INF folder and its internal is treated as private area.
If we deploy any resource under private area then client is unable to access that resource by using its
name directly. So access the private area elements by using url pattern specified in web.xml
95 | P a g e
Ratanit Adv.Java Mr. Ratan
Form tag method attribute <form method=”get”> used to represent which type of request we
are sending from client browser like get,post,put….etc
Form tag action attribute <form action=”url”> used to represent url pattern of the particular
servlet used to provide the mapping between form page & servlet.
At server side to read the form page data use logical name of the text filed name="uname".
96 | P a g e
Ratanit Adv.Java Mr. Ratan
Description <Description>
97 | P a g e
Ratanit Adv.Java Mr. Ratan
web.xml:
<web-app>
<servlet>
<servlet-name>logical_name</servlet-name>
<servlet-class>fully qualified name of servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logical_name</servlet-name>
<url-pattern>urlpattern_name</url-pattern>
</servlet-mapping>
</web-app>
ex:
<web-app>
<servlet>
<servlet-name>aaa</servlet-name>
<servlet-class>com.dss.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>aaa</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Step 4: Start the Server & access the web application by using url.
Open web browser and type the complete URL on address bar.
http://localhost:8888/app1/firstservlet
98 | P a g e
Ratanit Adv.Java Mr. Ratan
99 | P a g e
Ratanit Adv.Java Mr. Ratan
The servlet interface contains 5-methods , but three are life cycle methods
1. Init()
2. Service()
3. Destroy()
100 | P a g e
Ratanit Adv.Java Mr. Ratan
Give the project name & Select the servlet version create the project:
101 | P a g e
Ratanit Adv.Java Mr. Ratan
Creating servlet:
102 | P a g e
Ratanit Adv.Java Mr. Ratan
Approach 1:- Take user defined class which implements Servlet Interface
MyServlet.java:
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FirstServlet implements Servlet {
Web.xml:-
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class> com.dss.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
103 | P a g e
Ratanit Adv.Java Mr. Ratan
Observation:
I above approach the developer must override 5-methods if required or not. But to write the
logics of servlets we are using only service() method.
Observation:
When we send the request to user defined servlet class the container will create the object of
servlet in this process it uses default constructor.
Inside the class if we are declaring argument constructor while instantiation the container will
generate exception
public class FirstServlet implements Servlet {
public FirstServlet(int a) {
}
}
javax.servlet.ServletException: Error instantiating servlet class [com.dss.FirstServlet]
Observation:
When we send the first request to Servlet the servlet initialization ( init() ) done only once.
When we send second request directly it will dorequest processing (service() )
Based on above two pointes we can decide the response time of both servlets is differing.
To give the same response time to every request performs servlet initialization during server startup.
To perform servlet initialization during server startup use <load-on-startup> configuration in web.xml
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.dss.FirstServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<load-on-startup> is taking positive number it represents priority, if we are passing other than
positive number the load-on-startup configuration ignored.
104 | P a g e
Ratanit Adv.Java Mr. Ratan
MyServlet.java:-
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
105 | P a g e
Ratanit Adv.Java Mr. Ratan
106 | P a g e
Ratanit Adv.Java Mr. Ratan
107 | P a g e
Ratanit Adv.Java Mr. Ratan
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Ht1tpServletResponse;
Case : doPost() : To specify the post request use form tag method attribute <form method=”post”>
form.html:
<html>
<body>
<form method="post" action="./HttpServletDemo">
Click here to generate post request: <input type="submit" value="click">
</form>
</body>
</html>
108 | P a g e
Ratanit Adv.Java Mr. Ratan
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
Note: in this approach the particular url pattern belongs to particular servlet.
Case 1: Case 2:
<servlet-mapping> <servlet-mapping>
<servlet-name>FirstServlet</servlet-name> <servlet-name>FirstServlet</servlet-name>
<url-pattern>/abc/*</url-pattern> <url-pattern>/abc/xyz/*</url-pattern>
</servlet-mapping> </servlet-mapping>
ex: ex:
http://localhost:9999/ServletApp1/abc/xyz http://localhost:9999/ServletApp1/abc/xyz
http://localhost:9999/ServletApp1/xyz/abc http://localhost:9999/ServletApp1/xyz/abc
http://localhost:9999/ServletApp1/abc/xyz/123 http://localhost:9999/ServletApp1/abc/xyz/abc
Note: Multiple requested url patterns are trapped by same servlet with specific suffix(directory name)
use this approach.
Note: All the requested url patters are trapped by single servlet use this approach.
109 | P a g e
Ratanit Adv.Java Mr. Ratan
ServletRequest<<interface>>
For every request, the Servlet container creates ServletRequest object.
It contains complete information about HTTP Request text message.
Methods:
a) getParameter(String name)
b) Enumeration getParameterNames()
c) getContentLength()
d) getContentType() : (MIME types)
e) getInputStream()
f) getLocales() : (en_US)
g) getProtocol() : http
h) getScheme() : (http/1.1)
i) getServerName() : (localhost)
j) getServerPort() : (9090)
ServletResponse<<interface>>
The Servlet container creates ServletResponse object. It is used to send HTTP Response message
to web browser.
Methods:
a) getOutputStream() : For sending binary data
b) getWriter() : For sending character data
c) setContentType(String type) : Specifying MIME type of the response.
When we start the server the main job of container is to recognize each and every web application
and to prepare ServletContext object to each and every web application.
While recognizing web application container will recognize web.xml file under WEB-INF folder then
perform loading, parsing and reading the content of web.xml file.
While reading the content of web.xml file, if container identifies any context data in web.xml file then
container will store context data in ServletContext object at the time of creation.
After the server startup when we send a request from client to server protocol will pick
up the request tehn perform the following actions.
1. Protocol will establish virtual socket connection between client and server as part of
the server IP address and port number which we specified in the URL.
2. Protocol will prepare a request format having request header part and body part,
where header part will maintain request headers and body part will maintain request
parameters provided by the user.
3. After getting the request format protocol will carry request format to the main
server.
110 | P a g e
Ratanit Adv.Java Mr. Ratan
Upon receiving the request from protocol main server will check whether the request data is
in well-formed format or not, if it is in well-formed then the main server will bypass request
to container.
Upon receiving the request from main server container will pick up application name and
resource name from request and check whether the resource is for any html page or Jsp
page or an URL pattern for a servlet.
If the resource name is any html page or Jsp page then container will pick up them
application folder and send them as a response to client.
If the resource name is an URL pattern for a particular servlet available under classes
folder then container will go to web.xml file identifies the respective servlet class name on
the basis of the URL pattern.
After identifying the servlet class name from web,xml file container will recognize the
respective servlet .class file under classes folder then perform the following actions.
Here container will load the respective servlet class byte code to the memory.
Step 2: Servlet Instantiation:Here container will create a object for the loaded servlet.
Here container will create ServletConfig object and access init(_) method by passing
ServletConfig object reference.
After the servlet initialization container will create a thread to access service(_,_)
method, for this container has to create request and response objects.
When container generated thread reaching to the ending point of service(_,_) method
then container will keep the thread in dead state, with this container will dispatch the
dynamic response to main server from response object, where main server will bypass the
response to the protocol.
When protocol receives the response from main server then protocol will prepare
response format with header part and body part, where header part will manage all the
response headers and body part will manage the actual dynamic response.
111 | P a g e
Ratanit Adv.Java Mr. Ratan
After getting response format protocol will carry that response format to the client.
When the response is reached to the client protocol will terminate the virtual socket
connection between client and server, with this container destroy the request and response
objects.
When container destroy request and response objects then container will go to the
waiting state depends on the container implementation, if container identifies no further
request for the same resource then container will destroy servlet object.
Note: In servlet execution, container will destroy ServletConfig object just before
destroying the servlet object.
After servlet deinstantiation container will eliminate the loaded servlet byte code from
operational memory.
In the above servlet life cycle, all the objects like request, response and ServletConfig
are destroyed before servlet deinstantiation, but still Servlet object is available in memory.
In general ServletContext object will be destroyed at the time of server shut down.
112 | P a g e
Ratanit Adv.Java Mr. Ratan
If we want to design a servlet with this approach then we have to take an user defined class it should
be an implementation class to Servlet interface.
Where the purpose of init(_) method to provide servlets initialization.
Note: In servlets execution, to perform servlets initialization container has to access init(_) method. To
access init(_) method container has to create ServletConfig object.
ServletConfig is an object, it will manage all the configuration details of a particular servlet like logical
name of servlet, initialization parameters and so on.
In servlet, the main purpose of service(_,_) method is to accommodate the complete logic and to
process the request by executing application logic.
Note: In servlet, service(_,_) method is almost all same as main(_) method in normal Java application.
When we send a request from client to server then container will access service(_,_) method
automatically to process the request, where the purpose of getServletConfig() method is to get
ServletConfig object at servlet initialization.
Where getServletInfo() method is used to return generalized description about the present servlet.
Where destroy() method can be used to perform servlet reinstantiation.
To prepare application logic in service(_,_) method we have to use the following conventions.
If we want to access the above servlet then we have to provide the following URL at client browser.
http://localhost:8080/loginapp/login
113 | P a g e
Ratanit Adv.Java Mr. Ratan
Directory structure:-
login.html:
<html>
<head>
<h1><center>Login page</center>
</head>
<body>
<form method="get" action="./LoginServlet">
<pre>
user name<input type="text" name="uname"/>
password<input type="password" name="upwd"/>
<input type="submit" value="login"/>
</pre>
</form>
</body>
</html>
Web.xml:
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.dss.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
114 | P a g e
Ratanit Adv.Java Mr. Ratan
LoginServlet.java:
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
if(uname.equals("durga")&&upwd.equals("ratan"))
{ writer.println("Login Success...."+uname);
}
else
{ writer.println("Login Fail try with valid credentials");
}
}
}
Note : At server side to read the data from client side form page we are using logical name of fields, if logical
name is wrong we will get null value.
115 | P a g e
Ratanit Adv.Java Mr. Ratan
doGet() vs doPost():
Get Request:
1. The default request type is get request.
2. In GET request the user entered information is appended to the URL in a query string.
3. The query string visible in the URL pattern so GET request is able to provide less request.
4. By using GET request we the client is able to send limited amount of data. GET request doesn’t
have body in the request format hence we are able to send the all parameter values in the form
of header part so by using GET request we are able to send limited amount of data(maximum
256 number of characters at a time)
5. In general in web applications GET request can be used to get the information from the server.
Post Request:
1. POST is not default request. To specify the post request use <form method=”post”>.
2. POST request the user entered information is sent as data not appended to URL.
3. POST is send the data client to server hence it is able to provide very good security .
4. POST request contains body part hence we are able to send the large amount of data client to
server by using body part of POST request.
5. In general in web applications POST request can be used to send the data to the server.
116 | P a g e
Ratanit Adv.Java Mr. Ratan
reg.html:
<html>
<head>
<center>Registration</center>
</head>
<body>
<form method="post" action="./Registration">
<pre>
Name <input type="text" name="uname"/>
Password <input type="password" name="upwd"/>
Qualification <input type="checkbox" name="uqual" value="BSC"/>BSC
<input type="checkbox" name="uqual" value="MCA"/>MCA
<input type="checkbox" name="uqual" value="M TECH"/>M TECH
Technologies
<select name="utech" size="3" multiple>
<option value="C">C</option>
<option value="C++">C++</option>
<option value="JAVA">JAVA</option>
</select>
Comments<input type="textarea" name="ucom" rows="5" cols="25"></textarea>
<input type="submit" value="Register"/>
</pre>
</form>
</body>
</html>
Web.xml:-
<web-app>
<display-name>Registration</display-name>
<servlet>
<servlet-name>Registration</servlet-name>
<servlet-class>com.dss.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registration</servlet-name>
<url-pattern>/Registration</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Registration.html</welcome-file>
</welcome-file-list>
</web-app>
117 | P a g e
Ratanit Adv.Java Mr. Ratan
Registration.java:-
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclassRegistrationextends HttpServlet {
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String uname=request.getParameter("uname");
String upwd=request.getParameter("upwd");
String[] uqual=request.getParameterValues("uqual");
String ugen=request.getParameter("ugen");
String[] utech=request.getParameterValues("utech");
String ucom=request.getParameter("ucom");
out.println("<html>");
out.println("<body bgcolor='lightgreen'>");
out.println("<center><b><font size='6'>");
out.println("Name....."+uname);
out.println("<br><br>");
out.println("Password......"+upwd);
out.println("<br><br>");
out.println("Qualification<br><br>");
for(int i=0;i<uqual.length;i++)
{ out.println(uqual[i]);
out.println("<br><br>");
}
out.println("Gender...."+ugen);
out.println("<br><br>");
out.println("Technologies<br><br>");
for(int i=0;i<utech.length;i++)
{ out.println(utech[i]);
out.println("<br><br>");
}
out.println("Comments......"+ucom);
out.println("<br><br>");
out.println("Congratulations....."+uname);
out.println("<br><br>U R Registration Success");
out.println("</font></b></center></body></html>");
}
118 | P a g e
Ratanit Adv.Java Mr. Ratan
LoginPage.html:-
<html>
<head>
<h1><center>login page</center>
</head>
<body>
<form method="get" action="./LoginServlet">
<pre>
user name<input type="text" name="uname"/>
password<input type="password" name="upwd"/>
<input type="submit" value="login"/>
</pre>
</form>
</body>
</html>
Web.xml:
<web-app>
<display-name>App1</display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.dss.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>LoginPage.html</welcome-file>
</welcome-file-list>
119 | P a g e
Ratanit Adv.Java Mr. Ratan
</web-app>
LoginServlet.java:-
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclass LoginServlet extends HttpServlet {
String status;
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer=response.getWriter();
String uname=request.getParameter("uname");
String upwd=request.getParameter("upwd");
writer.println("<html>");
writer.println("<body>");
writer.println("username is"+uname);
writer.println("<br>");
writer.println("user password is"+upwd);
writer.println("</body>");
writer.println("</html>");
120 | P a g e
Ratanit Adv.Java Mr. Ratan
LoginBean.java:-
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
publicclass LoginBean {
static Statement statement;
static
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbc");
Connection
connection=DriverManager.getConnection("jdbc:odbc:ratan","system","manager");
statement=connection.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("connection is created successfully");
}
publicvoid checkLogin(String uname, String upwd) throws SQLException {
String query="insert into eee values('"+uname+"','"+upwd+"')";
statement.executeUpdate(query);
System.out.println("vales are inserted successfully");
}
}
Example :-
public java.lang.String getParameter(java.lang.String name):-
If you want to read only one form field use getParamerter().
Returns the value of a request parameter as a String, or null if the parameter does not exist.
121 | P a g e
Ratanit Adv.Java Mr. Ratan
Used to read the all the values at a time but the condition is all the fields should have the
common name.
Returns an array of String objects containing all of the values the given request parameter has,
or null if the parameter does not exist.
CustomerDetails.html:-
<html>
<body>
<form action="CustomerServlet" method="GET">
<p>First Name: <input type="text" name="firstName" /></p>
<p>Last Name:<input type="text" name="lastName" /></p>
<p>Mobile: <input type="text" name="mobile" /></p>
<p>E-Mail: <input type="text" name="email" /></p>
<p> Enter H.No. <input type="text" name="t1"></p>
<p> Enter Street <input type="text" name="t1"></p>
<p> Enter Area <input type="text" name="t1"></p>
<p><input type="submit" value="Register" /></p>
</form>
</body>
</html>
Web.xml:-
<web-app>
<welcome-file-list>
<welcome-file>CustomerDetails.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>com.dss.CustomerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/CustomerServlet</url-pattern>
</servlet-mapping>
</web-app>
import org.apache.commons.dbcp.BasicDataSource;
122 | P a g e
Ratanit Adv.Java Mr. Ratan
dataSource.setUsername("system");
dataSource.setPassword("ratan");
dataSource.setMaxActive(10);
}
}
Required jars for connection pool :commons-dbcp.jarcommon-pool.jar for third party connection pool.
For oracle Database : ojdbc6.jar or ojdbc14.jar based on oracle version.
For mysql database : mysql-connector.jar
For servlets : servlet-api.jar
Note: in web application place the all jar files in lib folder instead of build path.
CustomerServlet.java:-
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
123 | P a g e
Ratanit Adv.Java Mr. Ratan
for(String ss : s)
{ sb.append(ss+",");
}
String addr = new String(sb);
try {
Connection connection = TestDb2.dataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("insert into customer values(?,?,?,?,?)");
preparedStatement.setString(1, firstname);
preparedStatement.setString(2, lastname);
preparedStatement.setString(3, email);
preparedStatement.setString(4, mobile);
preparedStatement.setString(5, addr);
int a = preparedStatement.executeUpdate();
124 | P a g e
Ratanit Adv.Java Mr. Ratan
Servlet Communications:-
Servlet Communication
Include forward
Req1
Browser 1st Servlet
Res1
Redirection
2nd Servlet
welcome.html-
<HTML>
<HEAD>
Request Redirection
</HEAD>
<BODY>
<form method="post" action="hutch">
to send the request:-<input type="submit" value="click me">
</BODY>
</HTML>
Hutch.java:-
125 | P a g e
Ratanit Adv.Java Mr. Ratan
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Hutch extends HttpServlet
{ public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("To Get Services From Hutch Click");
out.println("<a
href='http://localhost:9999/vodaphoneapp/welcome.html'>[email protected]
m</a>");
out.println("</font></b></center></body></html>");
}
}
Web.xml:-
<web-app>
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>h</servlet-name>
<servlet-class>Hutch</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>h</servlet-name>
<url-pattern>/hutch</url-pattern>
</servlet-mapping>
</web-app>
LoginServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
126 | P a g e
Ratanit Adv.Java Mr. Ratan
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
if(uname.equals("sravya")&& upwd.equals("infotech"))
{ /*writer.println("login success");
writer.println("<a href='http://facebook.com'>click the link to redirect req to fb</a>");
*/
/*response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("location","https://www.google.co.in");*/
response.sendRedirect("http://facebook.com");
}
else
{ response.sendError(808,"login fail try once again");
}
}
}
Login.html:-
<html>
<body>
<form action="./LoginServlet">
user name: <input type="text" name="uname"/><br/>
password : <input type="password" name="upwd"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
Web.xml:-
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<servlet>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.sravya.LoginServlet</servlet-class>
127 | P a g e
Ratanit Adv.Java Mr. Ratan
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
RequestDispatcher:-
The requestDispatcher is used to dispatch the request to another resources(html,servlets,jsp) and
it is include the content of another resource.
There are two methods are available in the RequestDispatcher Object
1. Public void Include(ServletRequest request,ServletResponse response)throws
ServeltException,IOException
By using above method we are able to transfer the request from one resource to another
resources like html,servlets,jsp
2. Public void Forward (ServletRequest request,ServletResponse response)throws
ServletException,IOException
By using above method we are able to include the target resource response.
Step 1: get RequestDispatcher object
RequestDispatcher is an object, it will provide very good environment either to include the target
resource response into the present resource response or to forward request from present resource to the
target resource.
To get RequestDispatcher object we will use the following 2 ways.
1. ServletContext
1. getRequestDispatcher(_) method
2. gteNamedDispatcher(_) method
2. ServletRequest
1. getRequestDispatcher(_) method
getRequestDispatcher(_) vs getNamedDispatcher(_):-
Both the methods are used to get the RequestDispatcher object.
To get RequestDispatcher object, if we use getRequestDispatcher(_) method then we should pass
the locator of target resource as parameter.
Note : In case of the servlet, url pattern is treated as locator.
public RequestDispatcher getRequestDispatcher(String path)
To get RequestDispatcher object, if we use getNamedDispatcher(_) method then we have to pass
logical name of target resource as parameter.
Note : In case of the servlet, logical name is a name specified along with <servlet-name> tag in
web.xml file.
public RequestDispatcher getNamedDispatcher(String path)
What is the difference between getRequestDispatcher(_) method ServletContext and ServletRequest?
Both the methods can be used to get the RequestDispatcher object.
To get RequestDispatcher object, if we use getRequestDispatcher(_) method from ServletContext then
we must pass the relative path of target resource.
To get RequestDispatcher object, if we use getRequestDispatcher(_) method from ServletRequest then
we have to pass either relative path or absolute path of target resource.
Note: In general, relative path should prefix with forward slash(“/”) and absolute path should not prefix
with forward slash(“/”).
128 | P a g e
Ratanit Adv.Java Mr. Ratan
Login.html:-
<html>
<body bgcolor='red'>
<form action="./login" method="post">
Name:<input type="text" name="uname"/><br/>
Password:<input type="password" name="upwd"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
Web.xml:-
<web-app>
<servlet>
<servlet-name>sss</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sss</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/success</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Servlet1.java:-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
129 | P a g e
Ratanit Adv.Java Mr. Ratan
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String upwd=request.getParameter("upwd");
if(upwd.equals("ratan")){
RequestDispatcher rd=request.getRequestDispatcher("success");
rd.forward(request, response);
}
else{
writer.print("oops ! Sorry username or password error! try once again !");
RequestDispatcher rd=request.getRequestDispatcher("login.html");
rd.include(request, response);
}
}
}
Servlet2.java:-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.println("Welcome to ratansoft world : "+n);
out.println("ratan sir welcomes u : "+n);
}
}
ServletContext vs ServletConfig :-
Q: What are the differences between ServletConfig and ServletContext?
1. ServletConfig is an object, it will manage all the configuration details of a particular servlet, where the
configuration details include logical name of the servlet, initialization parameters and so on.
ServletContext is an object, it will manage all the context details of a particular web application, where
the context details include logical name of web application and context parameters and so on.
130 | P a g e
Ratanit Adv.Java Mr. Ratan
ServletContext is an object, it will provide the complete view of particular web application.
3. ServletConfig object will be prepared by the container immediately after servlet instantiation and just
before calling init(_) method in servlet initialization.
ServletContext object will be prepared by the container the moment when we start the server i.e. the
time when we deploy the web application.
4. ServletConfig object will be destroyed by the container just before servlet deinstaniation.
ServletContext object will be destroyed by the container when we shutdown the server i.e. the time
when we undeploy the web application.
5. Due to the above reasons, the life of ServletConfig object is almost all the life of the respective servlet
object.
The life of ServletContext object is almost all the life of the respective web application.
6. If we declare any data in ServletConfig object then that data will be shared upto respective servlet.
If we declare any data in ServletContext object then that data will be shared to all the no. of resources
which are available in the present web application.
7. Due to the above reason, ServletConfig object will provide less sharability where as ServletContext
object will provide more sharability.
8. In web applications, container will prepare ServletConfig object when it receives the request from
client only except in load-on-startup case.
In web applications, container will prepare ServletContext object irrespective of getting request from
client.
9. In web applications, ServletConfig object will allow only parameters data but ServletContext object
will allow both parameters and attributes data.
10. Due to the above reason, ServletConfig object will allow only Static Inclusion of data where as
ServletContext object will allow both Static Inclusion and Dynamic Inclusion of data.
To get the ServletContext object we have to use the following method from ServletConfig.
public ServletContext getServletContext();
131 | P a g e
Ratanit Adv.Java Mr. Ratan
-------------
</web-app>
To get the logical name of web application from ServletContext object we will use the following
method.
Public String getServletContextName()
Ex: String lname=context.getServletContextName();
If we want to provide context parameters on ServletContext object first we have to declare them in
web.xml file.
Form.html :
<html>
<body>
<a href="/FirstServlet">click here to get FirstServlet data</a>
<a href="/secondServlet">click here to get SecondServlet data</a>
</body>
</html>
Web.xml:-
<web-app>
<display-name>App1</display-name>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>manager</param-value>
</context-param>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.sravya.FirstServlet</servlet-class>
<init-param>
<param-name>aaa</param-name>
<param-value>apple</param-value>
</init-param>
<init-param>
<param-name>bbb</param-name>
<param-value>ratan</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>com.sravya.SecondServlet</servlet-class>
132 | P a g e
Ratanit Adv.Java Mr. Ratan
<init-param>
<param-name>ccc</param-name>
<param-value>orange</param-value>
</init-param>
<init-param>
<param-name>ddd</param-name>
<param-value>anu</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet</url-pattern>
</servlet-mapping>
</web-app>
FirstServlet.java
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
ServletConfig config = this.getServletConfig();
writer.println(config.getInitParameter("aaa"));
writer.println(config.getInitParameter("bbb"));
133 | P a g e
Ratanit Adv.Java Mr. Ratan
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecondServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println(config.getInitParameter("ccc"));
writer.println(config.getInitParameter("ddd"));
Web.xml:-
<web-app>
<display-name>App2</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.sravya.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
134 | P a g e
Ratanit Adv.Java Mr. Ratan
<servlet>
<servlet-name>SuccessServlet</servlet-name>
<servlet-class>com.sravya.SuccessServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SuccessServlet</servlet-name>
<url-pattern>/SuccessServlet</url-pattern>
</servlet-mapping>
</web-app>
LoginServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
if(uname.equals("sravya")&&upwd.equals("infotech"))
{
//RequestDispatcher dispatcher = request.getRequestDispatcher("SuccessServlet");
//dispatcher.forward(request, response);
request.getRequestDispatcher("SuccessServlet").forward(request, response);//project level code
}
else
{ writer.println("!OOPS login failed can u please try again");
//RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");
//dispatcher.include(request, response);
request.getRequestDispatcher("login.html").incude(request, response);//project level code
}
}
}
SuccessServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
135 | P a g e
Ratanit Adv.Java Mr. Ratan
LoginApplet.java:-
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Label;
136 | P a g e
Ratanit Adv.Java Mr. Ratan
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class LoginApplet extends Applet implements ActionListener {
Label l1,l2;
TextField tf1,tf2;
Button b;
String res="";
public void init(){
this.setBackground(Color.pink);
this.setLayout(new FlowLayout());
l1=new Label("User Name");
l2=new Label("Password");
tf1=new TextField(20);
tf2=new TextField(20);
tf2.setEchoChar('*');
b=new Button("Login");
b.addActionListener(this);
this.add(l1); this.add(tf1); this.add(l2); this.add(tf2); this.add(b);
}
public void actionPerformed(ActionEvent ae) {
try{
URL u=new
URL("http://localhost:2011/loginapp1/login?uname="+tf1.getText()+"&upwd="+tf2.getText());
URLConnection uc=u.openConnection();
uc.setDoInput(true);
InputStream is=uc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
res=br.readLine();
repaint();
}catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g){
Font f=new Font("arial", Font.BOLD, 30);
g.setFont(f);
g.drawString("Status :"+res, 50, 250);
}
}
oginApplet.html:-
<applet code="LoginApplet" width="500" height="500"></applet>
137 | P a g e
Ratanit Adv.Java Mr. Ratan
Include:
Forward:
138 | P a g e
Ratanit Adv.Java Mr. Ratan
Filters:-
To write the pre-processing logics & post processing logics we are using filters.
The main objective of the filter is to provide request preprocessing & response post processing.
Filters are mainly used to perform filtering tasks,
o Conversion
o Encryption, decription
o Security
o Input validations
o Data compression …etc
Filter Api :-
To develop the filter example we have to use below interfaces and these interfaces are present in
javax.servlet package
a. Filter <interface>
b. FilterConfig <interface>
c. FilterChain <interface>
Filter creation :-
Our normal java class will become Filter class when we implements Filter interface.The Filter
contains 3-methods hence in implementation class must override three methods.
Filter implementation:-
public interface Filter
{ public abstract void init(FilterConfig filterconfig) throws ServletException;
public abstract void doFilter(ServletRequest servletrequest, ServletResponse
servletresponse, FilterChain filterchain) throws IOException, ServletException;
public abstract void destroy();
}
Example :
class MyFilter implements Filter
{ //logics here [must override three methods]
}
Init() :- this method invoked only once it is used to initialize the Filter
doFilter() :-
it is invoked every time when user send the request to resource. And it is used to write
the logics of the Filter by using doFilter() method.
destroy() :- called when the filter is has been taken out of the service.
139 | P a g e
Ratanit Adv.Java Mr. Ratan
140 | P a g e
Ratanit Adv.Java Mr. Ratan
While executing a particular Filter in web applications, if we satisfy all the Filter
constraints then we need to bypass the request from present Filter to the next Filter web
resource, for this we need to use the following method from FilterChain.
While executing a particular web application, when container identify a particular Filter to
execute then container will execute that Filter by following the following Filter life cycle.
Filter Loading
at the time of
Filter Instantiation
Server start up
Filter Initialization
Filter Deinstantiation
atthe time of server shutdown
In web applications, by default all the Filters are auto-loaded, auto-instantiated, auto-
initialized at the time of server start up. So that Filters should not require load-on-startup
configuration in web.xml file.
141 | P a g e
Ratanit Adv.Java Mr. Ratan
To configure a Filter in web.xml file we have to use the following xml tags.
<web-app>
<filter>
<filter-name>logical_name</filter-name>
<filter-class>Fully Qualified name of Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>logical_name</filter-name>
<url-pattern>pattern_name</url-pattern>
or
<servlet-name>logical name of servlet</servlet-name>
</filter-mapping>
--------
</web-app>
If we want to provide mapping between a Filter and Servlet then we have to provide the
same url-pattern for both Filter and Servlet or provide the respective servlet logical name
along with <servlet-name> tag in place of <url-pattern> tag under <filter-mapping>.
In web applications, it is possible to use a single Filter for multiple number of web
resources.
In web applications, it is possible to provide multiple number of Filters for a single web
resource, in this case container will execute all the Filters as per the order in which we
provided <filter-mapping> tags in web.xml file.
142 | P a g e
Ratanit Adv.Java Mr. Ratan
Client
Qual:
Desig:
Next
Client
Name:
Age:
143 | P a g e
Ratanit Adv.Java Mr. Ratan
Form.html:-
<html>
<body>
<form action="./SuccessServlet">
User name : <input type="text" name="uname"/><br>
user age : <input type="text" name="uage"/><br>
user address : <input type="text" name="uaddr"/><br>
<input type="submit" value="registration"/>
</form>
</body>
</html>
Web.xml:-
<web-app>
<display-name>App3</display-name>
<welcome-file-list>
<welcome-file>form.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Filter1</filter-name>
<filter-class>com.sravya.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/SuccessServlet</url-pattern>
</filter-mapping>
<filter>
<filter-name>Filter2</filter-name>
<filter-class>com.sravya.Filter2</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter2</filter-name>
<url-pattern>/SuccessServlet</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>SuccessServlet</servlet-name>
<servlet-class>com.sravya.SuccessServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SuccessServlet</servlet-name>
<url-pattern>/SuccessServlet</url-pattern>
</servlet-mapping>
</web-app>
144 | P a g e
Ratanit Adv.Java Mr. Ratan
Filter1.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Filter1 implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
IOException, ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
int age = Integer.parseInt(request.getParameter("uage"));
if(age>20)
{
// pass the request along the filter chain
chain.doFilter(request, response);
}
else
{ writer.println("u r not eligible for mrg u age is below 20 years");
request.getRequestDispatcher("form.html").include(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
Filter2.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Filter2 implements Filter {
public void destroy() {
// TODO Auto-generated method stub
145 | P a g e
Ratanit Adv.Java Mr. Ratan
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
IOException, ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String uaddr = request.getParameter("uaddr");
if(uaddr.equals("hyderabad"))
{ chain.doFilter(request, response);
}
else
{ writer.println("this application only for hyd person");
request.getRequestDispatcher("form.html").include(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
SuccessServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SuccessServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String uname = request.getParameter("uname");
String uage = request.getParameter("uage");
String uaddr = request.getParameter("uaddr");
146 | P a g e
Ratanit Adv.Java Mr. Ratan
}
Session Tracking Mechanisms:
As part of the web application development it is essential to manage the clients previous request data at
the time of processing later request.
To achieve the above requirement if we use request object then container will create request object
when it receives request from client and container will destroy request object when it dispatch response
to client.
Due to this reason request object is not sufficient to manage clients previous request data at the time
of processing later request.
To achieve the above requirement we able to use ServletContext object, but ServletContext object will
share its data to all the components which are used in the present applications and to all the users of
the present web application.
Due to this reason ServletContext object is unable to provide clear cut separation between multiple
users.
In web applications, to manage clients previous request data at the time of processing later request
and to provide separation between multiple users we need a set of mechanisms explicitly at server side
called as Session Tracking Mechanisms.
Session:
Session is a time duration, it will start from the starting point of client conversation with server and will
terminate at the ending point of client conversation with the server.
The data which we transferred from client to server through multiple number of requests during a
particular session then that data is called State of the Session.
In general in web applications, container will prepare a request object similarly to represent a particular
user we have to prepare a separate session.
If we allow multiple number of users on a single web application then we have to prepare multiple
number of session objects.
In this context, to keep track of all the session objects at server machine we need a set of explicit
mechanisms called as Session Tracking Mechanisms.
From the above Session Tracking Mechanisms Servlet API has provided the first 3 Session Tracking
Mechanisms as official mechanisms, Hidden Form Fields Session Tracking Mechanism is purely
developers creation.
147 | P a g e
Ratanit Adv.Java Mr. Ratan
In HttpSession Session Tracking Mechanism, to create HttpSession object we will use either of the
following methods.
req.getSession();
req.getSession(false);
Q: If we allow multiple number of users to access present web application then automatically
container will create multiple number of HttpSession objects. In this case how container will identify
user specific HttpSession object in order to put user specific attributes and to get attributes?
Ans: In HttpSession Session Tracking Mechanism, when we create HttpSession object automatically
container will create an unique identification number in the form of hexadecimal number called as
Session Id.Container will prepare session id in the form of Cookie with the name JSESSIONID.
In general the basic nature of Cookie is to transfer from server to client automatically along with
response and it will be transferred from client to server automatically along with request.
Due to the above nature of Cookies session id Cookie will be transferred from server to client and
from client to server automatically.
In the above context, if we use getSession() method or getSession(false) method first container will pick
up session id value from request and it will identify the user specific HttpSession object on the basis of
session id value.
To destroy HttpSession object explicitly we will use the following method from HttpSession.
public void invalidate()
If we want to destroy HttpSession object after a particular ideal time duration then we have to use the
following method.
public void setMaxInactiveInterval(int time)
In web applications, HttpSession object will allow only attributes data, it will not allow parameters
data.
To set an attribute on to the HttpSession object we have to use the following method.
public void setAttribute(String name, Object value)
To get a particular attribute value from HttpSession object we have to use the following method.
public Object getAttribute(String name)
148 | P a g e
Ratanit Adv.Java Mr. Ratan
To get all attribute names from HttpSession object we have to use the following method.
public Enumeration getAttributeNames()
To remove an attribute from HttpSession object we have to use the following method.
public void removeAttribute(String name)
Drawbacks:
1. In HttpSession Session Tracking Mechanism, we will create a separate HttpSession object
for each and every user, where if we increase number of users then automatically number of
HttpSession object will be created at server machine, it will reduce the overall performance of the web
application.
2. In case of HttpSession Session Tracking Mechanism, we are able to identify user specific HttpSession
object among multiple number of HttpSession objects by carrying Session Id value from client to server
and from server to client.
In the above context, if the client browser disable Cookies then HttpSession Session Tracking
Mechanism will not execute its functionality.
Form1.html:
<html>
<head><center><b><font color="red" size="7">
Registration Form
</font></b></center></head>
<br><br>
<body bgcolor="lightblue"><b>
<font size="7">
<form method="post" action="./FirstServlet">
<pre>
Name <input type="text" name="uname"/>
Age <input type="text" name="uage"/>
<input type="submit" value="Next"/>
</pre>
</form></font></b></body></html>
Form2.html
<html>
<head><center><b><font color="red" size="7">
Registration Form
</font></b></center></head>
<br><br><hr>
<body bgcolor="lightblue"><b>
<font size="7">
<form method="post" action="./SecondServlet">
<pre> Qualification <input type="text" name="uqual"/>
Designation <input type="text" name="udes"/>
<input type="submit" value="Next"/>
</pre>
</form></font></b></body></html>
149 | P a g e
Ratanit Adv.Java Mr. Ratan
Form3.html
<html>
<head><center><b><font color="red" size="7">
Registration Form
</font></b></center></head>
<br><br>
<body bgcolor="lightblue"><b>
<font size="7">
<form method="post" action="./DisplayServlet">
<pre> Email <input type="text" name="email"/>
Mobile <input type="text" name="mobile"/>
<input type="submit" value="display"/>
</pre>
</form></font></b></body></html>
Web.xml:-
<web-app >
<display-name>HttpSession</display-name>
<welcome-file-list>
<welcome-file>form1.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.sravya.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>com.sravya.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>com.sravya.DisplayServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/DisplayServlet</url-pattern>
</servlet-mapping>
</web-app>
150 | P a g e
Ratanit Adv.Java Mr. Ratan
FirstServlet.java:-
package com.sravya;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FirstServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String uname = request.getParameter("uname");
String uage = request.getParameter("uage");
session.setAttribute("uname",uname);
session.setAttribute("uage",uage);
SecondServlet.java:-
package com.sravya;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SecondServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String uqual = request.getParameter("uqual");
String udes = request.getParameter("udes");
HttpSession session = request.getSession();//sid already avaialble
session.setAttribute("uqual", uqual);
session.setAttribute("udes", udes);
151 | P a g e
Ratanit Adv.Java Mr. Ratan
DisplayServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DisplayServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("*******Complete details*******");
writer.println("<br>");
writer.println("user name: "+session.getAttribute("uname"));
writer.println("<br>");
writer.println("user age: "+session.getAttribute("uage"));
writer.println("<br>");
writer.println("user qualification: "+session.getAttribute("uqual"));
writer.println("<br>");
writer.println("user designation: "+session.getAttribute("udes"));
writer.println("<br>");
writer.println("user mobile: "+mobile);
writer.println("<br>");
writer.println("user email: "+email);
writer.println("<br>");
}
}
152 | P a g e
Ratanit Adv.Java Mr. Ratan
In case of HttpSession Session Tracking Mechanism, when we create HttpSession object automatically
Session Id will be created in the form of the Cookie, where Session Id Cookie will be transferred from
server to client and from client to server along with response and request automatically.
In HttpSession Session Tracking Mechanism, we are able to identify user specific HttpSession object
on the basis of Session Id only.
In this context, if we disable Cookies at client browser then HttpSession Session Tracking Mechanism
will not execute its functionality.
In case of Cookies Session Tracking Mechanism, the complete client conversation will be stored at the
respective client machine only in the form of Cookies, here the Cookies data will be opened to every
user of that machine. So that Cookies Session Tracking Mechanism will not provide security for the
application data.
To overcome the above problem, we have to use URL-Rewriting Session Tracking Mechanism.
In case of URL-Rewriting Session Tracking Mechanism, we will not maintain the clients conversation at
the respective client machine, we will maintain the clients conversationin the form of HttpSession object
at server machine. So that URL-Rewriting Session Tracking Mechanism is able to provide very good
security for the application data.
URL-Rewriting Session Tracking Mechanism is almost all same as HttpSession Session Tracking
Mechanism, in URL-Rewriting Session Tracking Mechanism we will not depending on a Cookie to
maintain Session Id value, we will manage Session Id value as an appender to URL in the next generated
form.
In this context, if we send a request from the next generated form automatically the appended
Session Id value will be transferred to server along with the request.
In this case, eventhough if we disable Cookies at client browser, but still we are able to get Session Id
value at server machine and we are able to manage clients previous request data at the time of
processing the later request.
In URL-Rewriting Session Tracking Mechanism, every time we need to rewrite the URL with Session Id
value in the next generated form. So that this mechanism is called as URL-Rewriting Session Tracking
Mechanism.
In URL-Rewriting Session Tracking Mechanism, it is mandatory to append Session Id value to the URL by
getting Session Id value explicitly.
To perform this work HttpServletResponse has provided a separate method like,
public String encodeURL(String url)
Ex: out.println(“<form method=’get’
action=’”+res.encodeURL(“./second”)+”’>”);
Drawback:
In URL-Rewriting Session Tracking Mechanism, every time we need to rewrite the URL with Session Id
value in the generated form, for this we must execute encodeURL() method. So that URL-Rewriting
Session Tracking Mechanism should require dynamically generated forms, it will not execute its
functionality with static forms.
153 | P a g e
Ratanit Adv.Java Mr. Ratan
Form.html:-
<html>
<body>
<form action="./FirstServlet">
User name : <input type="text" name="uname"/><br>
user age : <input type="text" name="uage"/><br>
<input type="submit" value="next"/>
</form>
</body>
</html>
Web.xml:-
<web-app>
<display-name>url</display-name>
<welcome-file-list>
<welcome-file>form.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.sravya.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>com.sravya.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>com.sravya.DisplayServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/DisplayServlet</url-pattern>
</servlet-mapping>
</web-app>
154 | P a g e
Ratanit Adv.Java Mr. Ratan
FirstServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
session.setAttribute("uname", uname);
session.setAttribute("uage", uage);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<body>");
writer.println("<form method='get' action="+response.encodeUrl("./SecondServlet")+">");
writer.println("<br>");
writer.println("user qualificatins :<input type='text' name='uqual'/>");
writer.println("<br>");
writer.println("user designation : <input type='text' name='udes'/>");
writer.println("<br>");
writer.println("<input type='submit' value='next'/>");
writer.println("</form>");
writer.println("</body>");
writer.println("</html>");
}
}
155 | P a g e
Ratanit Adv.Java Mr. Ratan
SecondServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
session.setAttribute("uqual", uqual);
session.setAttribute("udes", udes);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<body>");
writer.println("<form method='get'
action="+response.encodeUrl("./DisplayServlet")+">");
writer.println("<br>");
writer.println("user email :<input type='text' name='email'/>");
writer.println("<br>");
writer.println("user mobile : <input type='text' name='mobile'/>");
writer.println("<br>");
writer.println("<input type='submit' value='display'/>");
writer.println("</form>");
writer.println("</body>");
writer.println("</html>");
}
}
156 | P a g e
Ratanit Adv.Java Mr. Ratan
DisplayServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
157 | P a g e
Ratanit Adv.Java Mr. Ratan
In the above context, when container dispatch response to client automatically all the added
Cookies will be transferred to client and maintain at client machine permanently.
In the above context, when we send further request from the same client automatically all the
Cookies will be transferred to server along with request.
By repeating the above process at each and every request we are able to manage client’s
previous data at the time of processing later request.
Limitaitons:-
If we disable the Cookies at client browser then Cookies Session Tracking Mechanism will
not execute its functionality.
In case of Cookies Session Tracking Mechanism, all the clients data will be maintain at
the respective client machine only, which is open to every user of that machine. So that
Cookies Session Tracking Mechanism will not provide security for the application data.
To create Cookie object with a particular name-value pair we have to use the following Cookie class
constructor.
public Cookie Cookie(String name, String value)
To add a Cookie to the response object we have to use the following method from
HttpServletResponse.
public void addCookie(Cookie c)
To get all the Cookies from response object we need to use the following method.
public Cookie[] getCookies()
To get name and value of a Cookie we have to use the following methods,
public String getName()
public String getValue()
In web applications, it is possible to provide comments to the Cookies. So that to set the comment to
Cookie and get the comment from Cookie we need to use the following methods.
public void setComment(String comment)
public String getComment()
In web applications, it is possible to provide version numbers to the Cookies. So that to set a version
number to Cookie and get a version number from Cookie we need to use the following methods.
public void setVersion(int version_no)
public int getVersion()
In web applications, it is possible to specify life time to the Cookies. So that to set max age to Cookie
and get max age from Cookie we need to use the following methods.
public void setMaxAge(int age)
public int getMaxAge()
158 | P a g e
Ratanit Adv.Java Mr. Ratan
In web applications, it is possible to provide domain names to the Cookies. So that to set domain
name to Cookie and get domain name from Cookie we need to use the following methods.
public void setDomain(String domain)
public String getDomain()
In web applications, it is possible to provide a particular path to the Cookies to store. So that to set a
path to Cookie and get a path from Cookie we need to use the following methods.
public void setPath(String path)
public String getPath()
Form1.html:
<html>
<head><center><b><font color="red" size="7">
Registration Form
</font></b></center></head>
<br><br>
<body bgcolor="lightblue"><b>
<font size="7">
<form method="post" action="./FirstServlet">
<pre> Name <input type="text" name="uname"/>
Age <input type="text" name="uage"/>
<input type="submit" value="Next"/>
</pre>
</form></font></b></body></html>
Form2.html
<html>
<head><center><b><font color="red" size="7">
Registration Form
</font></b></center></head>
<br><br><hr>
<body bgcolor="lightblue"><b>
<font size="7">
<form method="post" action="./SecondServlet">
<pre> Qualification <input type="text" name="uqual"/>
Designation <input type="text" name="udes"/>
<input type="submit" value="Next"/>
</pre>
</form></font></b></body></html>
Form3.html
<html>
<head><center><b><font color="red" size="7">
Registration Form
</font></b></center></head>
<br><br>
<body bgcolor="lightblue"><b>
<font size="7">
<form method="post" action="./DisplayServlet">
159 | P a g e
Ratanit Adv.Java Mr. Ratan
Web.xml:-
<web-app >
<display-name>Cookies</display-name>
<welcome-file-list>
<welcome-file>form1.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.sravya.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>com.sravya.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>com.sravya.DisplayServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/DisplayServlet</url-pattern>
</servlet-mapping>
</web-app>
160 | P a g e
Ratanit Adv.Java Mr. Ratan
FirstServlet.java:-
package com.sravya;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
response.addCookie(cookie1);
response.addCookie(cookie2);
request.getRequestDispatcher("form2.html").forward(request, response);
}
}
SecondServlet:-
package com.sravya;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecondServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String uqual = request.getParameter("uqual");
String udes = request.getParameter("udes");
response.addCookie(cookie3);
response.addCookie(cookie4);
request.getRequestDispatcher("form3.html").forward(request, response);
}
}
161 | P a g e
Ratanit Adv.Java Mr. Ratan
DisplayServlet.java:-
package com.sravya;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Cookie[] c = request.getCookies();
writer.println("user name="+ c[0].getValue());
writer.println("<br>");
writer.println("user name="+ c[1].getValue());
writer.println("<br>");
writer.println("user name="+ c[2].getValue());
writer.println("<br>");
writer.println("user name="+ c[3].getValue());
writer.println("<br>");
writer.println("user name="+ mobile);
writer.println("<br>");
writer.println("user name="+ email);
writer.println("<br>");
}
}
162 | P a g e
Ratanit Adv.Java Mr. Ratan
In the above context, if we dispatch the response to client then we are able to get a dynamic form with
visible fields and with invisible fields.
If we send a request from dynamic form then automatically all the visible fields data and invisible fields
data will be send to server as request parameters.
By repeating above process at each and every request we are able to manage the clients previous
request data at the time of processing the later request.
studentform.html:-
<html>
<head>
<body bgcolor="lightgreen">
<form method="get" action="./first">
<center><b><br><br>
Student Name:<input type="text" name="sname"/><br><br>
Student Id:<input type="text" name="sid"/><br><br>
Student Address:<input type="text" name="saddr"/><br><br>
<input type="submit" value="Submit">
</b></center>
</form>
</body>
</html>
web.xml:-
<web-app>
<display-name>hiddenformfieldsapp</display-name>
<welcome-file-list>
<welcome-file>studentform.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
163 | P a g e
Ratanit Adv.Java Mr. Ratan
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ThirdServlet</servlet-name>
<servlet-class>ThirdServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ThirdServlet</servlet-name>
<url-pattern>/third</url-pattern>
</servlet-mapping>
</web-app>
FirstServlet.java:-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
String sname=request.getParameter("sname");
String sid=request.getParameter("sid");
String saddr=request.getParameter("saddr");
out.println("<html><body bgcolor='lightyellow'>");
out.println("<center><b><br><br>");
out.println("Welcome to Student Application");
out.println("<br><br>");
out.println("<form method='get' action='/hiddenformfieldsapp/second'>");
out.println("<input type='hidden' name=sname value='"+sname+"'>");
out.println("<input type='hidden' name=sid value='"+sid+"'>");
out.println("<input type='hidden' name=saddr value='"+saddr+"'>");
out.println("<br><br>");
out.println("Student Age:");
out.println("<input type='text' name='sage'>");
out.println("<br><br>");
out.println("<input type='submit' value='Submit'>");
out.println("</form></b></center></body></html>");
}
}
164 | P a g e
Ratanit Adv.Java Mr. Ratan
SecondServlet.java:-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecondServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
String sname=request.getParameter("sname");
String sid=request.getParameter("sid");
String saddr=request.getParameter("saddr");
String sage=request.getParameter("sage");
out.println("<html><body bgcolor='lightyellow'>");
out.println("<center><b><br><br>");
out.println("Student Details Are...");
out.println("<br><br>");
out.println("Student Name....."+sname+"<br><br>");
out.println("Student Id....."+sid+"<br><br>");
out.println("Student Address....."+saddr+"<br><br>");
out.println("<a href='/hiddenformfieldsapp/third?sage="+sage+"'>
SHOW STUDENT AGE</a>");
}
}
ThirdServlet.java:-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ThirdServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
String sage=request.getParameter("sage");
out.println("<html><body bgcolor='lightpink'>");
out.println("<center><b><br><br>");
out.println("Student Age is....."+sage);
out.println("</b></center></body></html>");
}
}
165 | P a g e
Ratanit Adv.Java Mr. Ratan
Form.html:-
<html>
<body>
<form method="get" action="./MyServlet">
enter table name to Get Data : <input type="text" name="tname"/>
<input type="submit" value="submit">
</form>
</body>
</html>
Web.xml:
<web-app>
<welcome-file-list>
<welcome-file>form.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.dss.MyListener</listener-class>
</listener>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.dss.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
166 | P a g e
Ratanit Adv.Java Mr. Ratan
MyListener.java:
package com.dss;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
167 | P a g e
Ratanit Adv.Java Mr. Ratan
MyServlet.java:-
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
168 | P a g e
Ratanit Adv.Java Mr. Ratan
HttpSessionEvent vs HttpSessionListener:-
The httpSessionEvent is notified when the session object is changed. The corresponding listener is
HttpSessionListener.
We can perform some operatrions like counting number of login logged in users & maintains the
login details.
There are two methods declared in the HttpSessionListener interface which must be
implemented by the servlet programmer to perform some action.
Web.xml:-
<web-app>
<welcome-file-list>
<welcome-file>form.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.dss.CountUserListener</listener-class>
</listener>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>com.dss.First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>com.dss.Logout</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/Logout</url-pattern>
</servlet-mapping>
</web-app>
169 | P a g e
Ratanit Adv.Java Mr. Ratan
CountUSerListener:-
package com.dss;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
170 | P a g e
Ratanit Adv.Java Mr. Ratan
First.java:-
package com.dss;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
HttpSession session=request.getSession();
out.print("<br><a href='Logout'>logout</a>");
out.close();
}
}
171 | P a g e
Ratanit Adv.Java Mr. Ratan
Logout.java:-
package com.dss;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
HttpSession session=request.getSession(false);
session.invalidate();//invalidating session
172 | P a g e
Ratanit Adv.Java Mr. Ratan
Annotations in servlets:-
Annotaitons are used to provide the metadata of the application.
Annotations are introduced in servlet 3.0 version
Annotaitons are replacement of web.xml file but not completely.
With web.xml:-
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.dss.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
With annotaitons :-
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet
{ //code here
}
173 | P a g e
Ratanit Adv.Java Mr. Ratan
Example :-@WebServlet
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = { "/MyServlet" },
initParams = { @WebInitParam(name = "user1" , value = "ratan"),
@WebInitParam(name = "user2" , value = "anu")
})
@WebListener
public class MyListener implements HttpSessionListener
{ //code here
}
174 | P a g e
Ratanit Adv.Java Mr. Ratan
Example : @WebFilter
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
@WebFilter(urlPatterns="/Filter1",
initParams={
@WebInitParam(name="user1", value="ratan"),
@WebInitParam(name="user2", value="anu")
})
Limitations of annotaitons :-
1. It is not possible to configure welcome file list.
2. It is not possible to configure <context-param> data.
175 | P a g e
Ratanit Adv.Java Mr. Ratan
Example:-
Web.xml :-
<web-app>
<context-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</context-param>
<context-param>
<param-name>phone</param-name>
<param-value>9000160099</param-value>
</context-param>
</web-app>
ExampleServlet.java:-
package com.dss;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext ctx = config.getServletContext();
email = ctx.getInitParameter("email");
phone = ctx.getInitParameter("phone");
}
response.setContentType("text/html");
PrintWriter writer = resp.getWriter();
176 | P a g e
Ratanit Adv.Java Mr. Ratan
Index.html
<a href="MyServlet1">click for photo</a>
package com.dss;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("image/jpg");
ServletOutputStream out = response.getOutputStream();
177 | P a g e
Ratanit Adv.Java Mr. Ratan
Deployment process:
Generally there are four ways to deploy the application into server.
1. Create the war file & deploy the war file (import & export options in IDE).
2. Deploy the war file in tomcat webapps folder.
3. Deploy the war file directly from server console.
4. Copy the tomcat folder structure from IDE, deploy into tomcat web apps folder.
Create the war file & deploy the war file (import & export options in IDE).
178 | P a g e
Ratanit Adv.Java Mr. Ratan
Introduction
Servlet vs Jsp
JSP Model1 Architecture
JSP Model2 Architecture
Jsp life cycle
Jsp toservlet translation
Jsp tags
Jsp implicit 9-objects
Directives
Page
Include
Taglib
Scripting Elements
Scriptlets
Expression
Declarations
Comments
Jsp sopes
Page
Request
Application
Session
Jsp Actions
Standred Actions
Custom actions
Exception handling in jsp
JSTL:-
Core tags
SQL tags
Xml tags
Function tags
I18n tags
179 | P a g e
Ratanit Adv.Java Mr. Ratan
Jsp vs Servlets:-
Jsp is extension of servlets so we can use all features of servlets in addition we can use implicit
objects, custom tags, predefined tags.
If we down modifications on servlets for every modification need to recompiled and redeployed
but in jsp refresh button is enough to reflect the modifications.
Servlets runs faster compere to jsp because the jsp are internally converted into servlets that
converted servlets are executed then we will get the response.
To write the servlets we required more java knowledge but to write the jsp code less java
knowledge is sufficient.
In MVC jsp acts as a view part & servlets acts as a controller part.
Servlets are best for more processing logics but jsp are best to develop dynamic web pages for
more presentation logics rather than processing logics.
In servlets we are mixing both presentation logics and business logics but in jsp we can separate
our business logics with presentation logics.
We must place the servlets in private area of directory structure so to access the private area
elements web.xml is mandatory but it is possible to place the jsp pages both public & private
area hence to access the jsp web.xml is optional.
o
The life cycle methods of jsp
_jspInt() _jspService() _jspDestroy()
180 | P a g e
Ratanit Adv.Java Mr. Ratan
Web.xml:-
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
In this example we are using Annotations hence the web.xml configurations are minimized.
LoginServlet.java:-
package com.dss;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
181 | P a g e
Ratanit Adv.Java Mr. Ratan
public LoginServlet() { }
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Conclusion:-
In the above example, Servlet class is used for:
1) Handling User Inputs.
2) Performing (or Invoking) Business Logic.
3) Presentation layer (Rendering response on browser).
Disadvantages:-
1. Writing html code inside the servlets is not recommended and html code written by page authors
who may not know java.
2. Inside the servlet class the HTML tags are enclosed with out.Println () method it decsable IDE to
give predefined support.
3. For every change servlet is recompiled.
4. Servlets are directly can’t access we have to use web.xml file configuration.
182 | P a g e
Ratanit Adv.Java Mr. Ratan
183 | P a g e
Ratanit Adv.Java Mr. Ratan
184 | P a g e
Ratanit Adv.Java Mr. Ratan
Step 3: - create the jsp in project WebContent folder. [Right click on WebContent]
Step 4:- build path the required jar files. [Right click on project]
185 | P a g e
Ratanit Adv.Java Mr. Ratan
186 | P a g e
Ratanit Adv.Java Mr. Ratan
Jsp Application :-
first.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body bgcolor="lightgreen">
<center><b><font size="7" color="red">
First Jsp Application By Mr. Ratan
</font></b></center>
</body>
</html>
When you send the request to first.jsp it is translated to first_jsp.java the translated servlet
location is,
G:\JspApps\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\JspApp1\org\
apache\jsp
Mainly the jsp life cycle process :- From the Next Request:-
1. Translation phase
2. Compilation phase
3. Loading & Instantiating
4. _jspInit() method (Initialization)
5. _jspService() method (Request Handling)
6. _jspDestroy() method(Removing)
187 | P a g e
Ratanit Adv.Java Mr. Ratan
request
Jsp Loading
Jsp Parsing
Servlet Compilation
Servlet Loading
Servlet Instantiation
Servlet Initialization
Servlet Deinstantiation
Servlet Unloading
Jsp Unloading
188 | P a g e
Ratanit Adv.Java Mr. Ratan
Jsp Loading:-
Here container will load Jsp file to the memory from web application directory structure.
Jsp Parsing:-Here container will check all the tags in Jsp page are in well-formed format or not.
Servlet Compilation:-
After getting the translated servlet container will compile servlet java file and generates the
respective .class file.
Servlet Loading:-Here container will load the translated servlet class byte code to the memory.
Servlet Instantiation:- Here container will create object for the loaded servlet.
Servlet Initialization:-Here container will access _JspInit() method to initialize the servlet.
Servlet Deinstantiation:-
After destroying request and response objects container will be in waiting state depends
on the container, then container identifies no further request for the same resource then
container will destroy servlet object, for this container will execute _JspDestroy() method.
189 | P a g e
Ratanit Adv.Java Mr. Ratan
For the above 3 abstract methods HttpJspBase class has provided the default implementation
but _JspService(_,_) method would be overridden in first_jsp class with the content what we provided in
first.jsp file.
190 | P a g e
Ratanit Adv.Java Mr. Ratan
Translated Servlet:-
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
static {
_jspx_imports_packages = new java.util.HashSet<>();
_jspx_imports_packages.add("javax.servlet");
_jspx_imports_packages.add("javax.servlet.http");
_jspx_imports_packages.add("javax.servlet.jsp");
_jspx_imports_classes = null;
}
191 | P a g e
Ratanit Adv.Java Mr. Ratan
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("<html>\r\n");
192 | P a g e
Ratanit Adv.Java Mr. Ratan
out.write("<body bgcolor=\"lightgreen\">\r\n");
out.write(" <center><b><font size=\"7\" color=\"red\">\r\n");
out.write(" First Jsp Application By Mr. Ratan\r\n");
out.write(" </font></b></center>\t\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
Conclusion:- The _jspInit() and _jspDestroy() methods are invoked once, but _jspService() method is
executed each time a JSP page is requested.
If there is any error during translation, then the container raises an exception with error code 500
(internal server error).
193 | P a g e
Ratanit Adv.Java Mr. Ratan
Note: If we configure a jsp in web.xml then we can send the request to the jsp either by using jsp
filename or by using its url-pattern.
If we want to configure a JSP in web.xml file the xml elements are same as Servlet-configuration,
We need to replace <servlet-class> element with <jsp-file>
Servlets are private files present in classes folder hence access these file by using web.xml
Jsp are public file hence we can access the public file elements directly by sending request from browser.
First.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
this is the jsp file configured in web.xml
</body>
</html>
Web.xml:-
<web-app>
<servlet>
<servlet-name>FirstJsp</servlet-name>
<jsp-file>/first.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>FirstJsp</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
</web-app>
194 | P a g e
Ratanit Adv.Java Mr. Ratan
Jsp Elements:
Jsp Elements
195 | P a g e
Ratanit Adv.Java Mr. Ratan
Jsp Directives:-
The jsp directives are messages that tell the web container how to translate a jsp page into
the corresponding servlet.
<%@ include attribute="value" %> Includes a file during the translation phase.
<%@ taglib attribute="value" %>Declares a tag library, containing custom actions, used in the page
Page Directive:-
Page Directive can be used to define the present Jsp page characteristics like to define
import statements, specify particular super class to the translated servlet, to specify metadata about
present Jsp pages and so on.
<%@page [attribute-list]%>
Where attribute-list in Jsp page directive may include the following list.
Language contentType import extends
Info buffer autoFlush errorPage
isErrorPage session isThreadSafe isELIgnored
language:-
This attribute can be used to specify language.
The default value of this attribute is java.
<%@page language=”java”%>
196 | P a g e
Ratanit Adv.Java Mr. Ratan
contentType:
This attribute will take a particular MIME type in order to give an intimation to the client
about to specify the type of response which Jsp page has generated.
<%@page contentType=”text/html”%>
The default value of this attribute is text/html.
import:
This attribute can be used to import a particular packages into the present Jsp pages.
<%@page import=”java.io.*”%>
If we want to import multiple number of packages into the present Jsp pages then we
have to use either of the following 2 approaches.
Specify multiple number of packages with comma(,) .
<%@page import=”java.io.*,java.util.*,java.sql.*”%>
The default values of this attribute are java.lang, javax.servlet, javax.servlet.http, javax.servlet.jsp.
Note: Among all the Jsp page attributes only import attribute is repeatable attribute, no other
attribute is repeatable.
extends:
This attribute will take a particular class name, it will be available to the translated servlet
as super class.
<%@page extends=”com.dss.MyClass”%>
Where MyClass should be an implementation class to HttpJspPage interface and should
be a subclass to HttpServlet.
The default value of this attribute is HttpJspBase class.
info:
This attribute can be used to specify some metadata about the present Jsp page.
<%@page info=”First Jsp Application”%>
If we want to get the specified metadata programmatically then we have to use the
following method from Servlet interface.
public String getServletInfo()
The default value of this attribute is Jasper JSP2.2 Engine.
buffer:
This attribute can be used to specify the particular size to the buffer available in
JspWriter object.
Note: Jsp technology is having its own writer object to track the generated dynamic response,
JspWriter will provide very good performance when compared with PrintWriter in servlets.
<%@page buffer=”52kb”%>
The default value of this attribute is 8kb.
197 | P a g e
Ratanit Adv.Java Mr. Ratan
autoFlush:
It is a boolean attribute, it can be used to give an intimation to the container about to flush or
not to flush dynamic response to client automatically when JspWriter buffer filled with the response
completely.
If autoFlush attribute value is true then container will flush the complete response to the client
from the buffer when it reaches its maximum capacity.
If autoFlush attribute value is false then container will raise an exception when the buffer is
filled with the response.
org.apache.jasper.JasperException:An exception occured processing JSP page/first.jsp at line:9
root cause: java.io.IOException:Error:Jsp Buffer Overflow.
Note: if we provide 0kb as value for buffer attribute and false as value for autoFlush attribute then
container will raise an exception like org.apache.jasper.JasperException:/first.jsp(1,2)
jsp.error.page.badCombo
The default value of this attribute is true.
Application: -form.jsp
<%@ page language="java" contentType="text/html" buffer="1kb" autoFlush="true"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% for(int i=0; i<1000; i++) {
out.println("RAMA"); }
%>
</body>
</html>
Observation :-
<%@ page language="java" contentType="text/html" buffer="1kb" autoFlush="false"%>
Caused by: java.io.IOException: Error: JSP Buffer overflow
session:
It is a Boolean attribute, it is give intimation to the container about to allow or not to allow
session implicit object into the present Jsp page.The default value of this attribute is true.
Example: <%@page session=”true”%>
<%@ page session=”true” %>
The generated servlet class contains:
HttpSession session = null;
session = pageContext.getSession();
<%@ page session=”false” %>
Above two lines won’t be generated in servlet class.
198 | P a g e
Ratanit Adv.Java Mr. Ratan
errorPage:
This attribute can be used to specify an error page to execute when we have an exception in
the present Jsp page.
<%@page errorPage=”error.jsp”%>
isErrorPage:
It is a boolean attribute, it can be used to give an intimation to the container about to allow or not to
allow exception implicit object into the present Jsp page.
If we provide value as true to this attribute then container will allow exception implicit object into the
present Jsp page.
If we provide value as false to this attribute then container will not allow exception implicit object into
the present Jsp page.
The default value of this attribute is false.
Example: <%@page isErrorPage=”true”%>
first.jsp:
<%@ page language="java" contentType="text/html" import="java.util.*" errorPage="error.jsp"%>
<html>
<body>
<%!Date d=null;%>
<%
out.println(d.toString());
%>
</body>
</html>
error.jsp:
<%@ page language="java" contentType="text/html" isErrorPage="true"%>
<html>
<body>
<%=exception%>
</body>
</html>
199 | P a g e
Ratanit Adv.Java Mr. Ratan
isThreadSafe:-
It is a boolean attribute, it can be used to give an intimation to the container about to
allow or not to allow multiple number of requests at a time into the present Jsp page.
If we provide true as value to this attribute then container will allow multiple number of
requests at a time.
If we provide false as value to this attribute then automatically container will allow only one
request at a time and it will implement SingleThreadModel interface in the translated servlet.
The default value of this attribute is true.
Indicates whether the code in JSP already provides thread-safe (or) the generated servlet class to
provide thread-safe by implementing SingleThreadModel interface.
<%@ page isThreadSafe=”true” %>
In this case, the code inside JSP already provides thread-safe, hence, the generated servlet class
not required to implement SingleThreadModel interface. The JSP page can process any number of
requests simultaneously.
isELIgnored:-
It is a boolean attribute, it can be used to give an intimation to the container about to allow or
not to allow Expression Language syntaxes in the present Jsp page.
Note: Expression Language is a Scripting language, it can be used to eliminate java code completely from
the Jsp pages.
If isELIgnored attribute value is true then container will eliminate Expression Language syntaxes
from the present Jsp page.
If we provide false as value to this attribute then container will allow Expression Language syntaxes
into the present Jsp pages.
The default value of this attribute is false.
<%@page isELIgnored=”true”%>
The default value in JSP1.2 version is: true.
The default value from JSP2.0 version is: false
200 | P a g e
Ratanit Adv.Java Mr. Ratan
Include Directive:
The common code across all JSP pages recommended to write once in a separate JSP page, and
include this JSP across all other JSPs using <%@ include %> directive.
The main advantage with this approach is to promote Reusability and Maintainability.
<%@include file=”--”%>
Where file attribute can be used to specify the name and location of the target resource.
logo.jsp:
<html>
<body><center>
<table width="100%" height="20%" bgcolor="red">
<tr><td colspan="2"><center><b><font size="7" color="white">
Ratan Software Solutions
</font></b></center></td></tr>
</table></center></body>
</html>
footer.jsp:
<html>
<body><center>
<table width="100%" height="15%" bgcolor="blue">
<tr><td colspan="2"><center><b><font size="6" color="white">
copyrights2010-2020@Ratansoftwaresolutions
</font></b></center></td></tr>
</table></center></body>
</html>
body.jsp:
<html>
<body bgcolor="lightyellow">
<center><b><font size="7">
<p><br>
Ratan Software Solutions is one of the Training Institute.
<br><br></p>
</font></b></center></body>
</html>
mainpage.jsp:
<%@include file="logo.jsp"%>
<%@include file="body.jsp"%>
<%@include file="footer.jsp"%>
Note : in including mechanism all the dependent file content Is included in main file during
translation page hence it is static inclusion.
201 | P a g e
Ratanit Adv.Java Mr. Ratan
Taglib directive:-
We can use ‘taglib‘ directive to make custom tags available to the JSP page.
Syntax:-
<%@ taglib uri=”URI” prefix=”prefix” %>
Example: -
<%@ taglib uri=”http://struts.apache.org/tags-html” prefix="html"%>
202 | P a g e
Ratanit Adv.Java Mr. Ratan
Expressions : <%= expression%> that are evaluated and inserted into output,
Scriptlets : <% code %> that are inserted into the servlets service method,
Declarations: <%! code %> that are inserted into the body of the servlet class, outside of any methods.
1) Declarations:
It can be used to declare the variable declarations, method definitions, classes
declaration…etc
The code written inside the jsp declaration tag is placed outside the service() method of
servlet.
Syntax : <%! Field or method Declarations; %>
2) Scriptlets:-This Scripting Element can be used to provide a block of java code. This is code is
placed inside _jspService() method.
Syntax: <% Block of java code %>
Example :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" import="java.util.*" %>
<html>
<body>
<!-- basic application -->
<%! Date d=null; %>
<% d= new Date(); %>
today date is=<%=d%>
</body>
</html>
If we provide any block of java code by using scriptlets then that code will be available to translated
servlet inside _jspService(_,_) method.
203 | P a g e
Ratanit Adv.Java Mr. Ratan
3) Expressions:
This is scripting element can be used to evaluate the single java expression and display that expression
resultant value onto the client browser.
Syntax: <%=Java Expression%>
If we provide any java expression in expression scripting element then that expression will be available
to translated servlet inside _JspService(_,_) method as a parameter to out.write() method.
Ex: out.write(Java Expression);
4) Jsp Comments:-
In Jsp pages, we are able to use the following 3 types of comments.
XML-Based Comments
Jsp-Based Comments
Java-Based Comments inside Scripting Elements
1. XML-Based Comments:
<!--
St-1
St -2 Description
-->
2. Jsp-Based Comments:
<%--
st-1
st-2Description
--%>
204 | P a g e
Ratanit Adv.Java Mr. Ratan
Login.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%!
String uname;
String upwd;
%>
<%
uname = request.getParameter("username");
upwd = request.getParameter("password");
if(uname.equals("ratan") && upwd.equals("ratan"))
{ out.println("login success");
}
else
{ out.println("login failure");
}
%>
<br/>
user name : <%=uname %>
<br/>
user Password : <%=upwd %>
</body>
</html>
205 | P a g e
Ratanit Adv.Java Mr. Ratan
Login.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%!
String uname;
String upwd;
%>
<%
uname = request.getParameter("username");
upwd = request.getParameter("password");
if(uname.equals("ratan") && upwd.equals("ratan"))
{ response.sendRedirect("http://www.facebook.com");
}
else
{ response.sendError(777,"login fail try with valid user name & password");
}
%>
<br/>
user name : <%=uname %>
<br/>
user Password : <%=upwd %>
</body>
</html>
206 | P a g e
Ratanit Adv.Java Mr. Ratan
Scopes in jsp :-
There are four scopes in jsp
Page
Request
Session
Application
Page scope:-
‘page’ scope means, the JSP object can be accessed only from within the same page
where it was created.
The default scope for JSP objects created using <jsp:useBean> tag is page. JSP implicit
objects out, exception, response, pageContext, config and page have ‘page’ scope.
Request scope:-
A JSP object created using the ‘request’ scope can be accessed from any pages that serves that
request. More than one page can serve a single request. The JSP object will be bound to the request
object.
Implicit object request has the ‘request’ scope.
Session scope :-
‘session’ scope means, the JSP object is accessible from pages that belong to the same session
from where it was created. The JSP object that is created using the session scope is bound to the session
object.
Implicit object session has the ‘session’ scope.
Application scope:-
A JSP object created using the ‘application’ scope can be accessed from any pages across the
application. The JSP object is bound to the application object.
Implicit object application has the ‘application’ scope.
207 | P a g e
Ratanit Adv.Java Mr. Ratan
PageContext :-
pageContext is a implicit object in jsp of type PageContext object.
The PageContext object is used to set or get or remove the the attricutes form fallowing scopes,
Page
Request
Session
Application
form.html:-
<html>
<body>
<form action="welcome.jsp" method="post">
Enter user name = <input type="text" name="uname"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Welcome.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%
String uname = request.getParameter("uname");
pageContext.setAttribute("uname",uname, PageContext.SESSION_SCOPE);
Second.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%String uname = (String)pageContext.getAttribute("uname",PageContext.SESSION_SCOPE);
out.println("Welcome="+uname);
%>
</body>
</html>
208 | P a g e
Ratanit Adv.Java Mr. Ratan
<context-param>
<param-name>username</param-name>
<param-value>ratan</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>Anu</param-value>
</context-param>
<servlet>
<servlet-name>aaa</servlet-name>
<jsp-file>/First.jsp</jsp-file>
<init-param>
<param-name>Animal</param-name>
<param-value>Tiger</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>aaa</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bbb</servlet-name>
<jsp-file>/Second.jsp</jsp-file>
<init-param>
<param-name>Fruit</param-name>
<param-value>Mango</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>bbb</servlet-name>
<url-pattern>/Second</url-pattern>
</servlet-mapping>
</web-app>
209 | P a g e
Ratanit Adv.Java Mr. Ratan
First.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%!String animal;
String uname;
String upwd;
%>
<%animal = config.getInitParameter("Animal");
uname = application.getInitParameter("username");
upwd = application.getInitParameter("password");
%>
Second.java
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%! String animal;
String uname;
String upwd;
%>
210 | P a g e
Ratanit Adv.Java Mr. Ratan
SaveName.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<% String name = request.getParameter("uname");
session.setAttribute( "theName", name );
%>
<a href="NextPage.jsp">Continue</A>
</body>
</html>
NextPage.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<head>
Hello,<%= session.getAttribute("theName")%>
</body>
</html>
Example :-
Form1.html
<html>
<body bgcolor="pink">
<center> <form method="get" action="./First.jsp">
Name : <input type="text" name="uname"/><br><br>
Age : <input type="text" name="uage"/><br><br>
<input type="submit" value="Next"/>
</form>
</center>
</body>
</html>
First.jsp:-
211 | P a g e
Ratanit Adv.Java Mr. Ratan
session.setAttribute("name", name);
session.setAttribute("age", age);
%>
<jsp:forward page="form2.html"/>
</body>
</html>
Form2.html:-
<html>
<body bgcolor="pink">
<center>
<form method="get" action="./second.jsp">
Qualification : <input type="text" name="uqual"/><br><br>
Designation : <input type="text" name="udesig"/><br><br>
<input type="submit" value="Next"/>
</form>
</center>
</body>
</html>
Second.jsp:-
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%!String qual;
String desig;
%>
212 | P a g e
Ratanit Adv.Java Mr. Ratan
This approach specify one error for all kind of exceptions, so we can’t specify the error
page different exceptions like,
SQLException ---> dbError.jsp
IOException ---> ioerror.jsp
When the file name of error page is changed we have to update all referenced jsp files.
213 | P a g e
Ratanit Adv.Java Mr. Ratan
Web.xml:-
<web-app>
<error-page>
<exception-type>java.lang.StringIndexOutOfBoundsException</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
error.jsp:-
<%@ page contentType="text/html"%>
<html>
<body>
<%out.print("hi Mr.RATAN StringIndexOutOfBounds Exception raised");
%>
</body>
</html>
The above error pages can be used across all JSPs in a given web application. Declarative
approach is always recommended.
In error page no need to specify the isErrorPage attribute.
214 | P a g e
Ratanit Adv.Java Mr. Ratan
Note: While preparing Tag Handler classes in custom tags container will provide pageContext object as
part of its life cycle, from this we are able to get all the implicit objects.
In Jsp applications, by using pageContext object we are able to perform some operations with the
attributes in Jsp scopes page, request, session and application like adding an attribute, removing an
attribute, getting an attribute and finding an attribute.
To set an attribute onto a particular scope pageContext has provided the following method.
public void setAttribute(String name, Object value, int scope)
Where scopes may be
public static final int PAGE_SCOPE=1;
public static final int REQUEST_SCOPE=2;
public static final int SESSION_SCOPE=3;
public static final int APPLICATION_SCOPE=4;
Example:
<% pageContext.setAttribute(“a”, “aaa”, pageConext.REQUEST_SCOPE); %>
To get an attribute from page scope we have to use the following method.
public Object getAttribute(String name)
Ex: String a=(String)pageContext.getAttribute(“a”);
If we want to get an attribute value from the specified scope we have to use the following method.
public Object getAttribute(String name, int scope)
Ex: String uname=(String)pageContext.getAttribute(“uname”, pageContext.SESSION_SCOPE);
To remove an attribute from a particular we have to use the following method.
public void removeAttribute(String name, int scope)
Ex: pageContext.removeAttribute(“a”, pageContext.SESSION_SCOPE);
To find an attribute value from page scope, request scope, session scope and application scope we
have to use the following method.
Public Object findAttribute(String name)
Ex: String name=pageContext.findAttribute(“uname”);
215 | P a g e
Ratanit Adv.Java Mr. Ratan
Jsp Actions:
In Jsp technology, by using scripting elements we are able to provide java code inside the Jsp pages,
but the main theme of Jsp technology is not to allow java code inside Jsp pages.
To eliminate java code from Jsp pages we have to eliminate scripting elements, to eliminate scripting
elements from Jsp pages we have to provide an alternative i.e. Jsp Actions.
In case of Jsp Actions, we will define a scripting tag in Jsp page and we will provide a block of java code
w.r.t. scripting tag.
When container encounters the scripting tag then container will execute respective java code, by this an
action will be performed called as Jsp Action.
In Jsp technology, there are 2 types of actions.
1. Standard Actions
2. Custom Actions
1. Standard Actions:
Standard Actions are Jsp Actions, which could be defined by the Jsp technology to perform a particular
action.
Jsp technology has provided all the standard actions in the form of a set of predefined tags called
Action Tags.
1. <jsp:useBean---->
2. <jsp:setProperty---->
3. <jsp:getProperty---->
4. <jsp:include---->
5. <jsp:forward---->
6. <jsp:param---->
7. <jsp:plugin---->
8. <jsp:fallback---->
9. <jsp:params---->
10. <jsp:declaration---->
11. <jsp:scriptlet---->
12. <jsp:expression---->
Java Beans:
216 | P a g e
Ratanit Adv.Java Mr. Ratan
<jsp:useBean>:
The main purpose of <jsp:useBean> tag is to interact with bean object from a particular Jsp
page.
This tag used to locate or instantiate bean class. If the bean object is already created it doesn’t
create a bean based on scope. But if the bean is not created it instantiate the bean.
Note: In <jsp:useBean> tag, always it is suggestible to provide either application or session scope to the
scope attribute value.
When container encounters the above tag then container will pick up class attribute value i.e. fully
qualified name of Bean class then container will recognize Bean class .class file and perform Bean class
loading and instantiation.
After creating Bean object container will assign Bean object reference to the variable specified as value
to id attribute.
After getting Bean object reference container will store Bean object in a scope specified as value to scope
attribute.
<jsp:setProperty>:
The main purpose of <jsp:setProperty> tag is to execute a particular setter method in order to set a value
to a particular Bean property.
Syntax: <jsp:setProperty name=”--” property=”--” value=”--”/>
Where name attribute will take a variable which is same as id attribute value in <jsp:useBean> tag.
Where property attribute will take a property name in order to access the respective setter method.
Where value attribute will take a value to pass as a parameter to the respective setter method.
3. <jsp:getProperty>:
The main purpose of <jsp:getProperty> tag is to execute a getter method in order to get a value from
Bean object.
Syntax: <jsp:getProperty name=”--” property=”--”/>
Where name attribute will take a variable which is same as id attribute value in <jsp:useBean> tag.
Where property attribute will take a particular property to execute the respective getter method.
Note: In case of <jsp:useBean> tag, in general we will provide a separate <jsp:setProperty> tag to set a
particular value to the respective property in Bean object.
In case of <jsp:useBean> tag, it is possible to copy all the request parameter values directly onto the
respective Bean object.
To achieve this we have to provide “*” as value to property attribute in <jsp:setProperty> tag.
Ex: <jsp:setProperty name=”e” property=”*”/>
If we want to achieve the above requirement then we have to maintain same names in the request
parameters i.e. form properties and Bean properties.
Note: The above “*” notation is not possible with <jsp:getProperty> tag.
217 | P a g e
Ratanit Adv.Java Mr. Ratan
Form.html
<html>
<h5> *******Employee Details********</h5>
<body>
<form method="post" action="main.jsp">
Employee id :<input type="text" name="eid"/><br>
Employee name : <input type="text" name="ename"/><br>
Employee salary :<input type="text" name="esal"/></br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Main.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%! int eid;
String ename;
double esal;
%>
<% eid = Integer.parseInt(request.getParameter("eid"));
ename = request.getParameter("ename");
esal = Double.parseDouble(request.getParameter("esal"));
%>
<jsp:useBean id="eb" class="com.sravya.EmpBean" scope="page"/>
<jsp:setProperty property="ename" name="eb" value="<%=ename%>"/>
<jsp:setProperty property="eid" name="eb" value="<%=eid%>"/>
<jsp:setProperty property="esal" name="eb" value="<%=esal%>"/>
<h5>**********Employee Details**********</h5>
Employee name : <jsp:getProperty property="ename" name="eb"/><br>
Employee id : <jsp:getProperty property="eid" name="eb"/> <br>
Employee salary: <jsp:getProperty property="esal" name="eb"/><br>
</body>
</html>
218 | P a g e
Ratanit Adv.Java Mr. Ratan
EmpBean.java
package com.sravya;
import java.io.Serializable;
publicclass EmpBean implements Serializable{
int eid;
String ename;
double esal;
publicint getEid() {
return eid;
}
publicvoid setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
publicvoid setEname(String ename) {
this.ename = ename;
}
publicdouble getEsal() {
return esal;
}
publicvoid setEsal(double esal) {
this.esal = esal;
}
}
219 | P a g e
Ratanit Adv.Java Mr. Ratan
4. <jsp:include>:
Q: What are the differences between include directive and <jsp:include> action
tag?
Ans: 1. In Jsp applications, include directive can be used to include the content of the
target resource into the present Jsp page.
In Jsp pages, <jsp:include> action tag can be used to include the target resource
response into the present Jsp page response.
2. In general include directive can be used to include static resources where the frequent
updations are not available.
<jsp:include> action tag can be used to include dynamic resources where the frequent
updations are available.
3. In general directives will be resolved at the time of translation and actions will be
resolved at the time of request processing. Due to this reason include directive will be
resolved at the time of translation but <jsp:include> action tag will be resolved at the time
of request processing.
If we are trying to include a target Jsp page into present Jsp page by using include
directive then container will prepare only one translated servlet.
To include a target Jsp page into the present Jsp page if we use <jsp:include> action tag
then container will prepare 2 separate translated servlets.
In Jsp applications, include directives will provide static inclusion, but <jsp:include>
action tag will provide dynamic inclusion.
In Jsp technology, <jsp:include> action tag was designed on the basis of Include
Request Dispatching Mechanism.
Where page attribute will take the name and location of the target resource to include its
response.
Where flush is a boolean attribute, it can be used to give an intimation to the container
about to autoFlush or not to autoFlush dynamic response to client when JspWriter buffer
filled with the response at the time of including the target resource response into the
present Jsp page.
220 | P a g e
Ratanit Adv.Java Mr. Ratan
Add.jsp:-
<%@page import="java.sql.*"%>
<%!
String pid;
String pname;
int pcost;
static Connection con;
static Statement st;
ResultSet rs;
ResultSetMetaData rsmd;
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "ratan");
st=con.createStatement();
}
catch(Exception e){
e.printStackTrace();
}
}
%>
<% pid=request.getParameter("pid");
pname=request.getParameter("pname");
pcost=Integer.parseInt(request.getParameter("pcost"));
st.executeUpdate("insert into product values('"+pid+"','"+pname+"',"+pcost+")");
out.println("values are inserted successfully");
%>
<jsp:include page="form.html"/>
221 | P a g e
Ratanit Adv.Java Mr. Ratan
Include Directive:-
1) It is used to include the target jsp page into present jsp page.
2) Include directive include the target page data into present jsp file at translation time(jsp-servlet).
3) If any modification done in jsp file will not be visible until jsp file compiles again.
4) Include directive is static import.
5) It is better for static pages, if we are using for dynamic pages for every change it requires translation.
6) By using include directive we are unable to pass parameters to target page.
Syntax:- <%@ include file="file_name" %>
Example:- <%@ include file="hello.jsp" %>
Include Action:-
1) It is used to include the target jsp into present jsp page.
2) The content of the target jsp included at runtime instead of translation time.
3) If you done the modifications these are effected when we send the request to jsp.
4) Include action is dynamic import.
5) Instead of including original data it is calling include method at runtime.
6) By using include action we are able to pass parameters to the included page.
<jsp:include page="file_name" />
<jsp:param name="parameter_name" value="parameter_value" />
</jsp:include>
Syntax:- <jsp:include page="file_name" />
Example:- <jsp:include page="hello.jsp"/>
main.jsp:-
<%@ page language="java" contentType="text/html" %>
<html>
<body>
This is info about main.jsp file<br><br><br>
<jsp:include page="hello.jsp">
<jsp:param name="a" value="10"/>
</jsp:include>
</body>
</html>
hello.jsp:-
<%@ page language="java" contentType="text/html" %>
<%@page import="java.util.*"%>
<html>
<head>
<body>
hi this is hello.jsp file content<br>
welcome to Sravyainfotech<br>
<%="Today date ="+new Date()%><br>
<%="param tag value="+request.getParameter("a")%>
</body>
</html>
222 | P a g e
Ratanit Adv.Java Mr. Ratan
5. <jsp:forward>:
Ans: 1. <jsp:include> action tag can be used to include the target resource response into
the present Jsp page.
<jsp:forward> tag can be used to forward request from present Jsp page to the target
resource.
2. <jsp:include> tag was designed on the basis of Include Request Dispatching Mechanism.
<jsp:forward> tag was designed on the basis of Forward Request Dispatching Mechanism.
3. When Jsp container encounter <jsp:include> tag then container will forward request to
the target resource, by executing the target resource some response will be generated in
the response object, at the end of the target resource container will bypass request and
response objects back to first resource, at the end of first resource execution container will
dispatch overall response to client. Therefore, in case of <jsp:include> tag client is able to
receive all the resources response which are participated in the present request processing.
When container encounters<jsp:forward> tag then container will bypass request and
response objects to the target resource by refreshing response object i.e. by eliminating
previous response available in response object, at the end of target resource container will
dispatch the generated dynamic response directly to the client without moving back to first
resource. Therefore, in case of <jsp:forward> tag client is able to receive only target
resource response.
Syntax:<jsp:forward page=”--”/>
Where page attribute specifies the name and location of the target resource.
<jsp:include>&<jsp:forward> :-
login.html
<html>
<body>
<form action="main.jsp">
<h5> *******Login Details*******</h5>
User name : <input type="text" name="uname"/><br>
Password : <input type="password" name=upwd/><br>
<input type="submit" value="login"/>
</form>
</body>
</html>
223 | P a g e
Ratanit Adv.Java Mr. Ratan
Main.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%! String uname;
String upwd;
%>
<%
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
if(uname.equals("sravya"))
{
%>
<jsp:forward page="success.jsp"/>
<%
}
else
{out.println("****U R Login is fail try with another username & password*******");
}%>
<jsp:include page="login.html"/>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
Hi this is Success jsp<br>
U r login is Success
</body>
</html>
6. <jsp:param>:
This action tag can be used to provide a name value pair to the request object at the
time of by passing request object from present Jsp page to target page either in include
mechanism or in forward mechanism or in both.
This tag must be utilized as a child tag to <jsp:include> tag and <jsp:forward> tags.
--------------Application4---------------
224 | P a g e
Ratanit Adv.Java Mr. Ratan
forwardapp:
registrationform.html:
<html>
<body bgcolor="lightgreen">
<form action="registration.jsp">
<pre>
<u>Registration Form</u>
Name : <input type="text" name="pname"/>
Age : <input type="text" name="uage"/>
Address : <input type="text" name="uaddr"/>
<input type="submit" value="Registration"/>
</pre>
</form>
</body>
</html>
existed.jsp:
<center><h1>User Existed</h1></center>
success.jsp:
<center><h1>Registration Success</h1></center>
failure.jsp:
<center><h1>Registration Failure</h1></center>
registration.jsp:
<%@page import="java.sql.*"%>
<%!
String uname;
int uage;
String uaddr;
static Connection con;
static Statement st;
ResultSet rs;
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"ratan");
st=con.createStatement();
}
catch(Exception e){
e.printStackTrace();
}
}
%>
225 | P a g e
Ratanit Adv.Java Mr. Ratan
<%
try{
uname=request.getParameter("uname");
uage=Integer.parseInt(request.getParameter("uage"));
uaddr=request.getParameter("uaddr");
rs=st.executeQuery("select * from reg_users where uname='"+uname+"'");
boolean b=rs.next();
if(b==true)
{
%>
<jsp:forward page="existed.jsp"/>
<%
}
else
{
int rowCount=st.executeUpdate("insert into reg_users values
('"+uname+"',"+uage+",'"+uaddr+"')");
if(rowCount == 1)
{
%>
<jsp:forward page="success.jsp"/>
<%
}
else
{
%>
<jsp:forward page="failure.jsp"/>
<%
}
}
}
catch(Exception e){
%>
<jsp:forward page="failure.jsp"/>
<%
e.printStackTrace();
}
%>
7. <jsp:plugin>:
This tag can be used to include an applet into the present Jsp page.
Where code attribute will take fully qualified name of the applet.
Where width and height attributes can be used to specify the size of applet.
Where type attribute can be used to specify which one we are going to include whether it
is applet or bean.
226 | P a g e
Ratanit Adv.Java Mr. Ratan
8. <jsp:params>:
In case of the applet applications, we are able to provide some parameters to the applet
in order to provide input data.
Similarly if we want to provide input parameters to the applet from <jsp:plugin> tag we
have to use <jsp:param> tag.
<jsp:param> tag must be utilized as a child tag to <jsp:params> tag.
<jsp:params> tag must be utilized as a child tag to <jsp:plugin> tag.
Syntax:
<jsp:plugin>
<jsp:params>
<jsp:param name=”--” value=”--”/>
<jsp:param name=”--” value=”--”/>
----------
</jsp:params>
----------
</jsp:plugin>
If we provide any input parameter to the applet then that parameter value we are able to
get by using the following method from Applet class.
public String getParameter(String name)
Ex:String msg=getParameter(“message”);
pluginapp:
LogoApplet.java:
import java.awt.*;
import java.applet.*;
public class LogoApplet extends Applet
{
String msg;
public void paint(Graphics g)
{
msg=getParameter("message");
Font f=new Font("arial",Font.BOLD,40);
g.setFont(f);
this.setBackground(Color.blue);
this.setForeground(Color.white);
g.drawString(msg,150,70);
}
}
logo.jsp:
<jsp:plugin code="LogoApplet" width="1000" height="150" type="applet">
<jsp:params>
<jsp:param name="message" value="ratan software solutions"/>
</jsp:params>
</jsp:plugin>
227 | P a g e
Ratanit Adv.Java Mr. Ratan
9. <jsp:fallback>:
The main purpose of <jsp:fallback> tag is to display an alternative message when client
browser is not supporting <OBJECT---> tag and <EMBED---> tag.
Syntax:<jsp:fallback>-------Description---------</jsp:fallback>
11. <jsp:scriptlet>:
This tag is almost all same as thescripting element scriptlets, it can be used to provide a block of Java
code in Jsp pages.
Syntax:<jsp:scriptlet>
--------
-------- Block of Java code
--------
</jsp:scriptlet>
12. <jsp:expression>:
This tag is almost all same as the scripting element expression, it can be used to provide a Java
expression in the present Jsp page.
Syntax:<jsp:expression> Java Expression </jsp:expression>
<%@page import="java.util.*"%>
<jsp:declaration>
Date d=null;
String date=null;
</jsp:declaration>
<jsp:scriptlet>
d=new Date();
date=d.toString();
</jsp:scriptlet>
<html>
<body bgcolor="lightyellow">
<center><b><font size="6" color="red"><br><br>
Today Date : <jsp:expression>date</jsp:expression>
</font></b></center></body>
</html>
228 | P a g e
Ratanit Adv.Java Mr. Ratan
2. Custom Actions:
In Jsp technology, by using Jsp directives we are able to define present Jsp page
characteristics, we are unable to use Jsp directives to perform actions in the Jsp pages.
To perform actions if we use scripting elements then we have to provide Java code inside
the Jsp pages.
The main theme of Jsp technology is not to allow Java code inside Jsp pages, to eliminate
Java code from Jsp pages we have to eliminate scripting elements.
If we want to eliminate scripting elements from Jsp pages we have to use actions.
1. Standard Actions
2. Custom Actions
Standard Actions are predefined actions provided by Jsp technology, these standard
actions are limited in number and having bounded functionalities so that standard actions
are not sufficient to satisfy the complete client requirement.
In this context, there may be a requirement to provide Java code inside the Jsp pages so
that to eliminate Java code completely from Jsp pages we have to use Custom Actions.
Custom Actions are Jsp Actions which could be prepared by the developers as per their
application requirements.
In Jsp technology, standard actions will be represented in the form of a set of predefined
tags are called as Action Tags.
Similarly all the custom actions will be represented in the form of a set of user defined tags
are called as Custom Tags.
To prepare custom tags in Jsp pages we have to use the following syntax.
Syntax:<prefix_Nmae:tag_Name>
--------
-------- Body
--------
</prefix_Name>
If we want to design custom tags in our Jsp applications then we have to use the
following 3 elements.
1. Jsp page with taglib directive
2. TLD(Tag Library Descriptor) file
3. TagHandler class
Where TagHandler class is a normal Java class it is able to provide the basic functionality
for the custom tags.
Where TLD file is a file, it will provide the mapping between custom tag names and
respective TagHandler classes.
229 | P a g e
Ratanit Adv.Java Mr. Ratan
Where taglib directive in the Jsp page can be used to make available the tld files into the
present Jsp page on the basis of custom tags prefix names.
Internal Flow:
When container encounters a custom tag container will pick up the custom tag name and
the respective prefix name then recognize a particular taglib directive on the basis of the
prefix attribute value.
After recognizing taglib directive container will pick up uri attribute value i.e. the name
and location of tld file then container will recognize the respective tld file.
After getting tld file container will identify the name and location of TagHandler class on
the basis of custom tag name.
When container recognize the respective TagHandler class .class file then container will
perform TagHandler class loading, instantiation and execute all the life cycle methods.
1. Taglib Directive:
In custom tags design, the main purpose of taglib directive is to make available the required
tld file into the present Jsp page and to define prefix names to the custom tags.
Where prefix attribute can be used to specify a prefix name to the custom tag, it will
have page scope i.e. the specified prefix name is valid up to the present Jsp page.
Where uri attribute will take the name and location of the respective tld file.
2. TLD File:
The main purpose of TLD file is to provide the mapping between custom tag names and
the respective TagHandler classes and it is able to manage the description of the custom
tags attributes.
To provide the mapping between custom tag names and the respective TagHandler class
we have to use the following tags.
<taglib>
<jsp-version>jsp version</jsp-version>
<tlib-version>tld file version</tlib-version>
<short-name>tld file short name</short-name>
<description>description about tld file</description>
<tag>
<name>custom tag name</name>
<tag-class>fully qualified name of TagHandler class</tag-class>
<body-content>jsp or empty</body-content>
<short-name>custom tag short name</short-name>
<description>description about custom tags</description>
</tag>
---------
</taglib>
230 | P a g e
Ratanit Adv.Java Mr. Ratan
3. TagHandler class:
In custom tags preparation, the main purpose of TagHandler class is to define the basic
functionality for the custom tags.
To design TagHandler classes in custom tags preparation Jsp API has provided some
predefined library in the form of javax.servlet.jsp.tagext package (tagext-tag extension).
JspTag(I)
extends extends
Tag(I) SimpleTag(I)
extends
As per the tag library provided by Jsp technology there are 2 types of custom tags.
1. Classic tags
2. Simple Tags
1. Classic Tags:
Classic Tags are the custom tags will be designed on the basis of Classic tag library provided
by Jsp API.
As per the classic tag library provided by Jsp API there are 3 types of classic tags.
Simple Classic Tags are the classic tags, which should not have body and attributes list.
231 | P a g e
Ratanit Adv.Java Mr. Ratan
To design simple classic tags the respective TagHandler class must implement Tag
interface either directly or indirectly.
Predefined support:-
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
public interface Tag extends JspTag
{ public abstract void setPageContext(PageContext pagecontext);
public abstract void setParent(Tag tag);
public abstract Tag getParent();
public abstract int doStartTag()throws JspException;
public abstract int doEndTag()throws JspException;
public abstract void release();
public static final int SKIP_BODY = 0;
public static final int EVAL_BODY_INCLUDE = 1;
public static final int SKIP_PAGE = 5;
public static final int EVAL_PAGE = 6;
}
Userdefined class:-
public class MyHandler extends Tag
{ //write the code here
}
Where the purpose of getParent() method is to return the parent tags TagHandler class
object from the TagHandler class.
After the custom tags start tag evaluating the custom tag body is completely depending
on the return value provided by doStartTag () method.
1. EVAL_BODY_INCLUDE
2. SKIP_BODY
If doStartTag() method returns SKIP_BODY constant then container will skip the custom
tag body and encounter end tag.
232 | P a g e
Ratanit Adv.Java Mr. Ratan
Evaluating the remaining the Jsp page after the custom tag or not is completely
depending on the return value provided by doEndTag() method.
1. EVAL_PAGE
2. SKIP_PAGE
If doEndTag() method returns EVAL_PAGE constant then container will evaluate the
remaining Jsp page.
If doEndTag() method returns SKIP_PAGE constant then container will not evaluate the
remaining Jsp page.
233 | P a g e
Ratanit Adv.Java Mr. Ratan
setPageContext(_)
setParent(_)
getParent()
doStartTag() EVAL_BODY_INCLUDE
Evaluate Body
SKIP_BODY
EVAL_PAGE
doEndTag()
Evaluate Page
SKIP_PAGE
release()
Note:In Tag interface life cycle, container will execute getParent() method when the
present custom tag is child tag to a particular parent tag otherwise container will not
execute getParent() method.
234 | P a g e
Ratanit Adv.Java Mr. Ratan
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.tcs.Customtag</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>
Customtag.java:-
package com.tcs;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
publicclass Customtag implements Tag{
PageContext context;
publicint doEndTag() throws JspException {
System.out.println("doEndTag method");
returnSKIP_PAGE;
}
publicint doStartTag() throws JspException {
JspWriter writer = context.getOut();
try {
writer.println("this is custom tag application by Ratan");
writer.print("<br>");
} catch (IOException e) {
e.printStackTrace();
}
returnEVAL_BODY_INCLUDE;
}
235 | P a g e
Ratanit Adv.Java Mr. Ratan
Observations :-
returnEVAL_BODY_INCLUDE;returnSKIP_PAGE;
returnSKIP_BODY;returnSKIP_PAGE;
returnEVAL_BODY_INCLUDE; returnEVAL_PAGE;
returnEVAL_BODY_INCLUDE; returnSKIP_PAGE;
236 | P a g e
Ratanit Adv.Java Mr. Ratan
return 5; return 1;
Note: To compile above code we need to set the classpath environment variable to the location
of jsp-api.jar file.
Observations:
Case 1: In the above application, if we provide <body-content> type is empty in the tld file and if we
provide body to the custom tag then container will raise an Exception like
237 | P a g e
Ratanit Adv.Java Mr. Ratan
<taglib>
************
<tag>
*******
<attribute>
<name>attribute_name</name>
<required>true/false</required>
<rtexprvalue>true/false</rtexprvalue>
</attribute>
</tag>
</taglib>
Where <attribute> tag can be used to represent a single attribute in the tld file.
Where <name> tag will take attribute name.
Where <required> tag is a boolean tag, it can be used to specify whether the attribute is mandatory or
optional.
Where <rtexprvalue> tag can be used to specify whether the attribute accept runtime values or not.
Step 3: Declare a property and setter method in TagHandler class with the same name of the attribute
defined in custom tag.
public class MyHandler implements Tag {
private String name;
public void setName(String name) {
this.name=name;
}
*****************
}
238 | P a g e
Ratanit Adv.Java Mr. Ratan
2. Iterator Tags:
Iterator tags are the custom tags, it will allow to evaluate custom tag body repeatedly.
If we want to prepare iterator tags the respective TagHandler class must implement
javax.servlet.jsp.tagext.IterationTag interface.
Predefined support:-
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
public interface IterationTag extends Tag
{
public abstract int doAfterBody()throws JspException;
public static final int EVAL_BODY_AGAIN = 2;
}
Userdefined class:-
class MyHandler implements IterationTag
{ //write the body here
}
After evaluating the custom tag body in case of iterator tags, container will access doAfterBody()
method.
In the above context, evaluating the custom tag body again or not is completely depending on the
return value which we are going to return from doAfterBody() method.
1) EVAL_BODY_AGAIN
If we return EVAL_BODY_AGAIN constant from doAfterBody() method then container
will execute the custom tag body again.
2) SKIP_BODY
If we return SKIP_BODY constant from doAfterBody() method then container will skip
out custom tag body evaluation and encounter end tag of the custom tag.
239 | P a g e
Ratanit Adv.Java Mr. Ratan
setPageContext(_)
setParent(_)
getParent()
doStartTag() EVAL_BODY_INCLUDE
EVAL_BODY_AGAIN
SKIP_BODY
doAfterBody()
EVAL_PAGE
doEndTag()
Evaluate Page
SKIP_PAGE
release()
If we want to design custom tagsby using above approach then the respective
TagHandler class must implement Tag interface and IterationTag interface i.e. we must
provide the implementation for all the methods which are declared in Tag and IterationTag
interfaces in our TagHandler class.
This approach will increase burden to the developers and unnecessary methods in
TgaHandler classes.
240 | P a g e
Ratanit Adv.Java Mr. Ratan
To overcome the above problem Jsp API has provided an alternative in the form of
TagSupport class.
TagSupport is a concrete class, which was implemented Tag and IterationTag interfaces
with the default implementation.
If we want to prepare custom tags with the TagSupport class then we have to take an
user defined class, which must be a subclass to TagSupport class.
Predefined support:-
public interface TagSupport implements IterationTag {
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public PageContext pageContext;
public Tag t;
public void setPageContext(PageContext pageContext) {
this.pageContext=pageContext;
}
public void setParent(Tag t) {
this.t=t;
public Tag getParent() {
return t;
}
public int doStartTag()throws JspException {
return SKIP_BODY;
}
public int doAfterBody()throws JspException {
return SKIP_BODY;
}
public int doEndTag()throws JspException {
return EVAL_PAGE;
}
public void release() { }
}
User defined class:-
public class MyHandler implements TagSupport
{
}
241 | P a g e
Ratanit Adv.Java Mr. Ratan
Application:-
hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:iterate times="10"><br>
Hi Ratan how r u
</mytags:iterate>
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>iterate</name>
<tag-class>com.sravya.Iteration</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>times</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Iteration.java:-
package com.sravya;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
publicclass Iteration extends TagSupport{
privateint times;
privateint count=1;
publicvoid setTimes(int times) {
this.times = times;
}
@Override
publicint doAfterBody() throws JspException {
if(count<times)
{ count++;
returnEVAL_BODY_AGAIN;
}
else
{ returnSKIP_BODY;
}
}
@Override
publicint doStartTag() throws JspException {
returnEVAL_BODY_INCLUDE;
}
}
242 | P a g e
Ratanit Adv.Java Mr. Ratan
Application:-
Hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:loop start="1" end="20"><br>
Hi Ratan how r u
</mytags:loop>
remaining page of the JSP
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>loop</name>
<tag-class>com.sravya.Iteration</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>start</name>
<required>true</required>
</attribute>
<attribute>
<name>end</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Iteration.jsp:-
package com.sravya;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
publicclass Iteration extends TagSupport{
privateint start;
privateint end;
publicvoid setStart(int start) {
this.start = start; }
publicvoid setEnd(int end) {
this.end = end; }
@Override
publicint doAfterBody() throws JspException {
if(end>start)
{ start++;
returnEVAL_BODY_AGAIN; }
else
{ returnEVAL_PAGE; }
}
@Override
publicint doStartTag() throws JspException {
returnEVAL_BODY_INCLUDE; }
}
243 | P a g e
Ratanit Adv.Java Mr. Ratan
Nested Tags:-
Defining a tag inside a tag is called as Nested Tag.
In custom tags application, if we declare any nested tag then we have to provide a separate
configuration in tld file and we have to prepare a separate TagHandler class under classes folder.
hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:if condition='<%=10<20%>'>
<mytags:true>condition is true</mytags:true><br>
<mytags:false>condition is false</mytags:false><br>
</mytags:if>
rest of the JSP code
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>if</name>
<tag-class>com.sravya.If</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>condition</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>true</name>
<tag-class>com.sravya.True</tag-class>
<body-content>jsp</body-content>
</tag>
<tag>
<name>false</name>
<tag-class>com.sravya.False</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>
244 | P a g e
Ratanit Adv.Java Mr. Ratan
If.java:-
package com.sravya;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
publicclassIfextends TagSupport{
privateboolean condition;
publicvoid setCondition(boolean condition) {
this.condition = condition;
}
publicboolean getCondition()
{ return condition;
}
@Override
publicint doStartTag() throws JspException {
returnEVAL_BODY_INCLUDE;
}
@Override
publicint doEndTag() throws JspException {
returnEVAL_PAGE;
}
}
True.java:-
package com.sravya;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
publicclass True extends TagSupport {
@Override
publicint doStartTag() throws JspException {
If f = (If)getParent();
boolean b = f.getCondition();
if(b==true)
{ returnEVAL_BODY_INCLUDE;
}
else {
returnSKIP_BODY;
}
}
}
245 | P a g e
Ratanit Adv.Java Mr. Ratan
False.java:-
package com.sravya;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
publicclassFalseextends TagSupport {
@Override
publicint doStartTag() throws JspException {
If f = (If)getParent();
boolean b = f.getCondition();
if(b==true)
{ returnSKIP_BODY;
}
else
{ returnEVAL_BODY_INCLUDE;
}
}
}
empdetails.jsp:
emp.tld:
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>empDetails</name>
<tag-class>com.dss.EmpDetails</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
EmpDetails.java:
package com.dss;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class EmpDetails extends TagSupport
{
Connection con;
Statement st;
ResultSet rs;
public EmpDetails()
{
try
246 | P a g e
Ratanit Adv.Java Mr. Ratan
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","
ratan");
st=con.createStatement();
}
catch (Exception e)
{
e.printStackTrace();
}
}
247 | P a g e
Ratanit Adv.Java Mr. Ratan
3. Body Tags:
Up to now in our custom tags (simple classic tags, iteration tags) we prepared custom tags with the
body, where we did not perform updations over the custom tag body, just we scanned custom tag
body and displayed on the client browser.
If we want to perform updations over the custom tag body then we have to use Body Tags.
If we want to design body tags in Jsp technology then the respective TagHandler class must
implement BodyTag interface either directly or indirectly.
BodyTag:-
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
public interface BodyTag extends IterationTag
{public abstract void setBodyContent(BodyContent bodycontent);
public abstract void doInitBody()throws JspException;
public static final int EVAL_BODY_TAG = 2;
public static final int EVAL_BODY_BUFFERED = 2;}
All methods at inherited level:-
public interface BodyTag extends IterationTag
{ public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public static final int EVAL_BODY_BUFFERED;
public void setPageContext(PageContext pageContext);
public void setParent(Tag t);
public Tag getParent();
public int doStartTag()throws JspException;
public void doInitBody()throws JspException;
public void setBodyContent(BodyContent bodyContent);
public int doAfterBody()throws JspException;
public int doEndTag()throws JspException;
public void release(); }
User defined class:-
public class MyHandler implements BodyTag
{ //write the logics here; }
In case of body tags, there are 3 possible return values from doStartTag() method.
a) EVAL_BODY INCLUDE
If we return EVAL_BODY_INCLUDE constant from doStartTag() method then container will
evaluate the custom tag body i.e. display as it is the custom tag body on client browser.
b) SKIP_BODY
If we return SKIP_BODY constant from doStartTag() method then container will skip the custom
tag body.
c) EVAL_BODY_BUFFERED
If we return EVAL_BODY_BUFFERED constant from doStartTag() methodthen container will store
custom tag body in a buffer then access setBodyContent(_) method.
To access setBodyContent(_) method container will prepare BodyContent object with the buffer.
After executing setBodyContent(_) method container will access doInitBody() method in order to
prepare BodyContent object for allow modifications.
248 | P a g e
Ratanit Adv.Java Mr. Ratan
setPageContext(_)
setParent(_)
set-----()
getParent()
SKIP_BODY EVAL_BODY_AGAIN
doInitBody() SKIP_BODY
doAfterBody()
EVAL_BODY_
INCLUDE SKIP_BODY
doAfterBody()
EVAL_PAGE
doEndTag()
Evaluate Page
SKIP_PAGE
release()
249 | P a g e
Ratanit Adv.Java Mr. Ratan
To prepare custom tags if we use above approach then the respective TagHandler class must
implement all the methods declared in BodyTag interface irrespective of the application
requirement.
This approach may increase burden to the developers and unnecessary methods in the custom tag
application.
To overcome this problem we will use an alternative provided by Jsp technology i.e.
javax.servlet.jsp.tagext.BodyTagSupport class.
BodyTagSupport class is a concrete class, a direct implementation class to BodyTag interface and it
has provided the default implementation for all the methods declared in BodyTag interface.
If we want to prepare custom tags with BodyTagSupport class then the respective TagHandler class must
extend BodyTagSupport and overrides the only required methods.
public class BodyTagSupport implements BodyTag {
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public static final int EVAL_BODY_BUFFERED;
public PageContext pageContext;
public Tag t;
public BodyContent bodyContent;
public void setPageContext(PageContext pageContext) {
this.pageContext=pageContext;
}
public void setParent(Tag t) {
this.t=t;
}
public Tag getParent() {
return t;
}
public int doStartTag()throws JspException {
return EVAL_BODY_BUFFERED;
}
public void setBodyContent(BodyContent bodyContent) {
this.bodyContent=bodyContent;
}
public void doInitBody()throws JspException
{ }
public int doAfterBody()throws JspException {
return SKIP_BODY;
}
public int doEndTag()throws JspException {
return EVAL_PAGE; }
public void release() { }
}
250 | P a g e
Ratanit Adv.Java Mr. Ratan
In case of body tags, custom tag body will be available in BodyContent object, to get custom tag
body from BodyContent object we have to use the following method.
public String getString()
To send modified data to the response object we have to get JspWriter object from BodyContent,
for this we have to use the following method.
public JspWriter getEnclosingWriter()
Application:-
hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:reverse>
Sravya Infotech
</mytags:reverse>
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>reverse</name>
<tag-class>com.sravya.Reverse</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>
Reverse.java:-
package com.sravya;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
publicclass Reverse extends BodyTagSupport{
publicint doEndTag()throws JspException
{ try
{ String data=bodyContent.getString();
StringBuffer sb=new StringBuffer(data);
StringBuffer rdata=sb.reverse();
bodyContent.getEnclosingWriter().println(rdata);
}
catch(Exception e)
{
e.printStackTrace();
}
returnEVAL_PAGE;
}
}
251 | P a g e
Ratanit Adv.Java Mr. Ratan
--------------Application11--------------
custapp6:
editor.html:
<html>
<body bgcolor="lightgreen">
<b><font size="6" color="red">
<form action="./result.jsp">
<pre>
Enter SQL Query
<textarea name="query" rows="5" cols="50"></textarea>
<input type="submit" value="GetResult"/>
</pre>
</form></font></b></body>
</html>
result.jsp:
result.tld:
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>query</name>
<tag-class>com.dss.Result</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>
252 | P a g e
Ratanit Adv.Java Mr. Ratan
Result.java:
package com.dss;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class Result extends BodyTagSupport
{
Connection con;
Statement st;
ResultSet rs;
public Result()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","
ratan");
st=con.createStatement();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public int doEndTag() throws JspException
{
try
{
JspWriter out=pageContext.getOut();
String query=bodyContent.getString();
boolean b=st.execute(query);
if (b==true)
{
rs=st.getResultSet();
ResultSetMetaData rsmd=rs.getMetaData();
out.println("<html>");
out.println("<body bgcolor='lightblue'>");
out.println("<center><br><br>");
out.println("<table border='1' bgcolor='lightyellow'>");
int count=rsmd.getColumnCount();
out.println("<tr>");
for (int i=1;i<=count;i++)
{
out.println("<td><center><b><font size='6'
color='red'>"+rsmd.getColumnName(i)+"</font></b></center></td>");
}
out.println("</tr>");
while (rs.next())
{
out.println("<tr>");
for (int i=1;i<=count;i++)
253 | P a g e
Ratanit Adv.Java Mr. Ratan
out.println("<td><h1>"+rs.getString(i)+"</h1></td>");
}
out.println("</tr>");
}
out.println("</table></center></body></html>");
}
else
{
int rowCount=st.getUpdateCount();
out.println("<html>");
out.println("<body bgcolor='lightyellow'>");
out.println("<center><b><font size='7' color='red'>");
out.println("<br><br>");
out.println("Record Updated : "+rowCount);
out.println("</font></b></center></body></html>");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return EVAL_PAGE;
}
}
254 | P a g e
Ratanit Adv.Java Mr. Ratan
2. Simple Tags:
Classic tags Vs Simple tags:-
Classic tags are more API independent, but Simple tags are less API independent.
If we want to design custom tags by using classic tag library then we have to remember 3 types of
life cycles.
If we want to design custom tags by using simple tag library then we have to remember only 1 type of
life cycle.
In case of classic tag library, all the TagHandler class objects are cacheable objects, but in case of
simple tag library, all the TagHandler class objects are non-cacheable objects.
In case of classic tags, all the custom tags are not body tags by default, but in case of simple tags, all
the custom tags are having body tags capacity by default.
If we want to design custom tags by using simple tag library then the respective TagHandler class must
implement SimpleTag interface either directly or indirectly.
Predefind support:-
package javax.servlet.jsp.tagext;
import java.io.IOException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
public interface SimpleTag extends JspTag
{ public abstract void doTag()throws JspException, IOException;
public abstract void setParent(JspTag jsptag);
public abstract JspTag getParent();
public abstract void setJspContext(JspContext jspcontext);
public abstract void setJspBody(JspFragment jspfragment);
}
User defined class:-
public class MyHandler implements SimpleTag
{ //write the logics here
}
Where jspContext is an implicit object available in simple tag library, it is same as pageContext, it can
be used to make available all the Jsp implicit objects.
Where jspFragment is like bodyContent in classic tag library, it will accommodate custom tag body
directly.
Where setJspContext(_) method can be used to inject JspContext object into the present web
application.
Where setParent(_) method can be used to inject parent tags TagHandler class object reference into
the present TagHandler class.
Where getParent() method can be used to get parent tags TagHandler class object.
255 | P a g e
Ratanit Adv.Java Mr. Ratan
setJspContext(_)
setParent(_)
getParent()
setJspBody(_)
doTag()
X
To design custom tags if we use approach then the respective TgaHandler class must implement
SimpleTag interface i.e. it must implement all the methods which are declared in SimpleTag
interface.
This approach will increase burden to the developers and unnecessary methods in the custom tags.
To overcome the above problem Jsp technology has provided an alternative in the form of
javax.servlet.jsp.tagext.SimpleTagSupport class.
SimpleTagSupport is a concrete class provided by Jsp technology as an implementation class to
SimpleTag interface with default implementation.
If we want to design custom tags by using SimpleTagSupport class then the respective TagHandler
class must be extended from SimpleTagSupport class and where we have to override the required
methods.
Predefined support:-
public interface SimpleTag extends JspTag {
private JspContext jspContext;
private JspFragment jspFragment;
private JspTag jspTag;
public void setJspContext(JspContext jspContext) {
this.jspContext=jspContext;
}
public void setParent(JspTag t) {
this.jspTag=jspTag;
}
public void setJspBody(JspFragment jspFragment) {
this.jspFragment=jspFragment;
}
public JspTag getParent() {
return jspTag;
}
256 | P a g e
Ratanit Adv.Java Mr. Ratan
Application:
hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello/>
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.sravya.Hello</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Hello.java:-
package com.sravya;
import java.io.IOException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
publicclass Hello extends SimpleTagSupport{
@Override
publicvoid doTag() throws JspException, IOException {
JspContext context = getJspContext();
JspWriter writer = context.getOut();
writer.println("this is Sample Tag application");
}
}
257 | P a g e
Ratanit Adv.Java Mr. Ratan
Application:-
hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello>
hi this is body of custom tag<br>
</mytags:hello>
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.sravya.Hello</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
Hello.java:-
package com.sravya;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
publicclass Hello extends SimpleTagSupport{
@Override
publicvoid doTag() throws JspException, IOException {
JspWriter writer = getJspContext().getOut();
StringWriter stringWriter = new StringWriter();
getJspBody().invoke(stringWriter);
writer.println("this is Sample Tag application");
writer.println(stringWriter.toString());
}
}
258 | P a g e
Ratanit Adv.Java Mr. Ratan
Application:-
hello.jsp:-
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello msg="ratansoft">
hi this is body of custom tag<br>
</mytags:hello>
hello.tld:-
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.sravya.Hello</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>msg</name>
</attribute>
</tag>
</taglib>
Hello.java:-
package com.sravya;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
publicclass Hello extends SimpleTagSupport{
private String msg;
publicvoid setMsg(String msg) {
this.msg = msg;
}
@Override
publicvoid doTag() throws JspException, IOException {
JspWriter writer = getJspContext().getOut();
259 | P a g e
Ratanit Adv.Java Mr. Ratan
TaglibUri.java:-
package com.sravya;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
publicclass TaglibUri extends TagSupport{
@Override
publicint doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
try {
Date d = new Date();
writer.println("this is custom tag application URI attribute");
writer.println("<br/>");
writer.println("today date is="+d);
260 | P a g e
Ratanit Adv.Java Mr. Ratan
writer.println("<br/>");
} catch (IOException e) {
e.printStackTrace();
}
returnEVAL_BODY_INCLUDE;
}
@Override
publicint doEndTag() throws JspException {
returnEVAL_PAGE;
}
}
261 | P a g e
Ratanit Adv.Java Mr. Ratan
In Jsp technology, by using scripting elements we are able to provide Java code inside
the Jsp pages.
To preserve Jsp principles we have to eliminate scripting elements, for this we have to
use Jsp Actions.
In the above context, to eliminate Java code completely from Jsp pages we have to use
custom actions.
In case of custom actions, to implement simple Java syntaxes like if condition, for loop
and so on we have to provide a lot of Java code internally.
To overcome the above problem Jsp technology has provided a separate tag library with
simple Java syntaxes implementation and frequently used operations.
With the above convention Apache Tomcat has provided JSTL implementation in the form
of the jar files as standard.jar, jstl.jar.
Apache Tomcat has provided the above 2 jar files in the following location.
C:\Tomcat7.0\webapps\examples\WEB_INF\lib
If we want to get JSTL support in our Jsp pages then we have to keep the above 2 jar
files in our web application lib folder.
JSTL has provided the complete tag library in the form of the following 5 types of tags.
1. Core Tags
2. XML Tags
3. Internationalization or I18N Tags (Formatted tags)
4. SQL Tags
5. Functions tags
To get a particular tag library support into the present Jsp page we have to use the
following standard URL’s to the attribute in the respective taglib directive.
http://java.sun.com/jstl/core
http://java.sun.com/jstl/xml
http://java.sun.com/jstl/fmt
http://java.sun.com/jstl/sql
http://java.sun.com/jsp/jstl/functions
262 | P a g e
Ratanit Adv.Java Mr. Ratan
1. Core Tags:
In JSTL, core tag library was divided into the following 4 types.
1. <c:set----->:
This tag can be used to declare a single name value pair onto the specified scope.
Where var attribute will take a variable i.e. key in key-value pair.
Where value attribute will take a particular value i.e. a value in key-value pair.
Where scope attribute will take a particular scope to include the specified key-value pair.
2. <c:out----->:
This tag can be used to display a particular value on the client browser.
Syntax:<c:out value=”--”/>
To present an expression with value attribute we have to use the following format.
Syntax:${expression}
Ex:<c:out value”${a}”/>
If the container encounters above tag then container will search for ‘a’ attribute in the
page scope, request scope, session scope and application scope.
263 | P a g e
Ratanit Adv.Java Mr. Ratan
--------------Application13--------------
jstlapp1:
core.jsp:
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:set var="a" value="AAA" scope="request"/>
<br>
<c:out value="core tag library"/>
<br><br>
<c:out value="${a}"/>
</font></b></center>
<body>
<html>
3. <c:remove----->:
This tag can be used to remove an attribute from the specified scope.
Where scope attribute is optional, if we have not specified scope attribute then container
will search for the respective attribute in the page scope, request scope, session scope and
application scope.
--------------Application14--------------
core1.jsp:
264 | P a g e
Ratanit Adv.Java Mr. Ratan
4. <c:catch----->:
This tag can be used to catch an Exception raised in its body.
Syntax:<c:catch var=”--”>
---------- </c:catch>
Where var attribute will take a variable to hold the generated Exception object reference.
--------------Application15--------------
core2.jsp:
2. Conditional Tags:
Syntax:<c:if test=”--”/> Where test attribute is a boolean attribute, it may take either true or false
values.--------------Application16--------------
core3.jsp:
265 | P a g e
Ratanit Adv.Java Mr. Ratan
Syntax:<c:choose>
<c:when test=”--”>
-----------
</c:when>
-----------
<c:otherwise>
-----------
</c:otherwise>
</c:choose>
--------------Application17--------------
core4.jsp:
3. Iterator Tags:
1. <c:forEach----->:
This tag can be used to implement for loop to provide iterations on its body and it can be
used to perform iterations over an array of elements or Collection of elements.
266 | P a g e
Ratanit Adv.Java Mr. Ratan
------------
</c:forEach>
Where var attribute will take a variable to hold up the loop index value at each and every
iteration.
Where begin and end attribute will take start index value and end index value.
------------
</c:forEach>
Where var attribute will take a variable to hold up an element from the respective
Collection at each and every iteration.
Where items attribute will take the reference of an array or Collection from either of the
scopes page, request, session and application.
--------------Application18--------------
core5.jsp:
267 | P a g e
Ratanit Adv.Java Mr. Ratan
2. <c:forTokens----->:
------------
</c:forTokens>
Where var attribute will take a variable to hold up token at each and every iteration.
--------------Application19--------------
core6.jsp:
4. Url-Based Tags:
1. <c:import----->:
This tag can be used to import the content of the specified target resource into the
present Jsp page.
268 | P a g e
Ratanit Adv.Java Mr. Ratan
--------------Application20--------------
second.jsp:
<center><h1>This is second.jsp</h1></center>
core7.jsp:
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
Start
<br>
<c:import url="second.jsp"/>
<br>
End
</font></b></center>
<body>
<html>
2. <c:url----->:
--------------Application21--------------
core8.jsp:
269 | P a g e
Ratanit Adv.Java Mr. Ratan
2. <c:redirect----->:
This tag can be used to implement Send Redirect Mechanism from a particular Jsp page.
Syntax:<c:redirect url=”--”/>
--------------Application22--------------
core9.jsp:
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:redirect url="http://localhost:2020/registrationapp"/>
</font></b></center>
<body>
<html>
4. SQL Tags:
The main purpose of SQL tag library is to interact with the database in order to perform
the basic database operations.
JSTL has provided the following set of tags as part of SQL tag library.
1. <sql:setDataSource----->
2. <sql:update----->
3. <sql:query----->
4. <sql:transaction----->
5. <sql:param----->
6. <sql:dateParam----->
1. <sql:setDataSource----->:
This tag can be used to prepare the Jdbc environment like Driver loading, establish the
connection.
Where driver attribute will take the respective Driver class name.
Where user and password attributes will take database user name and password.
270 | P a g e
Ratanit Adv.Java Mr. Ratan
2. <sql:update----->:
This tag can be used to execute all the updation group SQL queries like create, insert,
update, delete, drop and alter.
In the above <sql:update> tag we are able to provide the SQL queries in 2 ways.
1. Statement style SQL queries, which should not have positional parameters.
2. PreparedStatement style SQL queries, which should have positional parameters.
If we use PreparedStatement style SQL queries then we have to provide values to the
positional parameters, for this we have to use the following SQL tags.
1. <sql:param----->:
This tag can be used to set a normal value to the positional parameter.
2. <sql:dateParam----->:
Syntax 2:<sql:dateParam>value</sql:dateParam>
--------------Application23--------------
jstlapp2:
sql.jsp:
271 | P a g e
Ratanit Adv.Java Mr. Ratan
--------------Application24--------------
sql1.jsp:
--------------Application25--------------
sql2.jsp:
272 | P a g e
Ratanit Adv.Java Mr. Ratan
--------------Application26--------------
sql3.jsp:
</font></b></center></body>
</html>
--------------Application27--------------
sql4.jsp:
273 | P a g e
Ratanit Adv.Java Mr. Ratan
3. <sql:query----->:
This tag can be used to execute selection group SQL queries in order to fetch the data from database
table.
Syntax 1:<sql:query var=”--” sql=”--”/>
If we execute selection group SQL queries by using <sql:query> tag then SQL tag library
will prepare result object to hold up fetched data.
In result object, all the column names will be represented in the form a single dimensional
array referred by columnNames predefined variable and column data (table body) will be
represented in the form of 2-dimensionnal array referred by rowsByIndex predefined
variable.
sql5.jsp:
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe" user="system" password="ratan"/>
<sql:query var="result" sql="select * from emp"/>
<table border="1" bgcolor="lightyellow">
<tr>
<c:forEach var="columnName"
items="${result.columnNames}">
<td><center><b><font size="6" color="red">
<c:out value="${columnName}"/>
</font></b></center></td>
</c:forEach>
</tr>
<c:forEach var="row" items="${result.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><b><font size="5">
<c:out value="${column}"/>
</font></b></td>
</c:forEach>
</tr>
</c:forEach>
</table>
</font></b></center>
</body>
</html>
274 | P a g e
Ratanit Adv.Java Mr. Ratan
4. <sql:transaction----->:
This tag will represent a transaction, which includes collection of <sql:update> tags and
<sql:query> tags.
1. <fmt:setLocale----->:
Syntax:<fmt:setLocale value=”--”/>
Where value attribute will take Locale parameters like en_US, it_IT and so on.
2. <fmt:formatNumber----->:
This tag can be used to represent a number w.r.t the specified Locale.
Where var attribute will take a variable to hold up the formatted number.
3. <fmt:formatDate----->:
This tag can be used to format present system date w.r.t. a particular Locale.
Where var attribute will take a variable to hold up the formatted date.
4. <fmt:setBundle----->:
This tag can be used to prepare ResourceBundle object on the basis of a particular
properties file.
Where var attribute will take a variable to hold up ResourceBundle object reference.
Where basename attribute will take base name of the properties file.
5. <fmt:message----->:
This tag can be used to get the message from ResourceBundle object on the basis of
provided key.
Where key attribute will take key of the message defined in the respective properties file.
--------------Application29--------------
275 | P a g e
Ratanit Adv.Java Mr. Ratan
jstlapp3:
abc_en_US.properties:
#abc_en_US.properties
#-------------------------------
welcome=Welcome to US user
abc_it_IT.properties:
#abc_it_IT.properties
#-------------------------------
welcome=Welcome toe Italiano usereo
fmt.jsp:
276 | P a g e
Ratanit Adv.Java Mr. Ratan
JSTL Functions:
The main purpose of functions tag library is to perform all the String operations which are
defined in the String class.
${fn.length(a)}
${fn.concat(a, “Hyderabad”)}
${fn.toLowerCase(a)}
${fn.toUpperCase (a)}
${fn.contains(a, “Software”)}
${fn.startsWith(a, “Ratan”)}
${fn.endsWith(a, “Solutions”)}
${fn.substring(a, 4, 20)}
277 | P a g e