You are on page 1of 76

Index

1.0 Basics of Java


1.1 Introduction of Java
1.2 Application of java
1.3 Types of Java Applications
1.4 Editions of Java
1.5 History of Java
1.6 Java Software’s
1.7 How java code executes
1.8 OOPS
2.0 JDBC
2..1 Introduction of JDBC
2.2 JDBC Driver
2.3 Java Database Connectivity
2.4 Driver Manager class
2.5 Connection interface
2.6 Statement interface
2.8 Result Set interface
2.9 Prepared Statement interface
2.10 Result Set Meta Data Interface
2.11 Store image in Oracle database
2.12 Retrieve image from Oracle database
2.13 Store file in Oracle database
2.14 Retrieve file from Oracle database
2.15 Java Callable Statement Interface
2.16 Transaction Management in JDBC
2.17 Batch Processing in JDBC
2.18 JDBC Row Set
3.0 Servlet
3.1 Introduction of Servlets
3.2 Servlet API
3.3 Servlet Interface
3.4 Generic Servlet class
3.5 Http Servlet class
3.6 Life Cycle of a Servlet
3.7 Steps to create a servlet example
3.8 War File
4
3.9 welcome-file-list in web.xml
3.10 Servlet Request Interface
3.11 Request Dispatcher in Servlet
3.12 Send Redirect in servlet
3.13 Servlet Config Interface
3.14 Servlet Context Interface
3.15 Attribute in Servlet
3.16 Session Tracking in Servlets
3.17 Event and Listener in Servlet
3.18 Servlet Filter
3.19 CRUD in Servlet
4.0 JSP
4.1 Introduction of JSP
4.2 Lifecycle of a JSP Page
4.3 Creating a simple JSP Page
4.4 JSP API
4.5 JSP Page interface
4.6 Http JSP Page interface
4.7 JSP Scripting elements
4.7.1 JSP script let tag
4.7.2 JSP expression tag
4.7.3 JSP Declaration Tag
4.8 JSP Implicit
4.9 JSP directives
4.9.1 JSP page directive
4.9.2 JSP Include Directive
4.9.3 JSP Tag lib directive
4.10 Exception Handling in JSP
4.11 JSP Action Tags
4.12 jsp:setProperty and jsp: getProperty action tags
5.0 JSTL
5.1 Introduction of JSTL
5.2 JSTL Core Tags
5.3 JSTL Function Tags
5.4 JSTL Formatting tags
5.5 JSTL XML tags
5.6 JSTL SQL Tags

4
BASIC

4
1.1 Introduction of Java – Java is an object-oriented platform independent computer programming
language.

“Write once read anywhere.”

Java is platform independent programming language. It means that java program is written once and the
program is executed irrespective of operating system. Features of Java - The primary objective of Java
programming language creation was to make it portable, simple and secure programming language. Apart
from this, there are also some excellent features which play an important role in the popularity of this language.
The features of Java are also known as java buzzwords. A list of most important features of Java language is
given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

1.2 Application of java - According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics 8. Games, etc.

1.3 Types of Java Applications - There are mainly 4 types of applications that can be created using
Java programming:

1) Standalone Application - Standalone applications are also known as desktop applications or window-
based applications. These are traditional software that we need to install on every machine. Examples of
standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.

2) Web Application - An application that runs on the server side and creates a dynamic page is called a
web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for
creating web applications in Java.

3) Enterprise Application - An application that is distributed in nature, such as banking applications, etc.
is called enterprise application. It has advantages of the high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.

4
4) Mobile Application - An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.

Java Platforms / Editions

1.4 Editions of Java - There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition) - It is a Java programming platform. It includes Java programming APIs
such as java. Lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.

2) Java EE (Java Enterprise Edition) - It is an enterprise platform which is mainly used to develop web and
enterprise applications. It is built on the top of the Java SE platform. It includes topics like Servlet, JSP, Web
Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition) - It is a micro platform which is mainly used to develop mobile
applications.

4) JavaFX - It is used to develop rich internet applications. It uses a light-weight user interface API.

1.5 History of Java - The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the time. The history
of java starts with Green Team. Java team members (also known as Green Team), initiated this project to
develop a language for digital devices such as set-top boxes, televisions, etc. However, it was suited for
internet programming. Later, Java technology was incorporated by Netscape. The principles for creating Java
programming were "Simple, Robust, Portable, Platform independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-oriented, Interpreted and Dynamic".

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. There are
given the significant points that describe the history of Java.

1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
2. Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3. Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.
5. Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania, etc.
6. In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7. Why had they chosen java name for java language? The team gathered to choose a new name. The
suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something
that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to
spell and fun to say.
8. According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so
unique, most of the team members preferred Java than other names.
9. Java is an island of Indonesia where first coffee was produced (called java coffee).
10. Notice that Java is just a name, not an acronym.
11. Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

4
12. In 1995, Time magazine called Java one of the Ten Best Products of 1995.
13. JDK 1.0 released in(January 23, 1996).

Java Version History - Many java versions have been released till now. The current stable release of
Java is Java SE 11.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th March 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th March 2018)

1.6 Java Software’s –

JVM - JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent
because the configuration of each OS is different from each other. However, Java is platform independent.
There are three notions of the JVM: specification, implementation, and instance. The JVM performs the
following main tasks:
1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment

JRE - JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries +
other files that JVM uses at runtime.

JDK - JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms
released by Oracle Corporation:
1. Standard Edition Java Platform
2. Enterprise Edition Java Platform
3. Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to
complete the development of a Java Application.

4
1.7 How java code executes –

Source code (.java) compiler bytecode (.class) JVM 0101011100 OS

1.8 OOPS – It stands for Object oriented programming system. Opps is a technique to think software
system as in term of our real-world objects. Opps is a design philosophy. Object-oriented programming (OOP)
is a software programming model constructed around objects.

Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts. These concepts are
known as pillars of oops.

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
7. Message Passing

Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language. Smalltalk
is considered the first truly object-oriented programming language. The popular object-oriented languages are
Java, C#, PHP, Python, C++, etc.

Features of Opps -
1. Object
2. Class
3. Data Hiding and Encapsulation
4. Dynamic Binding
5. Message Passing
6. Inheritance
7. Polymorphism
8. Overloading

4
9. Reusability

Object - It is a basic unit of Object-Oriented Programming and represents the real life entities. An entity that
has state and behaviour is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or
logical. A typical Java program creates many objects, which as you know, interact by invoking methods. An
object consists of:

1. State - It is represented by attributes of an object. It also reflects the properties of an object.


2. Behaviour - It is represented by methods of an object. It also reflects the response of an object with
other objects.
3. Identity - It gives a unique name to an object and enables one object to interact with other objects.

If you compare the software object with a real-world object, they have very similar characteristics. Software
objects also have a state and a behaviour. A software object's state is stored in fields and behaviour is shown
via methods. So, in software development, methods operate on the internal state of an object and the object
to-object communication is done via methods.

Class - Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint
from which you can create an individual object. Class doesn't consume any space. A class is a group of objects
which have common properties. It is a template or blueprint from which objects are created. It is a logical
entity. It can't be physical. A class in Java can contain:

1. Methods
2. Constructors
3. Blocks
4. Nested class and interface

4
Inheritance - When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism - If one task is performed by different ways, it is known as polymorphism. For example:
to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc. In Java,
we use method overloading and method overriding to achieve polymorphism. Another example can be to
speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction - Hiding internal details and showing functionality is known as abstraction. For example,
phone call, we don't know the internal processing. In Java, we use abstract class and interface to achieve
abstraction.

Encapsulation - Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example - capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

4
JDBC

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

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

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the
X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list
of popular interfaces of JDBC API are given below:
1. Driver interface
2. Connection interface
3. Statement interface
4. Prepared Statement interface
5. Callable Statement interface
6. Result Set interface
7. ResultSetMetaData interface
8. Database Metadata interface
9. Row Set interface

A list of popular classes of JDBC API are given below:


1. Driver Manager class
2. Blob class
3. Clob class
4. Types class

Why Should We Use JDBC ?


Before JDBC, ODBC API was the database API to connect and execute the query with the database. But
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That
is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

4
2.2 JDBC Driver
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver

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

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

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


Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers
provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
1. easy to use.
2. can be easily connected to any database.
Disadvantages:
1. Performance degraded because JDBC method call is converted into the ODBC function calls.
2. The ODBC driver needs to be installed on the client machine.

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

4
Advantaxge:
1. performance upgraded than JDBC-ODBC bridge driver.

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

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

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

4
Disadvantages:

1. Network support is required on client machine.


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

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

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

Disadvantage:
1. Drivers depend on the Database.

2.3 Java Database Connectivity - There are 5 steps to connect any java application with the database
using JDBC. These steps are as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection

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

Syntax of forName() method

Class.forName("oracle.jdbc.driver.OracleDriver");

4
2) Create the connection object -
The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)

Example to establish connection with the Oracle database


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

3) Create the Statement object - The createStatement() method of Connection interface is used to
create statement. The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method


public Statement createStatement()throws SQLException

Example to create the statement object


Statement stmt=con.createStatement();

4) Execute the query - The executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

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

Syntax of close() method


public void close()throws SQLException

Example to close connection


con.close();

Java Database Connectivity with Oracle - To connect java application with the oracle database, we
need to follow 5 following steps. In this example, we are using Oracle 10g as the database. So we need to
know following information for the oracle database:

1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port

4
number and XE is the Oracle service name. You may get all these information from the tnsnames.ora
file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.

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

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

Example to Connect Java Application with Oracle database - In this example, we are connecting to an
Oracle database and getting data from emp table. Here, system and oracle are the username and password of
the Oracle database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. //step2 create the connection object
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10. //step3 create the statement object
11. Statement stmt=con.createStatement();
12. //step4 execute query
13. ResultSet rs=stmt.executeQuery("select * from emp");
14. while(rs.next())
15. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
16. //step5 close the connection object
17. con.close();
18. }catch(Exception e){ System.out.println(e);}
19. }
20. }
The above example will fetch all the records of emp table.

Load the jar file:

1) paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.

2) set classpath:

set the temporary classpath:


Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;

set the permanent classpath:


Go to environment variable then click on new tab. In variable name write classpath and in variable value
paste the path to ojdbc14.jar by appending ojdbc14.jar; as

4
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

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

Useful methods of DriverManager class

Method Description
1) public static void registerDriver(Driver is used to register the given driver with
driver): DriverManager.
2) public static void deregisterDriver(Driver is used to deregister the given driver (drop the
driver): driver from the list) with DriverManager.
3) public static Connection getConnection(String is used to establish the connection with the
url): specified url.
4) public static Connection getConnection(String is used to establish the connection with the
url,String userName,String password): specified url, username and password.

2.5 Connection interface - A Connection is the session between java application and database. The
Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of
Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface
provide many methods for transaction management like commit(), rollback() etc.

Commonly used methods of Connection interface:


1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object
that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.

2.6 Statement interface - The Statement interface provides methods to execute queries with the database.
The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

The important methods of Statement interface are as follows:


1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object
of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.

Example of Statement interface - Let’s see the simple example of Statement interface to insert, update and
delete the record.
1. import java.sql.*;

4
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");
6. Statement stmt=con.createStatement();
7. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
8. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
9. int result=stmt.executeUpdate("delete from emp765 where id=33");
10. System.out.println(result+" records affected");
11. con.close();
12. }}

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

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface


1) public boolean next(): is used to move the cursor to the one row next from the
current position.
2) public boolean previous(): is used to move the cursor to the one row previous from the
current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.

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

5) public boolean absolute(int row): is used to move the cursor to the specified row number in the
Result Set object.
6) public boolean relative(int row): is used to move the cursor to the relative row number in the
ResultSet object, it may be positive or negative.
7) public int getInt(int column Index): is used to return the data of specified column index of the
current row as int.
8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
10) public String getString(String is used to return the data of specified column name of the
columnName): current row as String

2.9 PreparedStatement interface - The PreparedStatement interface is a subinterface of Statement. It


is used to execute parameterized query.

Let's see the example of parameterized query:

1. String SQL="insert into emp values(?,?,?)";


4
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods
of PreparedStatement.

Why use Prepared Statement ?


Improves performance: The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.

How to get the instance of PreparedStatement?


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

Methods of PreparedStatement interface - The important methods of PreparedStatement interface


are given below:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter
index.
public void setString(int paramIndex, String sets the String value to the given parameter index.
value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an instance of
ResultSet.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

1. create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:


1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");
7. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
8. stmt.setInt(1,101);//1 specifies the first parameter in the query
9. stmt.setString(2,"Ratan");
10. int i=stmt.executeUpdate();
11. System.out.println(i+" records inserted");
12. con.close();
13. }catch(Exception e){ System.out.println(e);}

4
14. }
15. }

2.10 ResultSetMetaData Interface - The metadata means data about data i.e. we can get further
information from the data. If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.

Commonly used methods of ResultSetMetaData interface


Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

How to get the object of ResultSetMetaData:

public ResultSetMetaData getMetaData()throws SQLException

Example of ResultSetMetaData interface :


1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8. PreparedStatement ps=con.prepareStatement("select * from emp");
9. ResultSet rs=ps.executeQuery();
10. ResultSetMetaData rsmd=rs.getMetaData();
11. System.out.println("Total columns: "+rsmd.getColumnCount());
12. System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
13. System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16. }
17. }

Output:
Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

4
Java DatabaseMetaData interface - DatabaseMetaData interface provides methods to get meta data
of a database such as database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.

Commonly used methods of DatabaseMetaData interface


1. public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
2. public String getDriverVersion()throws SQLException: it returns the version number of the JDBC
driver.
3. public String getUserName()throws SQLException: it returns the username of the database.
4. public String getDatabaseProductName()throws SQLException: it returns the product name of the
database.
5. public String getDatabaseProductVersion()throws SQLException: it returns the product version
of the database.
6. public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified catalog.
The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

How to get the object of DatabaseMetaData:


public DatabaseMetaData getMetaData()throws SQLException

Simple Example of DatabaseMetaData interface :


1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8. DatabaseMetaData dbmd=con.getMetaData();
9. System.out.println("Driver Name: "+dbmd.getDriverName());
10. System.out.println("Driver Version: "+dbmd.getDriverVersion());
11. System.out.println("UserName: "+dbmd.getUserName());
12. System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
13. System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16. }
17. }

Output:
Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
2.11 Store image in Oracle database - You can store images in the database in java by the help
of PreparedStatement interface. The setBinaryStream() method of PreparedStatement is used to set Binary
information into the parameterIndex.

4
The syntax of setBinaryStream() method is given below:
1. public void setBinaryStream(int paramIndex,InputStream stream) throws SQLException
2. public void setBinaryStream(int paramIndex,InputStream stream,long length) throws SQLException

For storing image into the database, BLOB (Binary Large Object) datatype is used in the table. For example:
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /

Let's write the jdbc code to store the image in the database. Here we are using d:\\d.jpg for the location of
image. You can change it according to the image location.

Java Example to store image in the database


1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
10. ps.setString(1,"sonoo");
11. FileInputStream fin=new FileInputStream("d:\\g.jpg");
12. ps.setBinaryStream(2,fin,fin.available());
13. int i=ps.executeUpdate();
14. System.out.println(i+" records affected");
15. con.close();
16. }catch (Exception e) {e.printStackTrace();}
17. }
18. }

If you see the table, record is stored in the database but image will not be shown. To do so, you need to retrieve
the image from the database which we are covering in the next page.

2.12 Retrieve image from Oracle database - By the help of PreparedStatement we can retrieve and
store the image in the database.

The getBlob() method of PreparedStatement is used to get Binary information, it returns the instance of Blob.
After calling the getBytes() method on the blob object, we can get the array of binary information that can be
written into the image file.

Signature of getBlob() method of PreparedStatement


1. public Blob getBlob()throws SQLException

Signature of getBytes() method of Blob interface


1. public byte[] getBytes(long pos, int length)throws SQLException

4
We are assuming that image is stored in the imgtable.
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /

Now let's write the code to retrieve the image from the database and write it into the directory so that it can be
displayed. In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by the
img tag.
1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. PreparedStatement ps=con.prepareStatement("select * from imgtable");
10. ResultSet rs=ps.executeQuery();
11. if(rs.next()){//now on 1st row
12. Blob b=rs.getBlob(2);//2 means 2nd column data
13. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
14. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
15. fout.write(barr);
16. fout.close();
17. }//end of if
18. System.out.println("ok");
19. con.close();
20. }catch (Exception e) {e.printStackTrace(); }
21. }
22. }

Now if you see the d drive, sonoo.jpg image is created.

1.13 Store file in Oracle database - The setCharacterStream() method of PreparedStatement is used to
set character information into the parameterIndex.
Syntax:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)throws SQLException

For storing file into the database, CLOB (Character Large Object) datatype is used in the table. For example:
1. CREATE TABLE "FILETABLE"
2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /

4
Java Example to store file in database
1. import java.io.*;
2. import java.sql.*;
3. public class StoreFile {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. PreparedStatement ps=con.prepareStatement(
10. "insert into filetable values(?,?)");
11. File f=new File("d:\\myfile.txt");
12. FileReader fr=new FileReader(f);
13. ps.setInt(1,101);
14. ps.setCharacterStream(2,fr,(int)f.length());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17. con.close();
18. }catch (Exception e) {e.printStackTrace();}
19. }
20. }

2.14 Retrieve file from Oracle database: The getClob() method of PreparedStatement is used to get
file information from the database.

Syntax of getClob method


public Clob getClob(int columnIndex){}

Let's see the table structure of this example to retrieve the file.
1. CREATE TABLE "FILETABLE"
2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /

The example to retrieve the file from the Oracle database is given below.
1. import java.io.*;
2. import java.sql.*;
3. public class RetrieveFile {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. PreparedStatement ps=con.prepareStatement("select * from filetable");
10. ResultSet rs=ps.executeQuery();
11. rs.next();//now on 1st row
12. Clob c=rs.getClob(2);
13. Reader r=c.getCharacterStream();

4
14. FileWriter fw=new FileWriter("d:\\retrivefile.txt");
15. int i;
16. while((i=r.read())!=-1)
17. fw.write((char)i);
18. fw.close();
19. con.close();
20. System.out.println("success");
21. }catch (Exception e) {e.printStackTrace(); }
22. }
23. }

2.15 Java CallableStatement Interface - CallableStatement interface is used to call the stored
procedures and functions. We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled. Suppose you need the get the
age of the employee based on the date of birth, you may create a function that receives date as the input and
returns age of the employee as the output.

What is the difference between stored procedures and functions.

The differences between stored procedures and functions are given below:
Stored Procedure Function
is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output Function supports only input parameter.
parameters.
Exception handling using try/catch block can be Exception handling using try/catch can't be
used in stored procedures. used in user defined functions.

The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given
below:
public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:


CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.

2.16 Transaction Management in JDBC - Transaction represents a single unit of work. The ACID
properties describes the transaction management well. ACID stands for Atomicity, Consistency, isolation and
durability.
1. Atomicity means either all successful or none.
2. Consistency ensures bringing the database from one consistent state to another consistent state.
3. Isolation ensures that transaction is isolated from other transaction.

4
4. Durability means once a transaction has been committed, it will remain so, even in the event of errors,
power loss etc.

In JDBC, Connection interface provides methods to manage transaction.


Method Description

void setAutoCommit(boolean status) It is true bydefault means each transaction is committed


bydefault.
void commit() commits the transaction.

void rollback() cancels the transaction.

2.17 Batch Processing in JDBC - Instead of executing a single query, we can execute a batch (group)
of queries. It makes the performance fast. The java.sql.Statement and java.sql.PreparedStatement interfaces
provide methods for batch processing.

Methods of Statement interface


Method Description
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.

Example -
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");
6. con.setAutoCommit(false);
7. Statement stmt=con.createStatement();
8. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
9. stmt.addBatch("insert into user420 values(191,'umesh',50000)");
10. stmt.executeBatch();//executing the batch
11. con.commit();
12. con.close();

4
13. }}
If you see the table user420, two records has been added.

2.18 JDBC RowSet - The instance of RowSet is the java bean component because it has properties and java
bean notification mechanism. It is introduced since JDK 5. It is the wrapper of ResultSet. It holds tabular data
like ResultSet but it is easy and flexible to use. The implementation classes of RowSet interface are as follows:
1. JdbcRowSet
2. CachedRowSet
3. WebRowSet
4. JoinRowSet
5. FilteredRowSet

Let's see how to create and execute RowSet.


1. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
2. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
3. rowSet.setUsername("system");
4. rowSet.setPassword("oracle");
5. rowSet.setCommand("select * from emp400");
6. rowSet.execute();

Advantage of RowSet
1. It is easy and flexible to use
2. It is Scrollable and Updatable bydefault

Simple example of JdbcRowSet


1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9. public class RowSetExample {
10. public static void main(String[] args) throws Exception {
11. Class.forName("oracle.jdbc.driver.OracleDriver");
12. //Creating and Executing RowSet
13. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
14. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
15. rowSet.setUsername("system");
16. rowSet.setPassword("oracle");
17. rowSet.setCommand("select * from emp400");
18. rowSet.execute();
19. while (rowSet.next()) {
20. // Generating cursor Moved event
21. System.out.println("Id: " + rowSet.getString(1));
22. System.out.println("Name: " + rowSet.getString(2));
23. System.out.println("Salary: " + rowSet.getString(3));
24. }

4
25. }
26. }
The output is given below:
Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000

4
SERVLET

4
3.1 Introduction of Servlets - Servlet technology is used to create a web application (resides at server
side and generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was common as a server-side programming language. However, there were many
disadvantages to this technology. We have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc.

Servlet can be described in many ways, depending on the context.


1. Servlet is a technology which is used to create a web application.
2. Servlet is an API that provides many interfaces and classes including documentation.
3. Servlet is an interface that must be implemented for creating any Servlet.
4. Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can
respond to any requests.
5. Servlet is a web component that is deployed on the server to create a dynamic web page.

Advantages of Servlet - There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such

4
as they share a common memory area, lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection,
etc.
4. Secure: because it uses java language.

3.2 Servlet API - The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api. The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and
classes that are responsible for http requests only.

There are many interfaces in javax.servlet package. They are as follows:


1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

There are many classes in javax.servlet package. They are as follows:


1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

There are many interfaces in javax.servlet.http package. They are as follows:


1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener

4
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

3.3 Servlet Interface - Servlet interface provides commonbehaviorto all the servlets.Servlet interface
defines methods that all servlets must implement. Servlet interface needs to be implemented for creating any
servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet.
These are invoked by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet
and invoked by the web container only once.
public void service(ServletRequest provides response for the incoming request. It is invoked
request,ServletResponse response) at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is being
destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.

Servlet Example by implementing Servlet interface

File: First.java
1. import java.io.*;
2. import javax.servlet.*;
3. public class First implements Servlet{
4. ServletConfig config=null;
5. public void init(ServletConfig config){
6. this.config=config;
7. System.out.println("servlet is initialized");
8. }
9. public void service(ServletRequest req,ServletResponse res)
10. throws IOException,ServletException{
11. res.setContentType("text/html");
12. PrintWriter out=res.getWriter();
13. out.print("<html><body>");
14. out.print("<b>hello simple servlet</b>");
15. out.print("</body></html>");

4
16. }

1. public void destroy(){System.out.println("servlet is destroyed");}

2. public ServletConfig getServletConfig(){return config;}

3. public String getServletInfo(){return "copyright 2007-1010";}

4. }

3.4 GenericServlet class - GenericServlet class implements Servlet, ServletConfig and


Serializableinterfaces. It provides the implementation of all the methods of these interfaces except the service
method. GenericServlet class can handle any type of request so it is protocol-independent.

There are many methods in GenericServlet class. They are as follows:


1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse response) provides service
for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being
destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need to call
super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given parameter
name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml
file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a
stack trace.

Servlet Example by inheriting the GenericServlet class

File: First.java
1. import java.io.*;
2. import javax.servlet.*;
3. public class First extends GenericServlet{
4. public void service(ServletRequest req,ServletResponse res)
5. throws IOException,ServletException{
6. res.setContentType("text/html");
7. PrintWriter out=res.getWriter();
8. out.print("<html><body>");
9. out.print("<b>hello generic servlet</b>");
10. out.print("</body></html>");
11. }
12. }

4
3.5 HttpServlet class – The HttpServlet class extends the GenericServlet class and implements
Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

There are many methods in HttpServlet class. They are as follows:


1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected
service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request
from the service method, and dispatches the request to the doXXX() method depending on the
incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST
request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD
request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the
OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request.
It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE
request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE
request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

3.6 Life Cycle of a Servlet - The web container maintains the life cycle of a servlet instance. Let's see
the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the this diagram, there are three


states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is
created. After invoking the init() method, Servlet
comes in the ready state. In the ready state,
servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts
to the end state.

1) Servlet class is loaded - The classloader is


responsible to load the servlet class. The servlet
class is loaded when the first request for the
servlet is received by the web container.

4
2) Servlet instance is created - The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.

3) init method is invoked - The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked - The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

5) destroy method is invoked - The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:

public void destroy()

How Servlet works? It is important to learn how servlet works for understanding the servlet well. Here, we
are going to get the internal detail about the first servlet program.

Web container does the following tasks:


1. loads the servlet class.
2. instantiates the servlet class.
3. calls the init method passing the ServletConfig object
else
4. calls the service method passing request and response objects

The web container calls the destroy method when it needs to remove the servlet such as at time of stopping
server or undeploying the project.

How web container handles the servlet request?


1. maps the request with the servlet in the web.xml file.
2. creates request and response objects for this request
3. calls the service method on the thread
4. The public service method internally calls the protected service method
5. The protected service method calls the doGet method depending on the type of request.
6. The doGet method generates the response and it is passed to the client.
7. After sending the response, the web container deletes the request and response objects. The thread is
contained in the thread pool or deleted depends on the server implementation.
3.7 Steps to create a servlet example - There are given 6 steps to create a servlet example. These steps
are required for all the servers. The servlet example can be created by three ways:
1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

4
The mostly used approach is by extending HttpServlet because it provides http request specific method such
as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1) Directory structures - The directory structure defines that where to put the different types of
files so that web container may get the information and respond to the client. The Sun
Microsystem defines a unique standard to be followed by all the server vendors. Let's see the
directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the
WEB-INF folder.

2) Create a Servlet - There are three ways to create the servlet.


1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests
such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are
inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get
request is the default request.

DemoServlet.java

4
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10. //writing html in the stream
11. pw.println("<html><body>");
12. pw.println("Welcome to servlet");
13. pw.println("</body></html>");
14. pw.close();//closing the stream
15. }}

3) Compile the servlet - For compiling the Servlet, jar file is required to be loaded. Different
Servers provide different jar files:
Jar file Server
1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss

Two ways to load the jar file


1. set classpath
2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.

4)Create the deployment descriptor (web.xml file) - The deployment descriptor is an xml file,
from which Web Container gets the information about the servet to be invoked. The web container uses the
Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet
program.
web.xml file
1. <web-app>
2. <servlet>
3. <servlet-name>sonoojaiswal</servlet-name>
4. <servlet-class>DemoServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>sonoojaiswal</servlet-name>
8. <url-pattern>/welcome</url-pattern>
9. </servlet-mapping>

4
10. </web-app>

There are too many elements in the web.xml file. Here is the illustration of some elements that is used in the
above web.xml file. The elements are as follows:

1. <web-app> represents the whole application.


2. <servlet> is sub element of <web-app> and represents the servlet.
3. <servlet-name> is sub element of <servlet> represents the name of the servlet.
4. <servlet-class> is sub element of <servlet> represents the class of the servlet.
5. <servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
6. <url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.

5)Start the Server and deploy the project - To start Apache Tomcat server, double click on the
startup.bat file under apache-tomcat/bin directory.

One Time Configuration for Apache Tomcat Server - You need to perform 2 tasks:
1. How to set JAVA_HOME in environment variable? To start Apache Tomcat server JAVA_HOME and
JRE_HOME must be set in Environment variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the new tab
of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable value -
> ok -> ok -> ok.
There must not be semicolon (;) at the end of the path.
After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin. Now server is
started successfully.

1. How to change port number of apache tomcat - Changing the port number is required if there is another
server running on the same system with same port number.Suppose you have installed oracle, you need to
change the port number of apache tomcat because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the
Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by 9999
and save this file.

5) How to deploy the servlet project - Copy the project and paste it in the webapps folder under apache
tomcat. But there are several ways to deploy the project. They are as follows:
o By copying the context(project) folder into the webapps directory
o By copying the war folder into the webapps directory
o By selecting the folder path from the server
o By selecting the war file from the server

Here, we are using the first approach - You can also create war file, and paste it inside the webapps
directory. To do so, you need to use jar tool to create the war file. Go inside the project directory (before the
WEB-INF), then write:

projectfolder> jar cvf myproject.war *

6) How to access the servlet - Open broser and write


4
http://hostname:portno/contextroot/urlpatternofservlet

For example: http://localhost:9999/demo/welcome

3.8 War File - A war (web archive) File contains files of a web project. It may have servlet, xml, jsp, image,
html, css, js etc. files.

Here, we will discuss what is war file, how to create war file, how to deploy war file and how to extract war
file.

What is war file? web archive (war) file contains all the contents of a web application. It reduces the time
duration for transferring file.

Advantage of war file - saves time: The war file combines all the files into a single unit. So it takes less time
while transferring file from client to server.

How to create war file? To create war file, you need to use jar tool of JDK. You need to use -c switch of jar,
to create the war file. Go inside the project directory of your project (outside the WEB-INF), then write the
following command:

jar -cvf projectname.war *

Here, -c is used to create file, -v to generate the verbose output and -f to specify the arhive file name.

The * (asterisk) symbol signifies that all the files of this directory (including sub directory).

How to extract war file manually? To extract the war file, you need to use -x switch of jar tool of JDK. Let's
see the command to extract the war file.

jar -xvf projectname.war

3.9 welcome-file-list in web.xml - The welcome-file-list element of web-app, is used to define a list of
welcome files. Its sub element is welcome-file that is used to define the welcome file. A welcome file is the
file that is invoked automatically by the server, if you don't specify any file name. By default server looks for
the welcome file in following order:
1. welcome-file-list in web.xml
2. index.html
3. index.htm
4. index.jsp

If none of these files are found, server renders 404 error.

3.10 ServletRequest Interface - An object of ServletRequest is used to provide the client request
information to a servlet such as content type, content length, parameter names and values, header
informations, attributes etc.

Methods of ServletRequest interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:
Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.

4
public String[] getParameterValues(String returns an array of String containing all values of given
name) parameter name. It is mainly used to obtain values of a
Multi select list box.
java.util.Enumeration getParameterNames() returns an enumeration of all of the request parameter
names.
public int getContentLength() Returns the size of the request entity data, or -1 if not
known.
public String getCharacterEncoding() Returns the character set encoding for the input of this
request.
public String getContentType() Returns the Internet Media Type of the request entity data,
or null if not known.
public ServletInputStream getInputStream() Returns an input stream for reading binary data in the
throws IOException request body.
public abstract String getServerName() Returns the host name of the server that received the
request.
public int getServerPort() Returns the port number on which this request was
received.

Example of ServletRequest to display the name of the user

In this example, we are displaying the name of the user in the servlet. For this purpose, we have used the
getParameter method that returns the value for the given request parameter name.

index.html
1. <form action="welcome" method="get">
2. Enter your name<input type="text" name="name"><br>
3. <input type="submit" value="login">
4. </form>

DemoServ.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServ extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");
9. PrintWriter pw=res.getWriter();
10.
11. String name=req.getParameter("name");//will return value
12. pw.println("Welcome "+name);
13.
14. pw.close();
15. }}

4
3.11 RequestDispatcher in Servlet - The RequestDispatcher interface provides the facility of dispatching the
request to another resource it may be html, servlet or jsp. This interface can also be used to include the content
of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.


1. public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another resource
(servlet,JSP file, or HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML
file) in the response.

As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is
not displayed to the user.

As you can see in the above figure, response of second servlet is included in the response of the first servlet that
client.

Syntax of getRequestDispatcher method


1. public RequestDispatcher getRequestDispatcher(String resource);

Example of using getRequestDispatcher method


2. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
3. //servlet2 is the url-pattern of the second servlet

4
4. rd.forward(request, response);//method may be include or forward

3.12 SendRedirect in servlet - The sendRedirect() method of HttpServletResponse interface can be


used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as
absolute URL. It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.

Difference between forward() and sendRedirect() method - There are many differences between the
forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse
interface. They are given below:
forward() method sendRedirect() method
The forward() method works at server side. The sendRedirect() method
works at client side.
It sends the same request and response objects to another servlet. It always sends a new request.

It can work within the server only. It can be used within and outside
the server.
Example: Example:
request.getRequestDispacher("servlet2").forward(request,respon response.sendRedirect("servlet2
se); ");

Syntax of sendRedirect() method


1. public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method


2. response.sendRedirect("http://www.mykss.in");

3.13 ServletConfig Interface - An object of ServletConfig is created by the web container for each
servlet. This object can be used to get configuration information from web.xml file. If the configuration
information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage
the web application if any specific content is modified from time to time.

Methods of ServletConfig interface -


1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization
parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of ServletContext.

How to get the object of ServletConfig


1. getServletConfig() method of Servlet interface returns the object of ServletConfig.

Syntax of getServletConfig() method


1. public ServletConfig getServletConfig();

Example of getServletConfig() method


1. ServletConfig config=getServletConfig();
2. //Now we can call the methods of ServletConfig interface

4
Syntax to provide the initialization parameter for a servlet
The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
1. <web-app>
2. <servlet>
3. ......
4. <init-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </init-param>
8. ......
9. </servlet>
10. </web-app>

3.14 ServletContext Interface - An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration information from web.xml file. There is
only one ServletContext object per web application. If any information is shared to many servlet, it is better
to provide it from the web.xml file using the <context-param> element.

There can be a lot of usage of ServletContext object. Some of them are as follows:
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.

There is given some commonly used methods of ServletContext interface.


1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application
scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.

4
5. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given name from
the servlet context.

How to get the object of ServletContext interface

1. getServletContext() method of ServletConfig interface returns the object of ServletContext.

2. getServletContext() method of GenericServlet class returns the object of ServletContext.

3.15 Attribute in Servlet - An attribute in servlet is an object that can be set, get or removed from one
of the following scopes:
1. request scope
2. session scope
3. application scope

The servlet programmer can pass informations from one servlet to another using attributes. It is just like
passing object from one class to another so that we can reuse the same object again and again. Attribute
specific methods of ServletRequest, HttpSession and ServletContext interface

There are following 4 attribute specific methods. They are as follows:


1. public void setAttribute(String name,Object object):sets the given object in the application
scope.
2. public Object getAttribute(String name):Returns the attribute for the specified name.
3. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
4. public void removeAttribute(String name):Removes the attribute with the given name from the
servlet context.

3.16 Session Tracking in Servlets - Session simply means a particular interval of time. Session
Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet. Http
protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests
to the server, server treats the request as the new request. So we need to maintain the state of an user to
recognize to particular user. HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:

4
Why use Session Tracking? To recognize the user It is used to recognize the particular user. Session Tracking
Techniques

There are four techniques used in Session tracking:


1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet - A cookie is a small piece of information that is persisted between the multiple client
requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works - By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is
sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

There are 2 types of cookies in servlets.


1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie - It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie - It is valid for multiple session . It is not removed each time when user closes the browser.
It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class - javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.

Constructor of Cookie class


Constructor Description
Cookie() constructs a cookie.

4
Cookie(String name, String value) constructs a cookie with a specified name and value.

There are given some commonly used methods of the Cookie class.
Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in
response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies
from the browser.

How to create Cookie?


1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?


1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

2) Hidden Form Field - In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of an user. In such case, we store the information in the hidden field and get it from another servlet.
This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.
Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

It is widely used in comment form of a website. In such case, we store page id or page name in the hidden
field so that each page can be uniquely identified.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not.

4
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.

3)URL Rewriting - In URL rewriting, we append a token or identifier to the URL of the next Servlet or the
next resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another
parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will
be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting


1. It will work only with links.
2. It can send Only textual information.

4) HttpSession interface - In such case, container creates a session id for each user.The container uses
this id to identify the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and
last accessed time.

4
Methods to get the object of HttpSession:
1. public HttpSession getSession():Returns the current session associated with this request, or if the
request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with
this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface


1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request associated with
this session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value from
the session scope in another servlet. To set the attribute in the session scope, we have used the setAttribute()
method of HttpSession interface and to get the attribute, we have used the getAttribute method.

index.html
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class FirstServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response){
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. String n=request.getParameter("userName");
10. out.print("Welcome "+n);

4
11. HttpSession session=request.getSession();
12. session.setAttribute("uname",n);
13. out.print("<a href='servlet2'>visit</a>");
14. out.close();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. HttpSession session=request.getSession(false);
10. String n=(String)session.getAttribute("uname");
11. out.print("Hello "+n);
12. out.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }

web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>FirstServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>s2</servlet-name>
12. <servlet-class>SecondServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>s2</servlet-name>
16. <url-pattern>/servlet2</url-pattern>
17. </servlet-mapping>
18. </web-app>

4
3.17 Event and Listener in Servlet - Events are basically occurrence of something. Changing the state
of an object is known as an event. We can perform some important tasks at the occurrence of these exceptions,
such as counting total and current logged-in users, creating tables of the database at time of deploying the
project, creating database connection object etc.

The event classes are as follows:


1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent

The event interfaces are as follows:


1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener

3.18 Servlet Filter - A filter is an object that is invoked at the preprocessing and postprocessing of a
request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and
decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if
we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to
change the servlet. So maintenance cost will be less.

Usage of Filter
1. recording all incoming requests
2. logs the IP addresses of the computers from which the requests originate
3. conversion
4. data compression
5. encryption and decryption
6. input validation etc.

Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.

4
3. Less Maintenance

Filter API - Like servlet filter have its own API. The javax.servlet package contains the three interfaces of
Filter API.
1. Filter
2. FilterChain
3. FilterConfig

1) Filter interface - For creating any filter, you must implement the Filter interface. Filter
interface provides the life cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used to
initialize the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when user
request,HttpServletResponse response, request to any resource, to which the filter is
FilterChain chain) mapped.It is used to perform filtering tasks.
public void destroy() This is invoked only once when filter is taken out of
the service.

2) FilterChain interface - The object of FilterChain is responsible to invoke the next filter or resource
in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains
only one method:

public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the


control to the next filter or resource.

How to define Filter


1. <web-app>
2. <filter>
3. <filter-name>...</filter-name>
4. <filter-class>...</filter-class>
5. </filter>
6. <filter-mapping>
7. <filter-name>...</filter-name>
8. <url-pattern>...</url-pattern>
9. </filter-mapping>
10. </web-app>

For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an advantage
over servlet-name element i.e. it can be applied on servlet, JSP or HTML.

Authentication Filter -We can perform authentication in filter. Here, we are going to check to password
given by the user in filter class, if given password is admin, it will forward the request to the WelcomeAdmin
servlet otherwise it will display error message.

FilterConfig - An object of FilterConfig is created by the web container. This object can be used to get the
configuration information from the web.xml file.

There are following 4 methods in the FilterConfig interface.

4
1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the
filter.
2. public String getInitParameter(String parameterName): Returns the parameter value for the
specified parameter name.
3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the
parameter names.
4. public ServletContext getServletContext(): Returns the ServletContext object.

3.19 CRUD in Servlet - A CRUD (Create, Read, Update and Delete) application is the most important
application for any project development. In Servlet, we can easily create CRUD application.

Servlet CRUD example - Create "user905" table in Oracle Database with auto incrementing id using
sequence. There are 5 fields in it: id, name, password, email and country.

File: index.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h1>Add New Employee</h1>
9. <form action="SaveServlet" method="post">
10. <table>
11. <tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
12. <tr><td>Password:</td><td><input type="password" name="password"/></td></tr>
13. <tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
14. <tr><td>Country:</td><td>
15. <select name="country" style="width:150px">
16. <option>India</option>
17. <option>USA</option>
18. <option>UK</option>
19. <option>Other</option>
20. </select>
21. </td></tr>
22. <tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>
23. </table>
24. </form>
25. <br/>

4
26. <a href="ViewServlet">view employees</a>
27. </body>
28. </html>

File: Emp.java
1. public class Emp {
2. private int id;
3. private String name,password,email,country;
4. public int getId() {
5. return id;
6. }
7. public void setId(int id) {
8. this.id = id;
9. }
10. public String getName() {
11. return name;
12. }
13. public void setName(String name) {
14. this.name = name;
15. }
16. public String getPassword() {
17. return password;
18. }
19. public void setPassword(String password) {
20. this.password = password;
21. }
22. public String getEmail() {
23. return email;
24. }
25. public void setEmail(String email) {
26. this.email = email;
27. }
28. public String getCountry() {
29. return country;
30. }
31. public void setCountry(String country) {
32. this.country = country;
33. }
34. }

File: EmpDao.java
1. import java.util.*;
2. import java.sql.*;
3. public class EmpDao {
4. public static Connection getConnection(){
5. Connection con=null;
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");

4
8. con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"
);
9. }catch(Exception e){System.out.println(e);}
10. return con;
11. }
12. public static int save(Emp e){
13. int status=0;
14. try{
15. Connection con=EmpDao.getConnection();
16. PreparedStatement ps=con.prepareStatement(
17. "insert into user905(name,password,email,country) values (?,?,?,?)");
18. ps.setString(1,e.getName());
19. ps.setString(2,e.getPassword());
20. ps.setString(3,e.getEmail());
21. ps.setString(4,e.getCountry());
22. status=ps.executeUpdate();
23. con.close();
24. }catch(Exception ex){ex.printStackTrace();}
25. return status;
26. }
27. public static int update(Emp e){
28. int status=0;
29. try{
30. Connection con=EmpDao.getConnection();
31. PreparedStatement ps=con.prepareStatement(
32. "update user905 set name=?,password=?,email=?,country=? where id=?");
33. ps.setString(1,e.getName());
34. ps.setString(2,e.getPassword());
35. ps.setString(3,e.getEmail());
36. ps.setString(4,e.getCountry());
37. ps.setInt(5,e.getId());
38. status=ps.executeUpdate();
39. con.close();
40. }catch(Exception ex){ex.printStackTrace();}
41. return status;
42. }
43. public static int delete(int id){
44. int status=0;
45. try{
46. Connection con=EmpDao.getConnection();
47. PreparedStatement ps=con.prepareStatement("delete from user905 where id=?");
48. ps.setInt(1,id);
49. status=ps.executeUpdate();
50. con.close();
51. }catch(Exception e){e.printStackTrace();}
52. return status;
53. }
54. public static Emp getEmployeeById(int id){

4
55. Emp e=new Emp();
56. try{
57. Connection con=EmpDao.getConnection();
58. PreparedStatement ps=con.prepareStatement("select * from user905 where id=?");
59. ps.setInt(1,id);
60. ResultSet rs=ps.executeQuery();
61. if(rs.next()){
62. e.setId(rs.getInt(1));
63. e.setName(rs.getString(2));
64. e.setPassword(rs.getString(3));
65. e.setEmail(rs.getString(4));
66. e.setCountry(rs.getString(5));
67. }
68. con.close();
69. }catch(Exception ex){ex.printStackTrace();}
70. return e;
71. }
72. public static List<Emp> getAllEmployees(){
73. List<Emp> list=new ArrayList<Emp>();
74. try{
75. Connection con=EmpDao.getConnection();
76. PreparedStatement ps=con.prepareStatement("select * from user905");
77. ResultSet rs=ps.executeQuery();
78. while(rs.next()){
79. Emp e=new Emp();
80. e.setId(rs.getInt(1));
81. e.setName(rs.getString(2));
82. e.setPassword(rs.getString(3));
83. e.setEmail(rs.getString(4));
84. e.setCountry(rs.getString(5));
85. list.add(e);
86. }
87. con.close();
88. }catch(Exception e){e.printStackTrace();}
89. return list;
90. }
91. }

File: SaveServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.annotation.WebServlet;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. @WebServlet("/SaveServlet")
9. public class SaveServlet extends HttpServlet {

4
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. String name=request.getParameter("name");
15. String password=request.getParameter("password");
16. String email=request.getParameter("email");
17. String country=request.getParameter("country");
18. Emp e=new Emp();
19. e.setName(name);
20. e.setPassword(password);
21. e.setEmail(email);
22. e.setCountry(country);
23. int status=EmpDao.save(e);
24. if(status>0){
25. out.print("<p>Record saved successfully!</p>");
26. request.getRequestDispatcher("index.html").include(request, response);
27. }else{
28. out.println("Sorry! unable to save record");
29. }
30. out.close();
31. }
32. }

File: EditServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.annotation.WebServlet;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. @WebServlet("/EditServlet")
9. public class EditServlet extends HttpServlet {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. out.println("<h1>Update Employee</h1>");
15. String sid=request.getParameter("id");
16. int id=Integer.parseInt(sid);
17. Emp e=EmpDao.getEmployeeById(id);
18. out.print("<form action='EditServlet2' method='post'>");
19. out.print("<table>");
20. out.print("<tr><td></td><td><input type='hidden' name='id' value='"+e.getId()+"'/></td
></tr>");
21. out.print("<tr><td>Name:</td><td><input type='text' name='name' value='"+e.getName
()+"'/></td></tr>");

4
22. out.print("<tr><td>Password:</td><td><input type='password' name='password' value='
"+e.getPassword()+"'/>
23. </td></tr>");
24. out.print("<tr><td>Email:</td><td><input type='email' name='email' value='"+e.getEm
ail()+"'/></td></tr>");
25. out.print("<tr><td>Country:</td><td>");
26. out.print("<select name='country' style='width:150px'>");
27. out.print("<option>India</option>");
28. out.print("<option>USA</option>");
29. out.print("<option>UK</option>");
30. out.print("<option>Other</option>");
31. out.print("</select>");
32. out.print("</td></tr>");
33. out.print("<tr><td colspan='2'><input type='submit' value='Edit & Save '/></td></tr>");
34. out.print("</table>");
35. out.print("</form>");
36. out.close();
37. }
38. }

File: EditServlet2.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.annotation.WebServlet;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. @WebServlet("/EditServlet2")
10. public class EditServlet2 extends HttpServlet {
11. protected void doPost(HttpServletRequest request, HttpServletResponse response)
12. throws ServletException, IOException {
13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
String sid=request.getParameter("id");
15. int id=Integer.parseInt(sid);
16. String name=request.getParameter("name");
17. String password=request.getParameter("password");
18. String email=request.getParameter("email");
19. String country=request.getParameter("country");
20. Emp e=new Emp();
21. e.setId(id);
22. e.setName(name);
23. e.setPassword(password);
24. e.setEmail(email);
25. e.setCountry(country);
26. int status=EmpDao.update(e);

4
27. if(status>0){
28. response.sendRedirect("ViewServlet");
29. }else{
30. out.println("Sorry! unable to update record");
31. }
32. out.close();
33. }
34. }

File: DeleteServlet.java
1. import java.io.IOException;
2. import javax.servlet.ServletException;
3. import javax.servlet.annotation.WebServlet;
4. import javax.servlet.http.HttpServlet;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. @WebServlet("/DeleteServlet")
8. public class DeleteServlet extends HttpServlet {
9. protected void doGet(HttpServletRequest request, HttpServletResponse response)
10. throws ServletException, IOException {
11. String sid=request.getParameter("id");
12. int id=Integer.parseInt(sid);
13. EmpDao.delete(id);
14. response.sendRedirect("ViewServlet");
15. } }

File: ViewServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import java.util.List;
4. import javax.servlet.ServletException;
5. import javax.servlet.annotation.WebServlet;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. @WebServlet("/ViewServlet")
10. public class ViewServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)
12. throws ServletException, IOException {
13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15. out.println("<a href='index.html'>Add New Employee</a>");
16. out.println("<h1>Employees List</h1>");
17. List<Emp> list=EmpDao.getAllEmployees();
18. out.print("<table border='1' width='100%'");
19. out.print("<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th><th>Country</th
>
20. <th>Edit</th><th>Delete</th></tr>");
21. for(Emp e:list){

4
22. out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td><td>"+e.getPassword()+"</td
>
23. <td>"+e.getEmail()+"</td><td>"+e.getCountry()+"</td><td><a href='EditServlet?id="+e.
getId()+"'>edit</a></td>
24. <td><a href='DeleteServlet?id="+e.getId()+"'>delete</a></td></tr>");
25. }

26. out.print("</table>");

27. out.close();

28. } }

Output

4
4
4
JSP

4
4.1 Introduction of JSP - JSP technology is used to create web application just like Servlet technology. It
can be thought of as an extension to Servlet because it provides more functionality than servlet such as
expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because
we can separate designing and development. It provides some additional features such as Expression
Language, Custom Tags, etc.

Advantages of JSP over Servlet


1) Extension to Servlet - JSP technology is the extension to Servlet technology. We can use all the features
of the Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain - JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation logic.

3) Fast Development - No need to recompile and redeploy - If JSP page is modified, we don't need to
recompile and redeploy the project. The Servlet code needs to be updated and recompiled if we have to change
the look and feel of the application.

4) Less code than Servlet - In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.

4.2 Lifecycle of a JSP Page


1. Translation of JSP Page
2. Compilation of JSP Page
3. Classloading (the classloader loads class file)
4. Instantiation (Object of the Generated Servlet is created).
5. Initialization ( the container invokes jspInit() method).
6. Request processing ( the container invokes _jspService() method).
7. Destroy ( the container invokes jspDestroy() method).

4.3 Creating a simple JSP Page - To create the first JSP page, write some HTML code as given below, and
save it by .jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP page.

4
index.jsp
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
It will print 10 on the browser.

How to run a simple JSP Page?


1. Start the server
2. Put the JSP file in a folder and deploy on the server
3. Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple JSP? No, there is no need of directory structure
if you don't have class files or TLD files. For example, put JSP files in a folder directly and deploy that folder.
It will be running fine. However, if you are using Bean class, Servlet or TLD file, the directory structure is
required.

The Directory structure of JSP - The directory structure of JSP page is same as Servlet. We contain the JSP
page outside the WEB-INF folder or in any directory.

4.4 JSP API - The JSP API consists of two packages:


1. javax.servlet.jsp
2. javax.servlet.jsp.tagext

javax.servlet.jsp package - The javax.servlet.jsp package has two interfaces and classes.The two interfaces
are as follows:
1. JspPage
2. HttpJspPage

Classes are as follows:


1. JspWriter
2. PageContext
3. JspFactory
4. JspEngineInfo
4
5. JspException
6. JspError

4.5 JspPage interface - According to the JSP specification, all the generated servlet classes must
implement the JspPage interface. It extends the Servlet interface. It provides two life cycle methods.

Methods of JspPage interface -


1. public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page is
requested firstly. It is used to perform initialization. It is same as the init() method of Servlet interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP before the JSP page
is destroyed. It can be used to perform some clean up operation.

4.6 HttpJspPage interface - The HttpJspPage interface provides the one life cycle method of JSP. It
extends the JspPage interface.

Method of HttpJspPage interface:


public void _jspService(): It is invoked each time when request for the JSP page comes to the container.
It is used to process the request. The underscore _ signifies that you cannot override this method.

4.7 JSP Scripting elements - The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
1. scriptlet tag
2. expression tag
3. declaration tag

4.7.1 JSP scriptlet tag - A scriptlet tag is used to execute java source code in JSP. Syntax is
as follows:

<% java source code %>

4.7.2 JSP expression tag - The code placed within JSP expression tag is written to the output stream of
the response. So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.

<%= statement %>

4
4.7.3 JSP Declaration Tag - The JSP declaration tag is used to declare fields and methods. The code
written inside the jsp declaration tag is placed outside the service() method of auto generated servlet. So it
doesn't get memory at each request.

<%! field or method declaration %>

4.8 JSP Implicit Objects - There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:


Object Type
Out JspWriter
Request HttpServletRequest
Response HttpServletResponse
Config ServletConfig
application ServletContext
Session HttpSession
pageContext PageContext
Page Object
Exception Throwable

4.9 JSP directives - The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.

There are three types of directives:


1. page directive
2. include directive
3. taglib directive

4.9.1 JSP page directive - The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

<%@ page attribute="value" %>

Attributes of JSP page directive


1. import
2. contentType
3. extends
4. info
5. buffer
6. language
7. isELIgnored
8. isThreadSafe
9. autoFlush
10. session
11. pageEncoding
12. errorPage

4
13. isErrorPage

4.9.2 Jsp Include Directive - The include directive is used to include the contents of any resource it may
be jsp file, html file or text file. The include directive includes the original content of the included resource at
page translation time (the jsp page is translated only once so it will be better to include static resource).

Syntax of include directive

<%@ include file="resourceName" %>

Example of include directive


1. <html>
2. <body>
3. <%@ include file="header.html" %>
4. Today is: <%= java.util.Calendar.getInstance().getTime() %>
5. </body>
6. </html>

4.9.3 JSP Taglib directive - The JSP taglib directive is used to define a tag library that defines many
tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive


<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive - In this example, we are using our tag named currentDate. To use this
tag we must specify the taglib directive so the container may get information about the tag.
1. <html>
2. <body>
3. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
4. <mytag:currentDate/>
5. </body>
6. </html>

4.10 Exception Handling in JSP - The exception is normally an object that is thrown at runtime. Exception
Handling is the process to handle the runtime errors. There may occur exception any time in your web
application. So handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform
exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file

Example of exception handling in jsp by the elements of page directive

There are 3 files:


1. index.jsp for input values
2. process.jsp for dividing the two numbers and displaying the result
3. error.jsp for handling the exception

index.jsp
1. <form action="process.jsp">

4
2. No1:<input type="text" name="n1" /><br/><br/>
3. No1:<input type="text" name="n2" /><br/><br/>
4. <input type="submit" value="divide"/>
5. </form>

process.jsp
1. <%@ page errorPage="error.jsp" %>
2. <%
3. String num1=request.getParameter("n1");
4. String num2=request.getParameter("n2");
5. int a=Integer.parseInt(num1);
6. int b=Integer.parseInt(num2);
7. int c=a/b;
8. out.print("division of numbers is: "+c);
9. %>

4.11 JSP Action Tags - There are many JSP action tags or elements. Each JSP action tag is used to
perform some specific tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are given
below.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.

The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we will see these
tags in bean developement.

jsp:forward action tag - The jsp:forward action tag is used to forward the request to another
resource it may be jsp, html or another resource.

Syntax of jsp:forward action tag with parameter


1. <jsp:forward page="relativeURL | <%= expression %>">
2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:forward>

4
jsp:include action tag - The jsp:include action tag is used to include the content of another resource it
may be jsp, html or servlet. The jsp include action tag includes the resource at request time so it is better for
dynamic pages because there might be changes in future. The jsp:include tag can be used to include static as
well as dynamic pages.

Syntax of jsp:include action tag without parameter


1. <jsp:include page="relativeURL | <%= expression %>" />

Syntax of jsp:include action tag with parameter


1. <jsp:include page="relativeURL | <%= expression %>">
2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:include>

Java Bean - A Java Bean is a java class that should follow following conventions:
1. It should have a no-arg constructor.
2. It should be Serializable.
3. It should provide methods to set and get the values of the properties, known as getter and setter
methods.

Simple example of java bean class

//Employee.java
1. package mypack;
2. public class Employee implements java.io.Serializable{
3. private int id;
4. private String name;
5. public Employee(){}
6. public void setId(int id){this.id=id;}
7. public int getId(){return id;}
8. public void setName(String name){this.name=name;}
9. public String getName(){return name;}
10. }

How to access the java bean class?

To access the java bean class, we should use getter and setter methods.
1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4. Employee e=new Employee();//object is created
5. e.setName("Arjun");//setting value to the object
6. System.out.println(e.getName());
7. }}

4
jsp:useBean action tag - The jsp:useBean action tag is used to locate or instantiate a bean class. If bean
object of the Bean class is already created, it doesn't create the bean depending on the scope. But if object of
bean is not created, it instantiates the bean.

Syntax of jsp:useBean action tag

1. <jsp:useBean id= "instanceName" scope= "page | request | session | application"


2. class= "packageName.className" type= "packageName.className"

3. beanName="packageName.className | <%= expression >" >

4. </jsp:useBean>

Attributes and Usage of jsp:useBean action tag

1. id: is used to identify the bean in the specified scope.

2. scope: represents the scope of the bean. It may be page, request, session or application. The default
scope is page.

1. page: specifies that you can use this bean within the JSP page. The default scope is page.

2. request: specifies that you can use this bean from any JSP page that processes the same
request. It has wider scope than page.

3. session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not. It has wider scope than request.

4. application: specifies that you can use this bean from any JSP page in the same application. It
has wider scope than session.

3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have no-
arg or no constructor and must not be abstract.

4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class
or beanName attribute. If you use it without class or beanName, no bean is instantiated.

5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

4.12 jsp:setProperty and jsp:getProperty action tags - The setProperty and getProperty action
tags are used for developing web application with Java Bean. In web devlopment, bean class is mostly used
because it is a reusable software component that represents data.

Syntax of jsp:setProperty action tag


1. <jsp:setProperty name="instanceOfBean" property= "*" |
2. property="propertyName" param="parameterName" |
3. property="propertyName" value="{ string | <%= expression %>}"
4. />

Example of jsp:setProperty action tag if you have to set all the values of incoming request in the bean

<jsp:setProperty name="bean" property="*" />

4
Example of jsp:setProperty action tag if you have to set value of the incoming specific property

<jsp:setProperty name="bean" property="username" />

Example of jsp:setProperty action tag if you have to set a specific value in the property

<jsp:setProperty name="bean" property="username" value="Kumar" />

jsp:getProperty action tag - The jsp:getProperty action tag returns the value of the property.

Syntax of jsp:getProperty action tag

<jsp:getProperty name="instanceOfBean" property="propertyName" />

Simple example of jsp:getProperty action tag

<jsp:getProperty name="obj" property="name" />

4
JSTL

4
5.1 Introduction of JSTL - The JSP Standard Tag Library (JSTL) represents a set of tags to simplify
the JSP development.

Advantage of JSTL
1. Fast Development - JSTL provides many tags that simplify the JSP.
2. Code Reusability - We can use the JSTL tags on various pages.
3. No need to use scriptlet tag - It avoids the use of scriptlet tag.

JSTL Tags - There JSTL mainly provides five types of tags:

Tag Name Description


Core tags The JSTL core tag provide variable support, URL management, flow control,
etc. The URL for the core tag is http://java.sun.com/jsp/jstl/core. The prefix of
core tag is c.

Function tags The functions tags provide support for string manipulation and string length. The
URL for the functions tags is http://java.sun.com/jsp/jstl/functions and prefix
is fn.

Formatting tags The Formatting tags provide support for message formatting, number and date
formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL for the XML
tags is http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.

5.2 JSTL Core Tags - The JSTL core tag provides variable support, URL management, flow control etc.
The syntax used for including JSTL core library in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag work.
c:import It Retrives relative or an absolute URL and display the contents to either a
String in 'var',a Reader in 'varReader' or the page.
c:set It sets the result of an expression under evaluation in a 'scope' variable.
c:remove It is used for removing the specified scoped variable from a particular scope.
c:catch It is used for Catches any Throwable exceptions that occurs in the body.
c:if It is conditional tag used for testing the condition and display the body
content only if the expression evaluates is true.
c:choose, c:when, It is the simple conditional tag that includes its body content if the evaluated
c:otherwise condition is true.
c:forEach It is the basic iteration tag. It repeats the nested body content for fixed
number of times or over collection.
c:forTokens It iterates over tokens which is separated by the supplied delimeters.
c:param It adds a parameter in a containing 'import' tag's URL.

4
c:redirect It redirects the browser to a new URL and supports the context-relative
URLs.
c:url It creates a URL with optional query parameters.

5.3 JSTL Function Tags - The JSTL function provides a number of standard functions, most of these
functions are common string manipulation functions. The syntax used for including JSTL function library in
your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

JSTL Functions Description


fn:contains() It is used to test if an input string containing the specified substring in a
program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a
case insensitive way.
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as XML markup.
fn:indexOf() It returns an index within a string of first occurrence of a specified
substring.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a particular
string value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase() It converts all the characters of a string to lower case.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given start and end
position.
fn:substringAfter() It returns the subset of string after a specific substring.
fn:substringBefore() It returns the subset of string before a specific substring.
fn:length() It returns the number of characters inside a string, or the number of items
in a collection.
fn:replace() It replaces all the occurrence of a string with another string sequence.

5.4 JSTL Formatting tags - The formatting tags provide support for message formatting, number and
date formatting etc. The url for the formatting tags ishttp://java.sun.com/jsp/jstl/fmt and prefix is fmt.

The JSTL formatting tags are used for internationalized web sites to display and format text, the time, the date
and numbers. The syntax used for including JSTL formatting library in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

Formatting Tags Descriptions


fmt:parseNumber It is used to Parses the string representation of a currency, percentage or
number.
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time
formatting.

4
fmt:formatNumber It is used to format the numerical value with specific format or precision.
fmt:parseDate It parses the string representation of a time and date.
fmt:bundle It is used for creating the ResourceBundle objects which will be used by their
tag body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable or
the named scoped variable.
fmt:message It display an internationalized message.
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.

5.5 JSTL XML tags - The JSTL XML tags are used for providing a JSP-centric way of manipulating and
creating XML documents.

The xml tags provide flow control, transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL XML tag library has custom tags used for
interacting with XML data. The syntax used for including JSTL XML tags library in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

Before you proceed further with the examples, you need to copy the two XML and XPath related libraries into
the <Tomcat Installation Directory>\lib:

Xalan.jar: Download this jar file from the link:

http://xml.apache.org/xalan-j/index.html

XercesImpl.jar: Download this jar file from the link:

http://www.apache.org/dist/xerces/j/

1.
XML Tags Descriptions
x:out Similar to <%= ... > tag, but for XPath expressions.
x:parse It is used for parse the XML data specified either in the tag body or an attribute.
x:set It is used to sets a variable to the value of an XPath expression.
x:choose It is a conditional tag that establish a context for mutually exclusive conditional
operations.
x:when It is a subtag of that will include its body if the condition evaluated be 'true'.
x:otherwise It is subtag of that follows tags and runs only if all the prior conditions evaluated
be 'false'.
x:if It is used for evaluating the test XPath expression and if it is true, it will processes
its body content.
x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet
Language) transformation.
x:param It is used along with the transform tag for setting the parameter in the XSLT style
sheet.

4
5.6 JSTL SQL Tags - The JSTL sql tags provide SQL support. The url for the sql tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql. The SQL tag library allows the tag to interact with
RDBMSs (Relational Databases) such as Microsoft SQL Server, mySQL, or Oracle. The syntax used for
including JSTL SQL tags library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

SQL Tags Descriptions


sql:setDataSource It is used for creating a simple data source suitable only for prototyping.

sql:query It is used for executing the SQL query defined in its sql attribute or the body.

sql:update It is used for executing the SQL update defined in its sql attribute or in the tag
body.
sql:param It is used for sets the parameter in an SQL statement to the specified value.

sql:dateParam It is used for sets the parameter in an SQL statement to a specified java.util.Date
value.
sql:transaction It is used to provide the nested database action with a common connection.

You might also like