WCD_Courseware
WCD_Courseware
op
yrig
ht
s
of
SE
ED
In
fo
te
ch
Lt
d.
|O
ffi
cia
lC
ur
ri cu
lu
m
m
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
This edition has been printed and published in house by Avani Publications.
C
This book including interior design, cover design and icons may not be duplicated/reproduced or transmitted in
anyway without the express written consent of the publisher, except in the form of brief excerpts quotations for the
purpose of review. The information contained herein is for the personal use of the reader and may not be
incorporated in any commercial programs, other books, databases or any kind of software without written consent of
the publisher. Making copies of this book or any portion thereof for any purpose other than your own is a violation of
copyright laws.
Limits of Liability/Disclaimer of Warranty : The author and publisher have used their best efforts in preparing this
book. Avani Publications make no representation or warranties with respect to the accuracy or completeness of the
contents of this book, and specifically disclaim any implied warranties of merchantability or fitness for any particular
purpose. There are no warranties, which extend beyond the descriptions contained in this paragraph. No warranty
may be created or extended by sales representatives or written sales materials. The accuracy and completeness of
the information provided herein and the opinions stated herein are not guaranteed or warranted to produce any
particular results and the advice and strategies contained herein may not be suitable for every individual. Author or
Avani Publications shall not be liable for any loss of profit or any other commercial damages, including but not limited
to special, incidental, consequential or other damages.
Trademarks : All brand names and product names used in this book are trademarks, registered trademarks or trade
names of their respective holders. Avani Publications is not associated with any product or vendor mentioned in this
book.
Note: All API references are taken from Java documentation. (http://docs.oracle.com/javase/7/docs/api/)
Print Edition : January 2012
Issue No./ Date : 01 / Jan. 25, 2012 Revision No. & Date : 00 / Jan. 25, 2012
Avani Publications
Flat no 2, Ground Floor, Radhakrishna Apts., Prabhat Road, Lane No. 10, Erandawana Pune 411004, Maharashtra,
India.
ii
Contents
Sr.
Chapter Name Page No.
m
No.
lu
cu
ri
0 Enhancing Employability iv
ur
lC
ia
1. Java Database Connectivity(JDBC) 1
c
ffi
|O
2. Advanced JDBC 43
d.
3. Lt
Introduction to Web Technologies 78
ch
te
fo
6. Servlets 162
s
ht
rig
iii
Enhancing Employability
Employability depends on the knowledge, skills and abilities that individuals
possess, the way they use these to solve problems and contribute to the growth of
the employing organization and the society. Employability skills are those skills
m
lu
that are necessary for getting, keeping and doing well in a job.
cu
ri
ur
Employability can be defined as an equation.
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
Promise of this book is to help strengthen your “WCD programming skill” which
rig
y
iv
Frameworks like Struts, Spring, Hibernate are being widely adopted by
industry to build applications rapidly. Knowledge of such frameworks is
becoming essential for application developers.
e) There is continuous demand for Web Component Developers in software
m
industry in large numbers.
lu
cu
ri
Role of this book
ur
lC
This book is a step by step guide to master WCD programming skills and would aid
ia
c
and reinforce the learning in the classroom. To master any programming language
ffi
|O
one needs hands-on practice along with clarity of concepts. This student book
d.
combined with lab manual is designed to serve the purpose.
Lt
ch
The smart tips embedded in the form of Tech App, Interview Tip, Additional
te
fo
Reading, Best Practices, etc. would help increase your curiosity and also help you
In
ED
We strive hard to make technical contents of this book completely error free.
s
ht
rig
However some mistakes might have slipped our attention. We request the reader
y
op
to send us any such errors you sight which will help us in improving this book
C
v
vi
C
op
yrig
ht
s
of
SE
ED
In
fo
te
ch
Lt
d.
|O
ffi
cia
lC
ur
ri cu
lu
m
“Beyond Obvious” Icons
In the student book, we have included special icons (Beyond Obvious Icons) in the
form of footnotes that are interspersed in the study material to give you the
m
precise context of the concept you are learning. As you get accustomed to this
lu
cu
way of learning, you will enjoy the fun of it which will make this learning highly
ri
ur
productive!
lC
ia
This icon indicates a particular best practice
c
ffi
which is followed while developing the
|O
applications, in design, in coding etc. Knowledge
d.
Lt
of best practices makes one a good developer or
ch
te
designer.
fo
In
revision pointers.
ht
rig
y
op
JDK7
and available in new version JDK 7.
vii
This is application of technology learned to solve
the real world problem.
m
lu
the application design perspective.
cu
ri
ur
This icon indicates quiz to be solved in the
lC
ia
classroom. This is for reinforcement of what you
c
ffi
have learnt by challengin you through the
|O
questions.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
viii
m
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
This chapter covers database connectivity using JDBC API. It includes SQL,
Parameterized SQL, Stored Procedure, JDBC Drivers, Database Transactions, Result
set metadata and Database metadata.
Objectives
At the end of this chapter you will be able to:
Compare File versus Database as storage medium.
List features provided by databases.
List Types of SQL.
Identify the need for JDBC.
List various technologies used to access data from databases.
State the algorithm for reading data from a database.
Construct a Java program to execute an SQL query.
List different types of JDBC drivers with their usage.
Identify various parts of JDBC URL and construct it as per need.
Use SQL to update the database records.
m
Use ResultSetMetaData class to fetch additional information about
lu
cu
the result set like column names.
ri
ur
List important methods of DatabaseMetaData class and their usage.
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Data is the most important part for any business application. Essentially, programs
are created to manage this business data. Consider an example of data about all
the employees in an organization. It is maintained in the files in different
departments like HR, Accounts and the department to which the employee
belongs to. In this case, same data is duplicated at multiple places. Extra computer
storage is needed to store these duplicate copies of data. Additionally, when the
data is stored at different locations, it is difficult to make the changes at all the
locations at the same time. This leads to a problem called data integrity. Data
integrity refers to the correctness of data maintained. For example, an employee
leaves the organization and the accounts department is unaware about it, the
salary processing will take place for that employee. Since each department being
an owner may modify their own copy making the data inconsistent. Hence control
over a group of records or data cannot be made uniform at the organizational
level. File system supports security at file level. Access can be given to an entire file
or denied to the entire file. This acts as a severe limitation when one wants to
control data at record level.
m
Data duplication or redundancy is greatly reduced. Data integrity is maintained as
lu
cu
the changes are done at one place in the database. All the applications can be
ri
ur
given selective access to the data items depending on the requirement. As the
lC
ia
data can be accessed at data item level rather than file level, security can be
c
ffi
controlled at data item level. Modern business applications use databases to store
|O
the data instead of files. Relational database management systems or RDBMS are
d.
Lt
widely used for this purpose. Examples of leading RDBMS softwares are Oracle,
ch
SQL Server, IBM DB2, Sybase, MySQL etc.
te
fo
In
ED
SE
of
s
ht
yrig
op
C
A database is a system which helps to organize, store and retrieve large amounts
of data easily. It is a set of related records and a set of programs to access this
data. It is an entire system that helps to enter, store and manage data, so it called
Database Management System (DBMS). Filing cabinet is used to file the papers.
New papers can be added to it and old unwanted papers can be removed. Changes
can be made to the existing papers. If any particular paper is required, it can be
retrieved. For easy and fast retrieval, index can be maintained. Sequence can also
be given these papers for easy maintenance and retrieval. DBMS is exactly like this
filing cabinet which is electronic.
Relational Databases or RDBMS is a type of database management system which
stores data in the form of rows and columns. There are many database objects like
stored procedures, index, triggers, sequence, view, etc. as shown in the above
diagram.
m
language and passed parameters to it. This special type of SQL queries are
lu
cu
called parameterized query. They execute faster than SQL.
ri
ur
Stored Procedure: Stored procedure by definition is a segment of code which
lC
ia
contains declarative or procedural SQL statements.
c
ffi
Index : Index is an additional data created in the database which allows faster
|O
access to the rows through use of pointers. Indexing of a table typically speeds
d.
Lt
up the data access from that table. It is a sorted list of rows accompanied by
ch
location of the row.
te
fo
Trigger: Trigger is a PLSQL program unit associated with a specific table which
In
ED
gets fired automatically whenever any user or application tries to modify the
SE
data from the concerned table in a predefined way. Trigger can be used to
of
apply business rules or to log all the changes in a particular data table.
s
ht
View: View is a logical or virtual table, based on a table or another view. View
op
C
does not have its own data but shows data from the base tables. Views can be
used to present relevant data from the same table to different users in
different format (view).
SQL is used to perform these operations such as addition, deletion, updating and
retrieval of data from the database.
SQL has three sub parts.
Data Definition Language (DDL) is a set of SQL commands used to create or
modify and delete database structures or objects such as tables, views etc. and
not actual data.
Examples of DDL commands are CREATE, ALTER, DROP.
Data Manipulation Language (DML) is a set of SQL commands which are used
to query, insert, update, and delete data stored in the database.
Examples of DML commands included are SELECT, INSERT, UPDATE, DELETE.
Data Control Language (DCL) is a set of commands for controlling access to the
data.
Examples of DCL commands included are GRANT, REVOKE.
m
lu
EMPLOYEE NO NUMBER(4)
cu
ri
ENAME VARCHAR2 (50)
ur
lC
ia
SAL NUMBER (5)
c
ffi
|O
Write SQL Queries for following.
d.
Lt
1. Select all employee names from employee table.
ch
2. Delete employee with employee no = 30.
te
fo
20000.
SE
of
s
ht
yrig
op
C
SQL is used to access the database. Application can be written in any language, for
example, Java, C#, VB.NET, C++, VB 6.0, etc. Consider an example of online
reservation system, banking application, etc. These applications need to access the
data or sometimes change the data in the database. Data access mechanisms are
required to do this task. They can be ODBC (Open Database Connectivity), JDBC
(Java Database Connectivity), DAO (Data Access Object), ActiveX Data Object
(ADO) and ActiveX Data Object on .NET platform (ADO.NET).
These mechanisms provide support in the form of different objects that interact
with lower level APIs (Application Programming Interfaces) to interact with the
respective database. These lower level APIs are called drivers. They provide an
interface to access the underlying database.
To access the data from database above are the typical steps. Let us understand
each of these steps in more details. We already know how to create and SQL
query.
m
Native-API partly Java Driver (Type 2)
lu
cu
ri
Net-Protocol All-Java Driver (Type 3)
ur
lC
Native Protocol All-Java Driver (Type 4)
iac
ffi
|O
d.
To get complete list of JDBC drivers use the following link
Lt
ch
http://industry.java.sun.com/products/jdbc/drivers
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Type 1 driver leverages ODBC driver implementation. It translates all JDBC calls to
ODBC (open database connectivity) calls and sends them to the ODBC driver. It is a
Java wrapper developed over ODBC API. It should be used only for prototyping and
is not recommended for production environment.
Advantage
Easily available as part of JDK.
Disadvantages
Limited to functionality of ODBC driver.
Not suitable for higher volume of transactions.
Slower in performance.
Example
sun.jdbc.odbc.JdbcOdbcDriver
m
lu
Example
cu
ri
com.ibm.db2.hcc.DB2Driver
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
Advantages
This driver is server-based. So, the vendor database is library not required
for client machines. it is fully written in Java and hence portable. It is suitable
for the web.
There are many opportunities to optimize portability, performance, and
scalability.
The net protocol can be designed to make the client JDBC driver very small
and fast to load.
It typically provides support for features such as caching (connections, query
results, and so on), load balancing, and advanced system administration such
as logging and auditing.
It is very flexible and allows access to multiple databases using one driver.
It is the most efficient amongst all driver types.
It essentially converts JDBC calls into vendor specific protocols thereby
eliminating need of native code installation at each client.
m
lu
backend server.
cu
In this case clients connect to database servers via an intermediate server
ri
ur
lC
component that acts as a gateway for multiple database servers.
ia
c
Example
ffi
|O
com.informix.jdbc.lfxDriver
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
Type 4 drivers typically make direct socket connections to the databases. They
convert the JDBC API calls to network calls using vendor-specific networking
protocols. Type 4 drivers generally offer better performance than their Type 1 and
Type 2 counterparts. These are preferred over other drivers, since there are no
additional libraries or middleware to install. Almost all major database vendors
provide Type 4 JDBC drivers.
Advantages
Type 4 drivers are completely written in Java. So we can achieve platform
independency. Number of translation layers is very less.
Performance is good.
Need not to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantages
With type 4 drivers, the user needs a different driver for each database
Example
oracle.jdbc.driver.OracleDriver
A Java application may use multiple databases to store data. These databases can
be accessed using different database drivers. The parameters required to obtain
connection may be different. In this situation, how to identify a specific driver is a
question. A JDBC URL is the answer. A database connection URL is a string that
DBMS JDBC driver uses to connect to a database. It can contain information such
as where to search for the database, the name of the database to connect to, and
configuration properties. The exact syntax of a database connection URL is
specified by your DBMS and JDBC driver documentation.
m
lu
cu
ODBC jdbc: odbc: dataSourceName
ri
ur
Driver jdbc:odbc:test
lC
iac
DB2 jdbc:db2:database_name
ffi
|O
Driver jdbc:db2:MyDB
d.
Inform jdbc:Informix- Lt
ch
te
ix sqli://<host>:<port>/<database_name>:INFORMIXSERVER=<sid>
fo
In
Driver jdbc:Informix-
ED
sqli://localhost:1025/MyInformixDB:INFORMIXSERVER=
SE
MyDBServer
of
s
ht
Oracle jdbc:oracle:thin:@host:port:service
rig
thin
y
jdbc:oracle:thin:@localhost:1521:oracle10g
op
Driver
C
Class.forName takes a string class name and loads the necessary class
dynamically at run time. When a driver is loaded, it registers itself with
DriverManager using registerDriver() method. The
getConnection() method of DriverManager class attempts to establish a
connection to the given database URL. The DriverManager attempts to select
an appropriate driver from the set of registered JDBC drivers.
Using Driver class
Code Example
String driverName="oracle.jdbc.driver.OracleDriver";
Driver driver= (Driver) Class.forName
(driverName).newInstance ();
Properties p=new Properties();
p.put ("user","java");
p.put ("password","java");
String
url="jdbc:oracle:thin:@192.168.1.100:1521:oracle9i";
m
lu
cu
Code Example
ri
ur
lC
ia
Properties props = new Properties ();
c
ffi
FileInputStream in = new FileInputStream
|O
("database.properties");
d.
props.load (in); Lt
ch
in.close();
te
fo
drivers);
SE
Statement
The Statement object returns a java.sql.ResultSet object that
encapsulates the results of query execution. This is an interface implemented by
driver vendors. The result set can be scrolled using a cursor for reading the data
values in the ResultSet.
Using Statement
1. Load the JDBC driver.
2. Get Connection.
3. Call CreateStatement.
4. Call executeQuery with SQL query as parameter.
5. Iterate over ResultSet to retrieve data.
6. Close the Statement object.
7. When you are finished using a Statement, call the method
Statement.close to immediately release the resources it is using. When
you call this method, its ResultSet objects are closed.
m
In JDK 7 and JDBC 4.1
lu
JDK7
cu
ri
In JDBC 4.1, which is available in Java SE release 7 and later,
ur
lC
you can use a try-with-resources statement to automatically
ia
close Connection, Statement, and ResultSet objects,
c
ffi
|O
regardless of whether an SQLException has been
d.
thrown. An automatic resource statement consists of a try
Lt
ch
statement and one or more declared resources.
te
fo
con.createStatement()) {
ED
} catch (SQLException e) {
SE
}
of
s
ht
yrig
op
C
Transactions
The day to day (real-life) applications like electronic money transfer, reservation
systems or accounting system involve a series of operations to complete a task.
This series of operations needs to be treated as an atomic unit - ‘a logical
transaction’ and we also need to have the facility for undoing changes under
certain circumstances.
For example, in a railway reservation system request to book a ticket for a
particular train against the cancellation of ticket for some other train. It is also
specified that the existing ticket is to be cancelled only if we are able to book it for
the other train.
1. This task involves two operations.
2. Cancellation of a ticket for one train and
3. Booking of a ticket for some other train.
These operations can be accomplished by executing a set of commands on the
reservation database. If one operation in a set of operations fails it is not
m
series of changes made using SQL commands like INSERT, UPDATE or DELETE can
lu
cu
be grouped together using transactions.
ri
ur
In a transaction, when manipulating the data in the database, the changes made
lC
ia
by us are not normally made permanent in the database until we give a command
c
ffi
to do so.
|O
d.
In a transaction, the changes made are not normally made permanent in the
Lt
database until we confirmed them. If changes are not confirmed, the database
ch
te
maintains its original state i.e. changes made during the database operations are
fo
In
undone.
ED
SE
Transactions in JDBC
op
C
The code block for transactions in JDBC is shown in the example below. By default
the property called AutoCommit is true, hence every single DML statement is
treated as a transaction and committed to the database. Hence when
setAutoCommit(false) is called, it disables it and allow the transaction
scope to contain more than one DML statements. Here this statement is
equivalent to Begin Transaction. All the statements inside the try block are part of
the transaction. If everything goes well, last statement to execute is Commit which
indicates success of the transaction.
m
lu
int amount) {
cu
try {
ri
ur
con.setAutoCommit (false);
lC
ia
from.balance=from.balance-amount; // withdraw from
c
ffi
one Account
|O
pst=con.prepareStatement ("update account set
d.
balance=? Where Lt
ch
accno=?");
te
fo
pst.setInt(1,from.balance);
In
T
s
r
Account
ht
a
rig
s
op
balance=?
a where
C
c
t accno=?");
i
o
pst.setInt (1, to.balance);
n pst.setInt (2, to.accountId);
int ii=pst.executeUpdate();
con.commit (); // if both are successful keep the
new state
} catch (Exception b) {
try {
con.rollback (); // if one of them fails undo
the other one
} catch (SQLException e) {
e.printStackTrace();
}
}
Transaction handling is an important part of database interactions
while creating business applications. Understand the transaction
mechanism in details.
|
SE
ED
In
Page 30
fo
te
ch
Lt
d.
|O
ffi
cia
lC
ur
ri cu
lu
m
m
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
and committed as individual
lu
cu
transactions. Otherwise, its SQL
ri
ur
statements are grouped into
lC
ia
transactions that are terminated
c
ffi
by a call to either the method
|O
commit or the method rollback
d.
Lt
ch
public void rollback()throws Drops all changes made since the
te
SQLException
fo
disabled.
y
op
C
m
lu
throws SQLException
cu
for sending parameterized SQL
ri
ur
statements to the database. A
lC
SQL statement with or without IN
ia
c
parameters can be pre-compiled
ffi
|O
and stored in a
d.
Lt PreparedStatement object.
ch
This object can then be used to
te
fo
multiple times.
ED
SE
of
s
ht
rig
y
op
C
Parameterized SQL is an SQL in which can pass the parameters at runtime while
you are executing it. Every database has a different way of implementation
parameterized query. Since they are cached by the database, they improve the
performance as compared to a non-parameterized query.
When database engine receives an SQL query it parses the query to find out any
syntax errors, then execution plan is prepared to access the data in most efficient
way. These steps are executed each time an SQL query is received. Databases
usually have a statement cache which stores the execution plan. This arrangement
facilitates reuse of execution plans for the statements which have been executed
previously, merely by substituting different parameters for each successive
execution.
PreparedStatement
PreparedStatement is Java way of performing parameterized query. The
PreparedStatement object contains an SQL statement that has already been
compiled. This means execution can be faster than that of Statement objects. It
m
appropriate setXXX() method before the statement is executed, where XXX
lu
cu
stands for data type. Being a subclass of Statement, PreparedStatement
ri
ur
inherits all the functionality of Statement.
lC
ia
c
ffi
|O
d.
Use PreparedStatement for better performance instead of
Lt
ch
Statement object in Java applications.
te
fo
In
ED
SE
Using PreparedStatement
of
1.
ht
rig
2. Set values for all the input parameters using setXXX() method. The first
y
op
the parameter to be set, and the second argument is the value to which the
parameter is to be set. Call appropriate methods from executeQuery,
executeUpdate.
3. Use clearParameters before using the same preparedStatement
object for successive call with different parameters.
4. In addition, it adds a whole set of methods which are needed for setting the
values to be sent to the database in place of the placeholders for IN
parameters. Also, the three methods execute, executeQuery, and
executeUpdate are modified so that they take no argument. The
Statement forms of these methods (the forms that take an SQL statement
parameter) should never be used with a PreparedStatement object.
5. Before a PreparedStatement object is executed, the value of each ‘?’
parameter must be set. This is done by calling a setXXX method, where XXX
is the appropriate type for the parameter. For example, if the parameter has a
Java type of long, the method to use is setLong().
m
lu
second argument.
cu
ri
ur
3. Call execute() to Invoke the stored procedure.
lC
ia
Extract the OUT parameter values using the getXXX() methods of
c
ffi
CallableStatement.
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
To retrieve the records or fields from a resultSet object, one needs to know
the structure, sequence, column names, data type of columns etc. In most of the
situations this information is known to the developer. Sometimes, it is necessary
to get this information dynamically at runtime. ResultSetMetaData is used
for this purpose. ResultSetMetaData interface provides information about
the structure of a particular ResultSet. It can be obtained by calling
getResultSetMetadata() method on any result set object.
ResultSetMetaData makes it possible for the user to display or manipulate
the data in the resultset without knowing its structure in advance. For example, a
generic method can be developed which would accept any result set object as a
parameter and display the contents of ResultSet in a Grid/Table fashion. The
beauty of this mechanism is that there is no hard-coding of column names or their
types.
m
int getColumnCount() Returns the number of columns in this
lu
cu
ResultSet object.
ri
ur
lC
String Gets the designated column's suggested title
ia
c
getColumnLabel()
ffi
for use in printouts and displays.
|O
String
d.
Note that type names returned by
getColumnTypeName() Lt getColumnTypeName() are database-
ch
te
query builder.
y
op
C
Business applications are developed with prior knowledge of the database and the
table structure. Sometimes, it is necessary to know information about the table
structures, features supported by database and so on dynamically at runtime. This
is like SYS Table space provided by Oracle. This table space stores information
about the data hence called meta-data. JDBC provides DatabaseMetaData
interface to dynamically discover information about database configuration,
system table structure, its capabilities, and so on. Using this interface one can
create an application to read and manipulate data or other objects like indexes,
and so on. independent of a particular database. This interface contains large
number of methods.
m
String Retrieves the name of this database
lu
cu
getDatabaseProductName() product.
ri
ur
lC
ResultSet getTables() Retrieves a description of the tables
iac
available in the given catalog
ffi
|O
ResultSet getlndexlnfo() Retrieves a description of the given
d.
Lt
table's indices and statistics.
ch
te
catalog.
op
C
Objectives
At the end of this chapter you will be able to:
List the types of ResultSet
Construct an application with scrollable and updatable ResultSet.
Construct an application for multiple queries with Batch Update.
List SQL Exception categories.
State the limitations of connected architecture.
Demonstrate disconnected architecture with JDBC.
m
type>,ResultSet.<update>);
lu
cu
ResultSet rs=stmt.executeQuery(“Select empId, empName,
ri
ur
empAddr, Age, Salary from empTable”);
lC
//Code for further processing goes here
iac
ffi
|O
d.
By default, ResultSet is TYPE_FORWARD_ONLY and
Lt
ch
READ_ONLY.
te
fo
m
avoid throwing an exception.
lu
cu
ri
Scroll Sensitive ResultSet
ur
lC
A Scroll Sensitive ResultSet is called so, because it is sensitive to changes being
iac
ffi
made to the underlying database. If more than one connection is manipulating the
|O
database and if the connection is of Scroll Sensitive type, changes made by
d.
Lt
another connection are generally visible to the client. Visibility of the changes is
ch
dependent upon the capabilities of the driver being used.
te
fo
Statement
In
ED
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIV
SE
E,
of
ResultSet.<update>);
s
ht
emp”);
y
op
C
m
lu
means that any operation on the resultset initiates a call to the
cu
ri
ur
database to ensure the freshness of the data. This leads to
lC
unnecessary overheads.
ia
c
ffi
|O
d.
Lt
ch
te
Scroll Sensitive ResultSets are a best fit for applications which use
fo
meaning.
yrig
op
C
By default, ResultSet can be used only for retrieval of the data (read-only) and
not for dynamic updation as and when required. As discussed earlier, default
ResultSet object obtained as follows:
//Database connectivity code
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“Select * from
empTable”);
//Further processing
It creates a forward-only and read-only kind of a ResultSet, which is a static
snapshot of a database at a given point of time. To change the data obtained using
the ResultSet, separate queries will have to be written and executed through
the code. This results in additional SQL programming burden and network
utilization. Instead, Java provides a work-around for this.
m
lu
type>,ResultSet.UPDATABLE);
cu
ResultSet rs=stmt.executeQuery(“Select * from
ri
ur
empTable”);
lC
ia
//Further processing
c
ffi
|O
It can be utilized to perform data manipulation operations without having to resort
d.
to writing SQL queries or having to initiate a network call.
Lt
ch
//scrollable and updatable resultset creation
te
rs.absolute(6);
ED
rs.updateRow();
of
s
ht
rig
y
rs.moveToInsertRow();
rs.updateString(“Name”,”Sony Corporation”);
rs.updateString(2,”make.believe”);
rs.insertRow();
Method Description
boolean Moves the cursor to the given row number in this
absolute(int row) ResultSet object.
void afterLast() Moves the cursor to the end of this ResultSet object,
just after the last row.
void beforeFirst() Moves the cursor to the front of this ResultSet object,
just before the first row.
void deleteRow() Deletes the current row from this ResultSet object and
from the underlying database.
m
lu
isAfterLast() ResultSet object.
cu
ri
ur
boolean Retrieves whether the cursor is before the first row in this
lC
isBeforeFirst() ResultSet object.
ia
c
ffi
boolean isFirst() Retrieves whether the cursor is on the first row of this
|O
ResultSet object.
d.
boolean isLast() Lt
ch
Retrieves whether the cursor is on the last row of this
te
ResultSet object.
fo
In
void
ED
void
s
moveToInsertRow()
rig
y
boolean
op
con.setAutoCommit(false);
m
stmt.addBatch("INSERT INTO departments VALUES (260,
lu
cu
'Shoe')");
ri
ur
stmt.addBatch("INSERT INTO emp_dept VALUES (1000,
lC
260)");
ia
c
ffi
|O
// submit a batch of update commands for execution
d.
Lt
int[] updateCounts = stmt.executeBatch();
ch
te
fo
catch block. For example, if a statement deep within the batch fails, whether the
of
entire batch should be failed or the statements prior to the failed query should be
s
ht
BatchUpdateException.
y
op
C
Select query does not work with batch updates, as the return
value is always the number of rows affected in the table.
m
process.
lu
cu
ri
Probably providing individual connection object to individual user could solve this
ur
lC
problem but creating an object at runtime while the applications are running and
ia
destroying after scope is a resource heavy process, which should be avoided so far
c
ffi
|O
as possible.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
As the requirements of all the users who wish to connect to the database is similar,
multiple connection objects having similar configurations can be created and held
at a specific location. Any user, who wishes to connect to the database, can find
the collection of the connections and request for an object to be made available.
As each user can have access to this shared space, the problem of having to wait
for a connection is solved. The collection of objects can also be created before the
application starts, when the processing requirements are relatively sparse.
This shared space where the collection of connection objects are kept is known as
connection pool. It acts as a go-between for the client code’s local connection
object and the actual physical connection linking it to the database. When the
connection is closed from the client’s code, the Connection object on local heap is
destroyed but the conduit to the database simply breaks the connection between
the client and the database. It then reverts back to another connection object
ready to serve another request within the pool.
m
pool in the shared workspace.
lu
cu
ri
This is normally achieved using a component called as DataSource.
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
Connection con = ds.getConnection();
lu
//perform database operations
cu
ri
ur
Declarative DataSource creation is a little complex and is handled in detail in
lC
ia
later chapters. In abstract, it involves creating and binding a DataSource object
c
ffi
using Java Naming and Directory Interface (JNDI). The client searches the JNDI tree
|O
using a virtual name associated with the data source. Internally this DataSource
d.
Lt
is wired to the connection pool which connects to the database.
ch
te
All these layers of indirection ensure that the final application becomes extremely
fo
In
flexible and independent of database vendors. Changes at the database levels are
ED
abstracted out at the DataSource level and the client code never has to bother
SE
}catch(SQLException exception){
System.out.println(exception.getMessage());
SQLException nextException =
exception.getNextException();
m
nextException.getNextException();
lu
}
cu
ri
}
ur
lC
ia
c
ffi
|O
With JDK 1.7, the same process has been simplified by making the
d.
Lt
SQLException class implement Iterable<Throwable> interface.
ch
JDK7
te
fo
In
ED
SE
try
s
ht
{
rig
}
catch(SQLException exception)
{
m
Method Description
lu
cu
String getMessage() Returns a description of the error.
ri
ur
lC
SQLException inherits this method from the
ia
java.util.Throwable class.
c
ffi
|O
int getErrorCode() Returns an integer value that corresponds to
d.
Lt
the database server or error code.
ch
te
String
fo
conventions.
of
s
ht
yrig
op
C
Iterable SQL Exception makes development effort faster and easier. Chain of
exception can be traversed faster and with lesser amount of coding.
Concrete Sub Classes help divide the SQLException hierarchy into three broad
categories to help deal with them in a better way. They are:
1. Transient
2. Recoverable
3. Non-transient
m
lu
the exception and initiate the entire transaction process again. Most of user-
cu
defined exceptions fall in this category. For example,
ri
ur
lC
InsufficientFundsException, InvalidChequeNumberException,
ia
etc.
c
ffi
|O
Non-Transient Exception
d.
Lt
There are situations where the problem cannot be dealt by the application, nor
ch
can it be solved by running the application once again; because running the
te
fo
application again with different circumstances does not solve the root cause of the
In
ED
example, FeatureNotSupportedException,
of
SQLSyntaxErrorException, SQLDataException.
s
ht
choose beforehand about ways to deal with the entire category of the said
op
C
exception.
try
{
//do something
}
catch(SQLTransientException sqltrex)
{
//do nothing
}
The example code will not do anything for all exceptions which belong to the
TransientException group, regardless of what specific exception is being
thrown.
Care should be taken that while initiating the transaction, the
previous connection object should be discarded and new one
obtained, either through connection pool or a new internally
created connection object.
m
{
lu
cu
int empno = rs.getInt(“empno");
ri
ur
String empname = rs.getString(“empname");
lC
}
ia
c
}
ffi
|O
catch(SQLException sqlErr)
d.
{
//perform exception code Lt
ch
te
} //resource released
fo
In
}
ED
As the statement object has been created with the try block, its scope is defined
SE
for the duration of the try block, as soon as try block finishes, the Statement object
of
s
In addition to the standard data types JDBC API provides support to numerous SQL
data types. These data types are mapped with interfaces in Java to provide the
freedom of implementation to the vendors and to build in a standard mode of
execution.
The most frequently used complex data type for JDBC is xLOB, where LOB stands
for Large OBjects. JDBC provides support to Binary Large Objects (BLOB), Character
Large OBjects (CLOB) and National Character Large OBjects (NCLOB). These data
types are usually used to represent character streams representing multimedia
files such as images, voice patterns, movie clips, audio sounds etc.
As the name suggests, BLOB objects are a collection of binary data items grouped
as a single entity, while CLOB is a collection of binary data items grouped as a
single entity. The difference is that CLOB usually has a specific character-encoding
associated with it to make sense out of the data being stored as binary streams.
NCLOB is a large object used for holding National Character Set and can hold data
as big as 4GB in size.
Usually, the actual data of these types of variables is kept in a separate holding
location (e.g., data warehouse) and a virtual reference is provided which acts as a
link to the data whenever required.
m
lu
Following code demonstrates working with large objects:
cu
ri
//Creating BLOB,CLOB and NCLOB objects
ur
lC
ia
c
Connection con = DriverManager. getConenction( url ,
ffi
|O
props);
d.
Blob aBlob = con.createBlob();
int numWritten = aBlob.setBytes(1, val); Lt
ch
te
fo
In
m
lu
byte[]getBytes(long pos, Retrieves all or part of the BLOB value that this
cu
ri
int length) Blob object represents, as an array of bytes.
ur
lC
long length() Returns the number of bytes in the BLOB value
ia
c
ffi
designated by this Blob object.
|O
long
d.
Retrieves the byte position in the BLOB value
position(Blob pattern, Lt
ch
designated by this Blob object at which
long start)
te
pattern begins.
fo
In
ED
represents.
y
op
m
lu
cu
ResultSet requires a live connection to the database to be
ri
ur
available at all points during its lifecycle.
lC
ia
This is called as connected architecture for database
c
ffi
|O
connectivity
d.
In situations where execution resources may not support
Lt
continuous network connectivity, this approach may fail
ch
te
of data inconsistency.
s
ht
yrig
op
C
ResultSet is a cursor which does not hold data but pointers to the actual data
values. Due to this, it becomes mandatory to hold a connection object alive even
when not actively using. This enables accessing it when any ResultSet
operation demands connectivity with the database. It may not be a problem under
typical scenarios. Situations where resources are scarce in terms of network
bandwidth or where data access instances are few and far between it is
recommended that the application should not control the network.
Database connectivity can be done either with a connected architecture or with a
disconnected architecture. ResultSet is part of the connected approach,
meaning if Client has a reference to a ResultSet object live during the
execution, a live connection to database will have to be maintained till the scope
of the ResultSet is valid. To reduce this drain on the resources, JDBC provides
components to manipulate the data using the disconnected architecture.
As disconnected components do not require live connection,
possibility of data inconsistency cannot be discounted, hence care
needs to be taken about using disconnected architecture.
m
lu
cu
Java supports disconnected architecture by way of RowSet.
ri
ur
A RowSet object holds tabular data
lC
ia
in a way that makes it more flexible
c
ffi
and easier to use than a resultset
|O
All RowSet Objects are derived from the ResultSet interface
d.
Lt
only. ch
All RowSet Objects are JavaBeans Components.
te
fo
Connected
ED
SE
Disconnected
of
s
ht
rig
y
op
m
lu
cu
Connected RowSet object:
ri
ur
A Connected RowSet object uses JDBC Driver, makes the
lC
connection with database and maintains that connection
iac
throughout its life span.
ffi
|O
e.g. JDBCRowSet
d.
Disconnected RowSet Object :
Lt
ch
A disconnected RowSet object makes a connection to a data
te
data back to the data source. After reading data from and
ED
from it.
of
e.g. CachedRowSet
s
ht
yrig
op
C
m
lu
CachedRowSet maintains its data in cache, so maximum operations with cache
cu
ri
only rather than database. CachedRowSet is super interface for all other
ur
lC
disconnected RowSet objects.
ia
c
Creating a CachedRowSet
ffi
|O
ResultSet rs= st.executeQuery("select * from emp");
d.
Lt
CachedRowSet cachedRowSet=new CachedRowSetImpl();
ch
cachedRowSet.populate(rs);
te
fo
In
or
ED
rs.setUrl("jdbc:oracle:thin:@oracleserver:1521:orcl");
of
s
rs.setUsername("mydb");
ht
rig
rs.setPassword("password123");
y
op
rs.execute();
Web applications are simple, intuitive and responsive that let their users get work
done online with less effort and time. Today, web applications are gaining
popularity since they are a gateway to the online market. This chapter covers
exhaustive information about web technologies.
Objectives
At the end of this chapter you will be able to:
Define a web site is and list types of web sites.
List basic terminologies of web applications.
List various components of web application architecture.
Define a browser and list popular browsers.
List scripting languages used for creating interactive web pages.
m
lu
may become over-burdened and have performance issues. Due to limited
cu
ri
bandwidths, the number of clients that can connect with the server is also limited.
ur
lC
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
known as a web server. The software which is used to manage the application on
cu
ri
the physical machine is also known as a Web Server. From the developer
ur
lC
perspective a Web Server is the software which is used to manage the access to
ia
the web application. It does not have the capability to host applications. At most it
c
ffi
|O
can serve static (HTML) pages.
d.
Apache HTTP Server is an example of a web server.
Lt
ch
Web Container
te
fo
web application, execute the applications lifecycle and manage the ecosphere in
of
which the application runs. Usually a web container comes bundled with a web
s
ht
Web Browser
As discussed earlier, text based data is the only way by which dissimilar systems
can share data with each other. The data being transferred from one end to
another needs to be read, understood and presented to the user in a usable
format. Web Browser is a software application that understands and translates
HTML content. It allows the user to interact with a remote system by converting
his/her requirements into text based content and using internal mechanisms to
transfer this content to a processing component.
The component that provides services to the user is known as a resource and it is
identified using a Uniform Resource Identifier (URI) or a Uniform Resource Locator
(URL). Simply put, a browser allows a user to connect with the internet and
retrieve or interact with a resource that can follow the text based data transfer
rules (HTTP) and is made up of HTML. A web browser (or client) is often referred
to as a user agent (UA).
The major web browsers in use are:
Internet Explorer (IE) – Developed by Microsoft Corporation.
m
Chrome – A web browser developed by Google Inc.
lu
cu
ri
A web browser usually has a Graphical User Interface, which helps the user to
ur
lC
understand the content better and faster.
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
cu
ri
ur
lC
Every browser handles the rendering of HTML and CSS and the
ia
processing of JavaScript slightly different, requiring tests to be run
c
ffi
|O
on multiple browsers to ensure web application works in all
d.
environments.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Web Container
A web container is a container which contains web applications.
In three (or more) tier architecture, the user interacts with the system using the
presentation layer, which deals only with the user input and output related
activities. The business logic is hidden from the user. The component for business
logic is accessed by all the clients at the same time and is normally kept at a
central public place known to all existing and potential users (usually by way of a
public URL). As the URL is public there is a requirement to cater to multiple user
requirements at the same time. To provide concurrent access the business logic
needs to be enveloped into threading mechanism, whereby, each client can
interact with the processing component by individual threads.
Since the business logic component focuses only on the business rules and should
not be catering to application execution related activities, a separate component
which provides such services is required. This component provides services to the
m
lu
This means delivery of HTML documents and any additional content that may be
cu
ri
included by a document, such as images, style sheets and scripts. Though the most
ur
lC
common use of web servers is to host web sites, they could also be used for data
ia
storage or for running enterprise applications.
c
ffi
|O
d.
Lt
A web container is different from a web server. Web server
ch
te
The most famous and popular of all web servers is Apache Tomcat
C
developed by the Apache Software Foundation. Not only is Apache free but
it is also available for several operating systems including Windows,
Macintosh and Linux/Unix.
2. Internet Information Services (IIS) –
It was formerly called as Internet Information Server. It is an integral part of
Windows Server family of products. It is a web server application and
includes a set of modules also referred to as extensions. These modules are
individual features that the server uses to process HTTP requests.
m
The methods are as described below:
lu
cu
ri
GET
ur
lC
It is used to retrieve whatever data is identified by the Uniform Resource Locator
iac
(URL), where the URL refers to a data-producing process, or a script which can be
ffi
|O
run by such a process. The required data is rendered as HTML and returned to
d.
client browser
Lt
ch
POST
te
fo
Submits data to be processed (e.g., from an HTML form) to the identified resource.
In
ED
The data is included in the body of the request. It is the responsibility of the
SE
component existing on the server side to retrieve the data and process it.
of
s
ht
rig
m
lu
submitting data to the server for processing. The methods can be
cu
used interchangeably but not recommended.
ri
ur
lC
ia
c
ffi
|O
For additional reading on HTTP specification visit the link below
d.
Lt
http://www.w3.org/Protocols/
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
It indicates that further action needs to be
lu
Choices
cu
taken by the user agent in order to fulfil the
ri
ur
request. It indicates multiple options for the
lC
resource that the client may need to follow.
ia
c
ffi
404 Not Found The requested resource does not exist.
|O
d.
500 Server An unexpected server error. The most
Lt
ch
Error common cause is a server-side script that has
te
fo
correctly.
SE
of
s
ht
y rig
op
C
m
</html>
lu
cu
The connection is closed by the server (or client)
ri
ur
lC
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
lu
Advantages of client-side scripting
cu
ri
Better scalability as less work done on server.
ur
lC
Reduces traffic network as there is no round trip to server.
iac
One can create UI constructs not inherent in HTML like:
ffi
|O
Drop-down and pull-out menus
d.
Tabbed dialogs
Lt
ch
Cool effects such as animation can be given.
te
fo
server.
ED
size, position, and attributes of the new window (e.g. menus, toolbars, etc.,
s
ht
are visible).
rig
Changing images as the mouse cursor moves over them; this effect is often
y
op
elements.
Popular scripting languages are: JavaScript and VBScript.
JavaScript is an interpreted programming or script language from Netscape. It is
similar in capability to Microsoft's Visual Basic, In general, script languages are
easier and faster to code than the more structured and compiled languages such
as C and C++. Script languages generally take longer to process than compiled
languages, but are very useful for shorter programs.
JavaScript is used in web site development to do following things:
Perform client side validations
Automatically change a formatted date on a web page
Cause a linked-to page to appear in a popup window
Cause text or a graphic image to change during a mouse rollover
Display pull down or popup menu.
m
lu
Server Pages before the page is sent to the requestor. Both Microsoft and
cu
Netscape browsers support JavaScript, but sometimes in slightly different ways.
ri
ur
lC
VBScript
iac
ffi
VBScript is an interpreted script language from Microsoft that is a subset of its
|O
Visual Basic programming language designed for interpretation by Web browsers.
d.
Lt
VBScript can be compared to other script languages that can be used on the Web,
ch
including: JavaScript by Netscape, Tcl by Sun Microsystem, and UNIX-derived Perl
te
fo
etc.
In
ED
to work with an interpreter that comes with a web browser - that is, at the user or
of
client end of the web client/server session. VBScript is designed for use with
s
ht
rig
Microsoft's Internet Explorer browser together with other programs that can be
y
op
run at the client, including ActiveX controls, automation servers, and Java applets.
C
Although Microsoft does support Netscape's JavaScript (it converts it into its own
JScript), Netscape does not support VBScript. For this reason, VBScript is best used
for intranet web sites that use only the Internet Explorer browser.
Server-side Scripting
In server-side scripting, web applications are executed at server-side. They are
created using languages like Perl, PHP, and server-side VBScript, and server-side
JavaScript. The output is displayed in the web browser in a format understood by
the browser. The server side scripting code is not visible to the client.
The server-side program can receive input from URL parameters, HTML form data,
cookies, and HTTP headers. It can access server-side databases, e-mail servers,
files, mainframes, and so on.
Following are the advantages of server-side scripting:
Distribution of application code not required.
Never exposes the server-side script code.
Emits the HTML markup based on the user’s input data.
m
response based on the user's inputs, access rights, or queries into data
lu
cu
stores.
ri
ur
Security is another advantage of server-side processing because only the
lC
ia
results of code processing are sent to the web browser keeping confidential
c
ffi
information such as passwords, credit card numbers, and even the code, on
|O
the server.
d.
Lt
In addition to the server-side scripts, there are other programming constructs
ch
te
Technology Description
SE
application
ht
rig
Development
C
HTML is the basic building block for creating a web application. HTML also ensures
that the application reaches multitudes rather than being dependent on the
technology being used. A user’s first look at the web application is always through
the HTML content. It is mandatory to generate HTML content that is pleasing,
user-friendly and usable. This can be possible only if the developer also has
knowledge about the HTML.
This chapter covers basics of HTML, its various tags, forms, embedded JavaScript
and event handling with JavaScript.
Objectives
At the end of this chapter you will be able to:
Explain HTML syntax.
Construct an HTML page using basic tags like text field, radio button.
Construct an HTML form for submitting data.
Construct an HTML page with JavaScript embedded.
Construct an HTML page with event handling mechanism enabled with
JavaScript.
Due to cross-platform data transfer issues, text based data transfer is preferred
over object based data transfer. The language made up of textual data and control
sequence is called as HTML. Hyper Text Markup Language (HTML) is a language of
the internet. As HTML is defined to be a standard language all the browsers
understand the individual markups and the actions associated with them.
HTML Tags
HTML markup tags are usually called HTML tags. They are keywords surrounded by
angle brackets like <html>. HTML tags normally come in pairs like <b> and </b>.
The first tag in a pair is the start tag; the second tag is the end tag. Start and end
tags are also called opening tags and closing tags.
HTML documents are also known as web pages. HTML documents contain HTML
tags and plain text. The purpose of a web browser (like Internet Explorer or
Firefox) is to read HTML documents and display them as web pages. The browser
does not display the HTML tags, but uses the tags to interpret the content of the
page.
m
<p>My first paragraph.</p>
lu
cu
</body>
ri
</html>
ur
lC
The text between <html> and </html> describes the web page.
iac
ffi
The text between <body> and </body> is the visible page content.
|O
The text between <h1> and </h1> is displayed as a heading.
d.
Lt
The text between <p> and </p> is displayed as a paragraph.
ch
te
HTML can be written and edited using many different editors like Dreamweaver
fo
In
HTML Document
<html>
<body>
<p>This is my first paragraph.</p>
</body>
</html>
The example above contains three HTML elements.
The <p> element:
<p>This is my first paragraph.</p>
The <p> element defines a paragraph in the HTML document. The element has a
start tag <p> and an end tag </p>.
The <body> element:
<body>
<p>This is my first paragraph.</p>
</body>
m
lu
<html>
cu
ri
ur
lC
<body>
ia
<p>This is my first paragraph.</p>
c
ffi
</body>
|O
d.
</html> Lt
ch
te
The <html> element defines the whole HTML document. The element has a start
fo
In
tag <html> and an end tag </html>. The element content is another HTML
ED
element (the body element), the contained element is known as a nested HTML
SE
element.
of
s
ht
Most HTML elements can be nested (can contain other HTML elements). HTML
rig
m
lu
Use Lowercase Attributes. Attribute names and attribute values are
cu
ri
case-insensitive. In some rare situations, when the attribute value
ur
lC
itself contains quotes, it is necessary to use single quotes.
ia
c
ffi
However, the World Wide Web Consortium (W3C) recommends lowercase
|O
attributes / attribute values in their HTML 4 recommendation. Newer versions of
d.
Lt
(X)HTML will demand lowercase attributes.
ch
te
Standard attributes
fo
In
ED
Attribute Description
SE
classname
of
Id
rig
style
C
Look and feel of web pages can be obtained using certain tags.
Heading
HTML headings are used for displaying text as headings. Headings should not be
used to make text BIG or bold. Search engines use headings to index the structure
and content of web pages. Since users may skim pages by its headings, it is
important to use headings to show the document structure.
H1 headings should be used as main headings, followed by H2 headings,
then the less important H3 headings, and so on.
The <hr/> tag creates a horizontal line in an HTML page. The <hr>
element can be used to separate content.
Paragraphs
Paragraphs are defined with the <p> tag. Most browsers display HTML correctly
even if there is no end tag.
<p>This is a paragraph</p>
<p>This is another paragraph</p>
m
The example above works in most browsers, but it is not reliable. Forgetting the
lu
cu
end tag can produce unexpected results or errors.
ri
ur
lC
ia
c
Future version of HTML will not allow you to skip end tags. Use the
ffi
|O
<br/> tag if you want a line break (a new line) without starting a
d.
new paragraph.
Lt
ch
In XHTML, XML, elements with no end tag (closing tag) are not
te
allowed.
fo
In
The <br /> element is an empty HTML element. It has no end tag. Large or small
rig
y
screens and resized windows will create different results. With HTML, output
op
C
cannot be changed by adding extra spaces or extra lines in the HTML code. The
browser removes extra spaces and extra lines when the page is displayed. Any
number of lines counts as one line, and any number of spaces count as one space.
Comments can be inserted into the HTML code to make it more readable and
understandable. Comments are ignored by the browser and are not displayed.
HTML uses tags like <b> and <i> for formatting output, like bold or italic text.
These HTML tags are called formatting tags. Often <strong> renders as <b>,
and <em> renders as <i>. However, there is a difference in the meaning of these
tags. <b> or <i> defines bold or italic text only. <strong> or <em> means that
the text needs to be rendered in a way that the user understands as "important".
All major browsers render strong as bold and em as italics. However, if a browser
wants to make a text highlighted with the strong feature, it might be cursive and
not bold.
The <font> tag is deprecated in HTML 4, and removed from HTML 5. The World
Wide Web Consortium (W3C) has removed the <font> tag from its
recommendations. Instead of <font> tag the style attribute for the component
should be used.
m
color.
lu
cu
</font>
ri
</p>
ur
lC
<p>
ia
c
<font size="3" face="verdana" color="blue”>
ffi
|O
This paragraph is in Verdana, size 3, and in blue text
d.
color.
</font> Lt
ch
te
</p>
fo
In
ED
SE
CSS was introduced together with HTML 4, to provide a better way to style HTML
elements. CSS can be added to HTML in:
4. Cascading Style Sheet files (CSS files)
5. The <style> element in the HTML head section
6. The style attribute in single HTML elements
The text-align property makes the old <center> tag obsolete.
A hyperlink (or link) is a word, group of words, or image that can be clicked to
jump to a new document or a new section within the current document. When the
cursor hovers over a link in a web page, the arrow turns into a little hand.
Links are specified in HTML using the <a> tag.
The <a> tag can be used in two ways:
To create a link to another document, by using the href attribute
To create a bookmark inside a document, by using the name attribute
The target attribute specifies where to open the linked document.
Tables are defined with the <table> tag. A table is divided into rows (with the
<tr> tag), and each row is divided into data cells (with the <td> tag). td stands
for "table data," and holds the content of a data cell. A <td> tag can contain text,
links, images, lists, forms, other tables, etc. Header information in a table is
defined with the <th> tag. All major browsers display the text in the <th>
element as bold and centered.
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items are marked with bullets. An ordered list starts with the <ol> tag.
Each list item starts with the <li> tag. The list items are marked with numbers.
HTML forms are used to pass data to a server. A form can contain input elements
like text fields, checkboxes, and radio-buttons, submit buttons and more. A form
can also contain select lists, textarea, fieldset, legend, and label elements. The
<form> tag is used to create an HTML form.
A submit button is used to send form data to a server. The data is sent to the page
specified in the form's action attribute. The file defined in the action attribute
usually does something with the received input.
Following are the input types that are used on a form:
Input type Description
Text Defines a one-line field that accepts text
input
Password Defines a password field for accepts hidden
text input
Radio Defines a set of options as radio buttons
Checkbox Defines a set of options as check boxes
Submit Defines a button for submitting data
m
The characters in a password field are masked (shown as asterisks).
lu
cu
Radio buttons let a user select only one of a limited number of
ri
ur
lC
choices.
iac
Checkboxes let a user select one or more options of a limited
ffi
|O
number of choices.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
The <select> tag is used to create a drop-down list. The <option> tags inside
the <select> element define the available options in the list.
m
lu
Java (developed by Sun Microsystems) is a powerful and much more
cu
ri
complex programming language used for building enterprise
ur
lC
applications.
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
To insert JavaScript into an HTML page, the <script> tag is used. Inside the
<script> tag the type attribute is used to define the scripting language. The
<script> and </script> tags tell where the JavaScript starts and ends.
Unlimited number of scripts can be put in the document, and scripts can exist in
the body as well as in the head section at the same time. It is a common practice
to put all functions in the head section, or at the bottom of the page. This way
they are all in one place and do not interfere with page content.
JavaScript is case sensitive; therefore care should be taken to use the correct cases
when writing JavaScript statements, create or call variables, objects and functions.
A JavaScript statement is a command to a browser. The purpose of the command
is to tell the browser what to do. The semicolon is optional, and the browser
interprets the end of a line as the end of the statement.
JavaScript can also be placed in external files. External JavaScript files often
contain code to be used on several different web pages. External JavaScript files
have the file extension .js.
m
lu
attribute of the <script> tag.
cu
ri
ur
JavaScript statements can be grouped together in blocks. Blocks start with a left
lC
curly bracket ({), and end with a right curly bracket (}). The purpose of a block is to
ia
c
ffi
make the sequence of statements execute together. Browsers that do not support
|O
JavaScript display JavaScript as page content. To prevent them from doing this, and
d.
Lt
as a part of the JavaScript standard, the HTML comment tag should be used to
ch
"hide" the JavaScript.
te
fo
In
comment tag <!-- before the first JavaScript statement, and a -->
SE
JavaScript closely follows the ‘C’ coding structure and naming conventions. It
allows the manipulation of the data using variables and variable operations.
Some of the operations available through JavaScript are
Operator Description
+ Addition of two expressions
- Subtraction of two expressions
* Multiplication of two expressions
/ Division of two expressions
% Modulus of two expressions
++ Increment of an expression
-- Decrement of an expression
+= Addition of an expression
-= Subtraction of an expression
*= Multiplication of an expression
/= Division of an expression
m
lu
!= Not equal
cu
> Greater than
ri
ur
lC
< Less than
ia
>= Greater than or equal to
c
ffi
|O
<= Less than or equal to
d.
&& And condition
Lt
ch
|| Or condition
te
! Not condition
fo
In
ED
SE
of
s
ht
yrig
op
C
m
}
lu
</script>
cu
ri
ur
The if....else statement should be used when a piece of code is to be
lC
executed if a condition is true, and there is an alternate code to be executed when
ia
c
ffi
the condition is false.
|O
<script type="text/javascript">
d.
Lt
//If the time is less than 10, you will get a "Good
ch
morning" greeting.
te
fo
. . .
ED
{
of
s
document.write("Good morning!");
ht
rig
}
y
op
else
C
{
document.write("Good day!");
}
</script>
Use if....else if...else statement to select one of several blocks of
code to be executed.
. . .
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>=10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
m
lu
for - loops through a block of code a specified number of times
cu
ri
while - loops through a block of code while a specified condition is true
ur
lC
The for Loop
iac
ffi
for loop is used when you know in advance how many times the script should
|O
run.
d.
Lt
ch
. . .
te
for (i=0;i<=5;i++)
fo
In
{
ED
document.write("<br />");
of
}
s
ht
. . .
yrig
op
The while loop loops through a block of code while a specified condition is true.
. . .
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
. . .
In certain situations the application may want to bring the user’s attention to a
specific event, data or action. This needs to be achieved in such a way that the
user has no option but to take a look at result generated by the application. This
action is called as notification. JavaScript allows notifying the user in three
different ways.
Alert Box
An alert box is often used if information is to be passed on to the user and ensure
that user notices it. When an alert box pops up, the user will have to click OK to
proceed.
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
m
</body>
lu
cu
A confirm box is often used if the user needs to verify or accept something. When
ri
ur
a confirm box pops up, the user will have to click either "OK" or "Cancel" to
lC
ia
proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel",
c
ffi
the box returns false.
|O
. . .
d.
<function show_confirm() Lt
ch
{
te
fo
if (r==true)
SE
{
of
}
ht
rig
else
y
op
{
C
m
document.write("Hello " + name + "! How are you
lu
today?");
cu
ri
}
ur
lC
}
ia
</script>
c
ffi
|O
</head>
d.
<body>
Lt
<input type="button" onclick="show_prompt()"
ch
te
</body>
In
ED
</html>
SE
of
s
ht
rig
y
op
C
To keep the browser from executing a script when the page loads, the script
should be written inside a function. A function contains code that will be executed
by an event or by a call to the function. Developer may call a function from
anywhere within a page (or even from other pages if the function is embedded in
an external .js file).
Functions can be defined both in the <head> and in the <body> section of a
document. However, to ensure that a function is read or loaded by the browser
before it is called, it is recommended to put functions in the <head> section.
A JavaScript function has syntax similar to ‘C’ programming language. The keyword
function identifies start of the function and the last closing bracket (}) defines
the end.
If a variable is declared using "var", within a function, the variable can only be
accessed within that function. When the function completes, the variable is
destroyed. These variables are called local variables. If a variable is declared
m
lu
cu
function functionName()
ri
{
ur
lC
// function code
ia
c
}
ffi
|O
Syntax of writing function with arguments is as follows:
d.
Lt
// var1,var2 are values passed into the function.
ch
{
In
ED
// function code
SE
}
of
s
ht
rig
y
op
C
By using JavaScript, dynamic web pages can be created. Events are actions that are
detected by JavaScript through the browser.
Every element on a web page has certain events which can trigger a JavaScript. For
example, when a user clicks a button on the HTML page, the button click event is
said to be generated and developer can write code to handle (perform against)
this event.
Examples of events:
A mouse click
A web page or an image loading
Mouse hovering over a hot spot on the web page
Selecting an input field in an HTML form
Submitting an HTML form
A keystroke
m
onChange
lu
On state change of a component. For
cu
example, data entry in a text field.
ri
ur
lC
OnLoad On page load
ia
c
ffi
onFocus When a component gains focus for data
|O
entry
d.
onBlur Lt When a component loses focus
ch
te
onMouseOver
fo
component.
ED
SE
of
s
ht
yrig
op
C
XML is eXtensible Markup Language. Unlike HTML tags, which are primarily used
to control the display and appearance of data, XML tags are used to define the
structure and data types of the data itself. Before using the XML file for any kind of
data processing, the files have to be verified for correctness and validity. XML
Parsers (SAX and DOM) provide the functionality for parsing XML files.
This chapter covers XML, its uses, XML components and their use, and XML
parsers (SAX and DOM).
Objectives
At the end of this chapter you will be able to:
Define XML and list its various usages.
List different components of XML and their usage.
Describe Simple API for XML (SAX) and Document Object Model (DOM).
Demonstrate the use of SAX and DOM parsers.
m
XML is Extensible Markup Language
lu
cu
ri
A tag-based meta language
ur
lC
Designed for structured data representation
iac
ffi
Represents data hierarchically (in a tree)
|O
Provides context to data (makes it meaningful)
d.
An open W3C standard Lt
ch
te
(SGML).
ED
SE
of
s
ht
yrig
op
C
XML is eXtensible Markup Language. XML and HTML have different goals: HTML is
designed to display data and is focused on how data looks, while XML is designed
to describe data and focuses on what data is. Like HTML, XML is also a passive
component. While XML tags can be used to describe the structure of an item such
as a purchase order, it does not contain any code which can be used to send that
purchase order, process it, or ensure that it is filled. Other component must have
the code to do these operations using the XML data files.
XML uses a set of tags to define elements of data. Each element encapsulates a
piece of data that may be very simple or very complex. A developer can define an
unlimited set of XML tags. For example, XML tags can be defined to declare data
from a purchase order, such as the price, tax, shipping address, billing address, and
so on.
The XML specification describes the XML data format and grammar and also
specifies two-tier client architecture for handling XML data. The first tier is the
XML Processor (also known as the XML parser). The parser ensures that the
presumed XML data is well-formed (has the correct structure and syntax), and may
m
As the XML file is made up of tags and sub-tags that are interlinked, the parsers
lu
cu
may create an in-memory tree structure representing the XML contents. This tree
ri
ur
structure helps faster data searches and manipulations.
lC
ia
XML rules are governed by an open source body World Wide Web Consortium
c
ffi
|O
(W3C), which regulates the structure and direction for XML technology
d.
development.
Lt
XML is a relatively a new markup language, but it is a subset of, and is based upon
ch
te
Characteristics of XML
SE
of
Extensibility
yrig
op
XML is a highly extensible and open ended markup language. XML provides a basic
C
syntax but does not define the actual tags; the tag set can be extended by anyone
for their own purpose.
Simplicity
XML is a very simple, hierarchical data representation.
Separation of semantics and representation
XML is all about the description of data and does not say anything about its
presentation.
XML works with internet
XML is based upon a simple text format. XML document is divided into two parts
as tags and the data. XML also uses existing Internet protocols, software, and
specifications wherever possible, for easier data processing and transmission.
m
lu
XML documents can use much of the infrastructure already built for HTML,
cu
ri
including the HTTP protocol and some browsers. HTTP allows XML to be
ur
lC
transferred across firewalls.
ia
XML parsing is well defined and widely implemented, making it possible to
c
ffi
|O
retrieve information from XML documents in a variety of environments.
d.
Applications can rely on XML parsers to do some structural validation, as
Lt
well as data type checking (when schemas are used).
ch
te
internationalized documents.
ED
XML documents are broken into several distinct components, each of which can be
created and modified separately, giving XML its strength of focused and
independent document processes. XML documents are modular and can be
extremely distributed, referencing components on various file systems, but
retaining the logic. The main parts of an XML document metadata are: the XML
SGML declaration, which is fixed and generally understood by XML-compliant
tools; the document type definition, which is the foundation of and used in valid
XML documents, and the document instance, in which the content of the
document is described by markup.
The XML document content has following components:
Elements
Elements are a discrete unit of content within a marked up document. An element
begins and ends with the mark-up tag that delimits and defines it. They can
contain sub-elements.
m
lu
marked up. They occur as name-value pairs ( name="value").
cu
ri
ur
The value of an attribute should be always quoted. Writing attributes in user
lC
defined tags should be avoided. A "Well Formed" XML document is a document
iac
that conforms to the XML syntax. The rules are defined in Document Type
ffi
|O
Definition (DTD).
d.
XML Prologue Lt
ch
te
All XML documents should have an XML prologue that states that the document is
fo
In
an XML document. The XML prologue must be the first thing in the document.
ED
SE
of
s
ht
yrig
op
C
m
lu
cu
A "Valid" XML document is a "Well Formed" XML
ri
ur
document, which also conforms to the rules of a
lC
Document Type Definition (DTD).
ia
c
ffi
DTD defines the structural specifications of an XML file.
|O
All elements and their attributes
d.
Lt
Relationship between elements
ch
te
m
lu
case, what follows "SYSTEM" is a URL naming the DTD file.
cu
ri
ur
<!DOCTYPE web-app SYSTEM “../path/to/dtd/file”>
lC
ia
The PUBLIC keyword allows a non-specific reference to a DTD via a URI, even via a
c
ffi
secondary (specific) URI.
|O
d.
The PUBLIC keyword is provided for well-known vocabularies.
Lt
ch
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
te
Transitional//EN"
fo
In
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
ED
transitional.dtd">
SE
of
s
ht
The primary use of an XML file in any application is to define the configurations or
to store the data. Configuration related information (data) or the data required for
applications need to be validated first, before it can be used within the application.
The application in question is created for business logic, and so it should not be
burdened with the task of XML checking. Therefore a component is needed whose
task will be to check the correctness of the XML file.
Java provides two approaches for checking the correctness, namely SAX (Simple
API for XML) and DOM (Document Object Model). These are also known as XML
Parsing approaches.
Simple API for XML (SAX)
SAX is a set of API which helps read the XML file sequentially. In this approach, the
document is read tag-by-tag and compared with the definitions (DTD, Schema) if
required. If there are any discrepancies in the construct of the XML structure,
these are caught at the time of accessing the documents. SAX APIs work on event
driven mechanism and call back methods. Each event (tag related) is trapped and
associated with one call-back method, which contains the code for executions.
m
lu
DOM works on the principles of tree structures. Here the whole file is read (using
cu
SAX) and converted into a tree structure, which is then used to traverse for
ri
ur
lC
accessing different tags within the file. The main advantage of this approach is that
ia
the tags can be accessed randomly because all the tags are available in the
c
ffi
|O
memory at any given point of time (after the files has been read into memory),
d.
unlike SAX, where the access is always sequential. There are no rules for deciding
Lt
when to use SAX or DOM, but the conventionally, SAX is used when file sizes are
ch
te
huge, as converting the entire file into memory would require more memory
fo
In
resources.
ED
SE
of
m
lu
cu
XML Schema is an XML-based alternative to DTD.
ri
ur
An XML schema describes the structure of an XML document.
lC
ia
The XML Schema language is also referred to as XML Schema
c
ffi
Definition (XSD).
|O
Schema specifies the structure of XML document.
d.
Lt
A Schema is useful for validating XML document content.
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
lu
cu
ri
It’s Not XML
ur
lC
XML document is written in one language and the
iac
ffi
grammar of that document is written using another
|O
language (DTD) which is bad, inconsistent.
d.
Lt
ch
DTD support a very limited capability for specifying
te
data types.
fo
In
ED
SE
of
s
ht
yrig
op
C
XML Schemas are used in most web applications as a replacement for DTDs. Here
are some reasons:
They are extensible to future additions
They are richer and more powerful than DTDs
They are written in XML
They support data types
They support namespaces
One of the greatest strength of XML Schemas is the support for data types. It is
also easier to do the following:
describe allowable document content
validate the correctness of data
work with data from a database
define data facets (restrictions on data)
define data patterns (data formats)
convert data between different data types
m
lu
Schema for application configuration are:
cu
ri
No need to learn a new language
ur
lC
A simple text-based XML editor can be used to edit Schema files
ia
c
A simple text-based XML parser can be used to parse Schema files
ffi
|O
The Schema can be manipulated with the XML Document Object Model
d.
(DOM(
Lt
ch
The Schema can be transformed with eXtensible Stylesheet Language
te
fo
Transformation (XSLT).
In
ED
sync for understanding the data. With XML Schemas, the sender has to describe
ht
rig
in other countries as 10 March. However, an XML element with a data type like
this:
<date type="date">2011-10-03</date>
ensures a mutual understanding of the content, because the XML data type "date"
requires the format "YYYY-MM-DD".
Well-Formed is not enough
Even if documents are well-formed they can still contain errors, and those errors
can have serious consequences, as the DTD cannot help match the data with data-
types. Hence, XML Schemas are used.
m
<?xml version="1.0"?>
lu
cu
<note
ri
ur
xmlns="http://www.w3schools.com"
lC
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
ia
c
ffi
xsi:schemaLocation="http://www.w3schools.com note.xsd">
|O
<to>Tove</to>
d.
<from>Jani</from> Lt
ch
<heading>Reminder</heading>
te
fo
</note>
ED
SE
of
s
ht
rig
y
op
C
As discussed earlier, an XML file can be parsed using an XMLParser. There are two
possibilities available for parsing an XML document. I) Simple API for XML
Processing (SAX) II) Document Object Model (DOM).
The example illustrates the code for building a SAX Parser.
public class SAXRead {
static public void main(String[] arg) {
String filename = null;
if (arg.length == 1) {
filename = arg[0];
} else {
usage();
}
// Create a new factory that will create the parser
.
SAXParserFactory spf = SAXParserFactory.newInstance
m
XMLReader reader = null;
lu
try {
cu
ri
SAXParser parser = spf.newSAXParser();
ur
lC
reader = parser.getXMLReader();
ia
} catch (Exception e) {
c
ffi
|O
System.err.println(e);
d.
System.exit(1);
} Lt
ch
te
reader.setContentHandler(new MyContentHandler());
In
ED
try {
of
reader.parse(is);
rig
} catch (SAXException e) {
y
op
System.exit(1);
C
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
}
}
class MyContentHandler implements ContentHandler {
public void startDocument() {
System.out.println("-" + "---
Document parse started");
}
m
URI);
lu
System.out.println(" Local name: " + localName
cu
ri
);
ur
lC
System.out.println(" Qualified name: " + qName);
ia
for (int i = 0; i < atts.getLength(); i++) {
c
ffi
|O
System.out.println(" Attribute: " + atts.ge
d.
tQName(i) + "=\""
Lt
+ atts.getValue(i) + "\"");
ch
te
}
fo
}
In
ED
alName,String qName) {
of
System.out.println("-" + "---
s
ht
URI);
C
m
System.out.print("\\t");
lu
break;
cu
ri
default:
ur
lC
System.out.print(ch[i]);
ia
break;
c
ffi
|O
}
d.
System.out.println("\"");
} Lt
ch
te
}
fo
In
ED
SE
of
s
ht
yrig
op
C
The responsibility of a DOM parser is to read the XML document specified and
convert that into a tree structure suitable for traversal. Internally, a DOM parser
takes help from a SAX Parser to read the file and then compares the XML against
the DTD or the Schema so that relationships between parent-child tags can be set
up and the tag tree is built in the memory.
Parsing the XML using DOM gives access to the root element of the tree, using
which the entire tree can be traversed, searched and indexed if required.
factory.setExpandEntityReferences(false);
m
Node childNode = list.item(i);
lu
visit(childNode, level + 1);
cu
ri
}
ur
lC
}
ia
}
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
Objectives
At the end of this chapter you will be able to:
List characteristics of a web application component.
Describe the life cycle of a servlet.
Construct a web application using simple servlet.
m
Construct an application with multiple servlet components.
lu
cu
Construct an application with response redirection.
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
Java Servlets are web components that allow application logic to be embedded in
the HTTP request-response process and provide a way by which a web application
can be built. Servlets are efficient, portable, robust, extensible, secure, and have a
widespread acceptance. Servlets solve many of the common problems faced when
using CGI.
Efficient
A servlet's initialization code is executed only the first time the web server loads it.
After the server is loaded, handling new requests is only a matter of calling the
service method. This is a much more efficient technique than loading a completely
new executable with every request.
Persistent
Servlets can maintain state between requests. When a servlet is loaded, it stays
resident in memory while serving incoming requests. A simple example of this
would be a Vector that holds a list of categories used in an online catalog. When
the servlet is initialized, it queries the database table which holds a list of
m
lu
Portable
cu
ri
Servlets are developed using Java, so they are portable. This enables servlets to be
ur
lC
moved to a new operating system without changing the source. Code that was
ia
c
compiled on a Windows NT platform can be moved to a Solaris box without
ffi
|O
making any changes.
d.
Robust Lt
ch
te
Because servlets are developed with access to the entire JDK, they are very
fo
In
powerful and robust solutions. Java provides a very well defined exception
ED
hierarchy for error handling. It has a garbage collector to prevent problems with
SE
memory leaks. In addition, it includes a very large class library that includes
of
security, and many other classes, reducing the possibility of errors in the code.
y
op
Extensible
C
Any servlet that needs to utilize services provided by the server has to connect
with the hooks supplied by the associated API (Servlet API). These hooks points are
methods published through interfaces. The custom component (User defined
servlet) has to implements these methods to gain access to services provided by
the server.
To ease the application development efforts, Servlet API provides an abstract class
GenericServlet which has abstract implementation provided for the
mandatory methods present in Servlet and ServletConfig interfaces.
One concrete class HttpServlet is also provided which provides default
implementations for the mandatory methods. This class is optimized to be worked
with the HTTP. Generally, a user defined servlet will be extending from
HttpServlet class.
m
lu
cu
Servlet interface
ri
ur
lC
This interface specifies the contract between the web container and a servlet. In
ia
case of Servlet API, the javax.servlet.Servlet is the interface that
c
ffi
|O
containers use to reference servlets.
d.
When a servlet is written, this interface must be directly or indirectly
Lt
ch
implemented. The interface may be implemented indirectly by extending either
te
javax.servlet.GenericServlet
fo
or
In
javax.servlet.http.HttpServlet.
ED
SE
of
s
ht
rig
GenericServlet class
y
op
abstract class, and all subclasses have to implement the service() method.
This class also implements the ServletConfig interface. This allows the
servlet developer to call the ServletConfig methods directly without
having to obtain the ServletConfig object.
HttpServlet class
This class extends GenericServlet, and provides an HTTP specific
implementation of the Servlet interface. Most of the customized servlets
extend this class.
The Servlet life cycle is as shown above. For a request from the client, if the servlet
is not already there in the memory, then it will be first initialized and loaded in the
memory. The subsequent request to same servlet uses the same instance of the
servlet. Once the web application is undeployed or the web-application server is
shut down the instance is destroyed. Once the servlet is instantiated in memory, it
is always ready to respond to a request.
Loading and Instantiation
The container loads the servlet during startup or when first request is made.
Servlet loading depends on <load-on-startup> of web.xml.
If <load-on-startup> value is positive, then the servlet loads along with the
container.
Otherwise it loads on the first request.
After loading the servlet, the container creates the instances of the servlet
by calling newInstance() method on it.
m
lu
service any request.
cu
The init() method is called only once throughout the life cycle of the
ri
ur
lC
servlet.
ia
If overridden, must call super.init(config)first.
c
ffi
|O
public void init( ServletConfig config){}
d.
public void init(){}
Lt
ch
Destroying the Servlet
te
Called by the servlet container to indicate that the servlet is being taken out
ED
SE
of service.
Frees the resources and does the cleanup tasks.
of
s
init() Method
Once the servlet has been instantiated, the web container calls the init()
method. The purpose of this method is to allow a servlet to perform any
initialization required before being invoked against HTTP requests.
The servlet specification guarantees that the init() method will be called
exactly once on any instance of the servlet, and will be allowed to complete before
any request is passed to the servlet, provided that it does not throw a
ServletException.
Some of the typical tasks that can be implemented in the init method are:
Read initialization parameters using ServletConfig object.
Initialize one time activities such as registering a database driver, a
connection pool or a logging service using the ServletContext object.
<web-app>
<servlet>
m
<param-value>10</param-value>
lu
cu
</init-param>
ri
…
ur
lC
</web-app>
ia
c
ffi
|O
int var= getServletConfig().getInitParameter(“varX”);
d.
Lt
//retrieve data from the web.xml configuration
ch
te
fo
In
ED
SE
ServletContext Interface
of
s
which the web server provides the servlet when the servlet is initialized.
y
op
int var=
getServletConfig().getServletContext().getInitParameter
(“varX”); //retrieve data from the servlet context
object.
Once the servlet object is instantiated, the container needs to execute the
processing logic available in the service method. Service is a generic method used
to encapsulate the servlet execution, but the behavior of the servlet may be
different for different HTML requirement.
For HTTP Get method (used for retrieving data from server side) the servlet needs
to react differently as compared to the POST (used for transferring data to server
side) method. There needs to be a mechanism in the servlet which can
differentiate the HTTP method and execute the corresponding piece of code.
Servlet API provides two methods belonging to HTTPServlet doGet()
and doPost() which correspond to the HTTP GET and POST methods.
The container identifies the HTTP method embedded in the HTTP request
and invokes the matching method.
The methods may need user input to start the processing. This user input is
provided to these methods in form of a parameter which encapsulates the
HTTP request.
m
The container provides a corresponding Servlet API object as part of the
lu
cu
parameter list to the methods.
ri
ur
lC
The client UI (HTML Form) and the processing logic (servlet) are linked with each
ia
other using the <action> tag of the HTML form, the value for this tag matches the
c
ffi
|O
URL-pattern defined in the configuration. The developer obtains the user input by
d.
using the Servlet API method getParameter(), which takes the field name as
Lt
ch
the parameter and returns the user input as return value.
te
fo
{
ED
{
of
s
System.out.println("\n\n");
ht
rig
System.out.println("init() executed");
y
op
}
C
m
out.println("<body>");
lu
cu
out.println("<p> Hi, Welcome to Seed </p>");
ri
out.println("<p> Thanks for accessing the
ur
lC
website</p>");
iac
out.println("<p> Thanks and Regards, </p>");
ffi
|O
out.println("</body>");
d.
out.println("</html>");
out.close(); Lt
ch
te
}
fo
In
ED
SE
of
s
ht
yrig
op
C
The Servlet container may contain more than one application within it. The URL
sent by the browser is used to identify the target application and the individual
component within it. The identified component is then executed by the container.
m
lu
<web-app>
cu
<servlet>
ri
ur
<servlet-name>SimpleServlet</servlet-name>
lC
ia
<servlet-class>pack.GreetingServlet</servlet-class>
c
ffi
</servlet>
|O
<servlet-mapping>
d.
Lt
<servlet-name>SimpleServlet</servlet-name>
ch
<url-pattern>/greeting</url-pattern>
te
fo
</servlet-mapping>
In
</web-app>
ED
SE
Writing of this configuration file may become a lengthy process, and in case of a
of
complex enterprise application it may even become confusing. To avoid this and
s
ht
ease the process of creating the web.xml, Java EE provides annotation which can
rig
y
be used to define the configuration using the Java class itself. Usage of annotations
op
C
ensures that the developer does not have to work with the XML file. Adding
@WebServlet before the servlet class definition in the Java class takes care of the
servlet configurations.
If the developers want to customize and fine tune the configuration, some more
annotations are also provided through the Servlet Annotations available with
Servlet 3.0 API.
Version 3.0 of the web deployment descriptor contains a new attribute called
metadata-complete on the web-app element. This attribute defines whether the
web descriptor is complete, or whether the class files of the web application
should be examined for annotations that specify deployment information.
If the attribute is set to true, the deployment tool must ignore any servlet
annotations present in the class files and use only the configuration details
mentioned in the descriptor.
Otherwise, if the value is not specified or is set to false, the container must
scan all class files of the application for annotations. This provides a way to
enable or disable scanning of the annotation and its processing during the
startup of the application.
@WebServlet(urlPatterns = { "/WelcomeServlet“})
public class WelcomeServlet extends HttpServlet {
m
asyncSuppo true/false - Specifies wether the servlet
lu
cu
rted supports asynchronous processing or not.
ri
ur
lC
description Servlet description - optional
ia
c
initParams Array of @WebInitParam, used to pass
ffi
|O
servlet config parameters - optional
d.
Lt
loadOnStart Integer value - optional
ch
up
te
fo
e
SE
is required
y
op
C
The user interacts with the system using an HTML form in which he/she may
provide some data upon which the business rules are to be applied. For
example, salary details on which income tax rules need to be applied.
This request, through the web server-container path, reaches the servlet
where the data embedded in the request needs to be retrieved. The request
sent by the user is in form of text. This textual data has to be converted into
Java specific data format. This task is managed by the web container when it
identifies the component for execution.
m
methods. Servlet API provides methods associated with the
lu
cu
HttpServletRequest to enable the retrieval of the data.
ri
ur
Similarly, when the result is generated it is generated in Java object format,
lC
ia
which is incompatible with textual data formats. To overcome this problem,
c
ffi
Servlet API has one more component called as HttpServletResponse
|O
which holds the data generated by the business rules unit. The web
d.
Lt
container converts the HttpServletResponse object into text based
ch
te
HTML code and pushes it onto the outbound channel which is retrieved by
fo
In
m
getAttribute()
lu
Returns value of a named attribute for this request.
cu
ri
ur
getContentLength() Size of request, if known.
lC
ia
getContentType() Returns MIME type of the request message body.
c
ffi
|O
getInputStream() Returns an InputStream for reading binary data
d.
Lt
from the body of the request message.
ch
te
getParameterNames()
fo
parameters.
ED
SE
name.
s
ht
rig
version>.<minor version>.
getReader() Returns a BufferedReader to get the text from
the body of the request message.
getRealPath() Returns actual path for a specified virtual path.
getRemoteAddr() IP address of the client machine sending this
request.
getRemoteHost() Host name of the client machine that sent this
request.
getServerName() Name of the host server that received this request.
getServerPort() Returns the port number used to receive this
request.
m
lu
RequestDispatcher rd=req.getRequestDispatcher(“<path of
cu
second component”);
ri
ur
lC
rd.forward(req,res);
ia
or
c
ffi
|O
RequestDispatcher rd=req.getRequestDispatcher(“<path of
d.
second component”);
rd.include(req,res); Lt
ch
te
fo
In
doing so.
of
s
ht
rig
y
op
C
Depending upon requirement request dispatching can be done either of two ways:
Forward
In case of forwarding the response, the response generated by the second servlet
is directly sent over to the client without going back to the first servlet. In such a
case, the response generated by the first servlet is displayed on the client browser,
but because the second servlet is also going to use the same browser window to
display its response is overwritten.
Include
In case of including the response, the response generated by the second servlet is
returned to the first servlet and embedded at the point of invocation within the
first servlet’s response data.
m
lu
Generally, when there is a single processing unit obtaining data
cu
ri
from different components request inclusion is preferred.
ur
lC
iac
ffi
|O
It is recommended to use forward mechanism of the
d.
RequestDispatcher in favour of the include mechanism, as
Lt
ch
it increases the flexibility and reusability of the application.
te
fo
In
ED
SE
of
s
ht
yrig
op
C
While executing the application, there might be a situation where the application
needs to start further execution with fresh set of data without user intervention
(transferring control from one module of application to another), or the user
needs to be redirected to another URL (redirection to another site). In such a
scenario, transferring the control using the RequestDispatcher is not
recommended as it also transfers the older request object along with the control.
Response Redirection generates a response programmatically in such a way that
the browser upon receiving the response automatically generates a fresh request
and tries to connect with the new URL.
sendRedirect() is used if
The browser has to initiate a new request to a different servlet / JSP
The servlet / JSP that is to be forwarded is not in the same web application
res.sendRedirect(“http://<path to some other
resource>”);
m
lu
to another site or application or to a static page within the same
cu
ri
ur
application.
lC
requestDispatcher.forward or include is used to
ia
c
ffi
transfer control to a dynamic component within the same
|O
application.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
To make the application truly responsive, the client specific data needs to be
maintained on the server. Returning user information needs to be mapped and
identified based on the earlier interactions with the application. This is achieved in
a web application with a mechanism called as Session Tracking which is the topic
of discussion in this chapter.
Objectives
At the end of this chapter you will be able to:
Construct an application for Session Tracking using Hidden Form Fields.
Construct an application for Session Tracking using Cookies.
Construct an application for Session Tracking using URL Rewriting.
Construct an application for Session Tracking using HttpSession object.
Construct an application to filter requests.
Construct an application to listen to application lifecycle events.
m
lu
cu
ri
For every user interaction from login to logout a separate, unique
ur
lC
session is created.
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
As mentioned earlier, web applications are accessed using HTTP, which is stateless.
HTTP specification does not allow information associated with the senders and
receiver’s identification to be stored internally.
A responsive application is built with an assumption that the user will be accessing
the same application in a single session multiple times. Because HTTP is stateless,
it becomes impossible to identify the customer using only the request data being
sent through.
Every request generated through HTTP is a fresh request, without having any
connection with the earlier request sent from the same physical address to the
same application. If the web application is built such that it accepts only the data
from the client request, then client’s identity is lost in processing and a continuous
flow of application execution cannot be simulated. For example,
m
Client Server
lu
cu
ri
Access facebook.com Locate the index.html and send it.
ur
lC
ia
Login with username and Identify the user and validate, respond with
c
ffi
password user’s home page
|O
d.
Click on wall Lt
Cannot understand which user’s wall, as no
ch
user information is provided; respond with an
te
fo
Login with username and Identify the user and validate, respond with
SE
The basic need for Session tracking can be identified as having to share the data
between multiple execution components. For example, when the user logs into an
application, he/she will provide their name and credentials. The same data is to be
utilized further in the application to customize the look-and-feel based on the
user’s preferences. To do so, the data provided by the user needs to be shared
with the component that generates the look and feel.
One way of doing this could be by using a shared file, which can act as a go-
between for multiple components. The data passing component can push the data
into a file and the data processing component can pull the data from the file.
There is nothing wrong with this mode of data sharing, but it has a huge drawback.
The files are stored on secondary devices, and secondary storage manipulations,
by rule, are slower as compared to primary memory.
To speed up the data storage and retrieval, the application needs to have a
mechanism that can hold the data and user identification in primary memory. This
can be achieved in Java by using one of three ways:
m
lu
cu
ri
ur
lC
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
lu
cu
ri
Hidden form fields store information about the
ur
lC
session. The hidden data can be retrieved later by
iac
using the HTTPServletRequest object
ffi
|O
Form fields can be used only on dynamically
d.
Lt
generated pages, so their use is limited. And there
ch
te
In this approach a unique token is embedded within each HTML form. For
example, the following HTML specifies an input control of type Hidden:
<input type= “Hidden” name= “uid” value= “seed”>
When the request is submitted, the server receives the token as part of the
request, which in turn can be used to identify the client by matching the unique
token.
This approach of session tracking or state management works only if the content is
created dynamically. For static content, this methodology is not suitable.
The sequence of implementing this approach is as follows:
1. The user requests a resource from the browser.
2. The resource generates the output dynamically using PrintWriter.
3. While generating the dynamic HTML, a hidden form field with a unique value
is generated and embedded in the HTML form.
4. The generated form is rendered on the client’s browser using
PrintWriter.
5. User fills up the data and submits the form.
6. The hidden form field, which is part of the HTML form is also packaged
inside the request data being sent across.
7. The targeted servlet component receives the HTML request.
8. Hidden form field parameter is retrieved using getParameter() method
by supplying the hidden form field name as parameter.
m
returning user.
lu
cu
11. Steps 2-10 repeat till complete.
ri
ur
lC
Code Example
iac
Following is a sample code to implement session tracking using Hidden form fields:
ffi
|O
The HTML file used to send request.
d.
Lt
ch
<BODY>
te
fo
value = "">
ht
rig
value>">
C
m
lu
cu
A Cookie is a string which is sent to a client at the start of
ri
a session.
ur
lC
If the client wants to continue the session it sends back
ia
the Cookie with subsequent requests.
c
ffi
Most common way to implement session tracking
|O
Cookies store information about a session in a human-
d.
readable file on the client's machine. The server
Lt
associates a session ID from the cookie with the data
ch
te
Cookies are the most commonly used means of tracking client sessions. Cookies
C
were first introduced by Netscape, and later picked up by virtually all major
browser applications.
A cookie is a small piece of textual information sent by the web application to the
client, stored on the client, and returned by the client for all requests to the server.
The web application creates a text file on the server side upon receipt of the first
request by a specific user. This text file, called a cookie, is attached to the response
object being assembled to be sent back to the client. The cookie travels to the
client-side along with the response data and the browser extracts this cookie and
stores it on local storage medium. The next time when a request is sent to the
same application (domain), browser searches in the local storage and identifies the
cookie files associated with the application. All the cookies associated with the
application are attached to the request and sent along with the actual request
data. The application component receiving this request retrieves the cookies
separately from the parameter data and the comparison of cookie data is done to
identify the specific client sending the specific request.
m
lu
Domain=DOMAINNAME; Max-age=SECONDS;
cu
ri
Path=PATH; secure; version=1*DIGIT
ur
lC
iac
ffi
|O
By default, user sessions are maintained using cookies. If cookies
d.
are disabled on the client side, some other means of session
Lt
ch
management is used.
te
fo
Because cookies containing user specific data are kept on the client-side machines,
In
ED
there are certain security concerns in situations where the client machines are
SE
shared.
of
s
ht
yrig
op
C
m
// Define content type
lu
cu
response.setContentType("text/html");
ri
ur
lC
PrintStream pout = new
iac
PrintStream(response.getOutputStream());
ffi
|O
d.
// Check to see if there are any cookies
Lt
Cookie[] cookieArray = request.getCookies();
ch
te
fo
In
// Default value
ED
int count = 0;
SE
of
if (cookieArray != null)
rig
{
y
op
{
Cookie c = cookieArray[i];
// Increment counter
m
response.addCookie(new Cookie ("count",
lu
cu
String.valueOf(count)));
ri
ur
lC
// Output message
ia
c
pout.println ("You have visited this page " + count +
ffi
|O
" times since your web browser started");
d.
pout.flush();
} Lt
ch
te
fo
In
{
s
ht
doGet(request,response);
rig
}
y
op
C
m
lu
cu
All links and redirections which are created by a
ri
ur
lC
Servlet have to be encoded to include the session ID.
iac
This is a less elegant solution because the session
ffi
|O
cannot be maintained by requesting a well-known
d.
Lt
URL which was created in a different (or no) session.
ch
te
If cookies are disabled on the client side, then developer can use URL rewriting as
a backup. Assuming that developer did his/her part correctly, URL rewriting always
works - the client cannot prevent it.
URL rewriting takes the session ID and appends it to every URL that comes into the
application, as shown below:
URL+;jsessionid=1234567
URL is the resource to which the request if being forwarded.
URL rewriting requires that all pages in the application be dynamically generated.
URL rewriting cannot be enforced for static HTML pages because the unique URL
path parameter (the jsessionid) is dynamic.
URL rewriting is used only if cookies fail, and only if developer specifies that the
responses should encode the URLs being sent to the client.
m
lu
pages are part of application navigation cycles.
cu
ri
URL rewriting has one more drawback; if the user book-marks the
ur
lC
URL and revisits the site using the book-mark, the application can
ia
c
be accessed, which may poses a security threat.
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
The URL which is being sent back to the client will have to be encoded thus.
public void doPost(HttpServletRequest req,
HttpServletResponse res)
{
PrintWriter out=res.getOut();
out.println("Click <a href=" +
res.encodeURL(req.getRequestURL().toString()) + ">this
link</a>");
out.println(" to access this page again.<br>");
. . .
}
Over and above the three session tracking mechanisms discussed earlier, Servlet
API provides one more way of implementing session tracking. HttpSession is
an object internally holding a map implementation. Any application using
HttpSession is internally using cookies generated by the container, transparent
to the developers. If cookies are disabled then it switches to URL rewriting mode
for maintaining the session.
The other session tracking mechanisms provide only session tracking. They help in
identifying a returning visitor, but there is no built-in help available in terms of
maintaining the user specific data. Cookies provide help in this regard, but coding
for maintaining the data is a little complex. To make the state management task
easier, HttpSession object exposes certain straight forward methods that the
developer has to embed within the code to manage the user state without extra
trouble.
The typical code for managing user state through HttpSession usage is as
follows:
public class AttributeServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
HttpSession session = request.getSession();
String name = request.getParameter("attrib_name");
String value =
request.getParameter("attrib_value");
String remove =
request.getParameter("attrib_remove");
if (remove != null && remove.equals("on"))
{
session.removeAttribute(name);
m
if (name != null && name.length() > 0 && (value
lu
cu
!= null) && value.length() > 0)
ri
{
ur
lC
session.setAttribute(name, value);
ia
c
}
ffi
|O
}
d.
response.setContentType("text/html");
Lt
PrintWriter out = response.getWriter();
ch
te
fo
In
out.println("<HTML>");
ED
out.println("<HEAD><TITLE>Session
SE
Attributes</TITLE></HEAD>");
of
out.println("<BODY>");
s
ht
out.println("<H1>Session Attributes</H1>");
rig
attribute");
C
String url="/session/servlet/attributes";
out.println("<FORM ACTION=\"" + url + "\"
METHOD=\"GET\">");
out.println("Name: ");
out.println("<INPUT TYPE=\"text\" SIZE=\"10\"
NAME=\"attrib_name\">");
out.println("Value: ");
out.println("<INPUT TYPE=\"text\" SIZE=\"10\"
NAME=\"attrib_value\">");
out.println("<BR><INPUT TYPE=\"checkbox\"
NAME=\"attrib_remove\">Remove");
out.println("<INPUT TYPE=\"submit\" NAME=\"update\"
VALUE=\"Update\">");
out.println("</FORM>");
out.println("<HR>");
out.println("Attributes in this Session");
// Print all session attributes
Enumeration e = session.getAttributeNames();
m
String att_value = (String)
lu
cu
session.getAttribute(att_name);
ri
out.println("<BR><B>Name:</B> ");
ur
lC
out.println(att_name);
iac
out.println("<B>Value: </B>");
ffi
|O
out.println(att_value);
d.
}
out.println("</BODY></HTML>"); Lt
ch
te
out.close();
fo
In
}
ED
}
SE
of
s
ht
m
lu
Authorization)
cu
ri
Image conversion Data compression
ur
lC
Localization XSL/T transformations of XML content
iac
Encryption Tokenizing
ffi
|O
MIME-type chaining Caching
d.
Lt
ch
te
filter.
ht
yrig
op
C
m
pass through this method.
lu
cu
Upon completion of its task destroy() is invoked.
ri
ur
lC
doFilter() receives FilterChain object as one parameter, which
iac
encapsulates the filter stack created using the configuration file. If a request is
ffi
|O
filtered through more than one filter, then each filter is invoked in turn depending
d.
on its precedence in the web.xml file.
Lt
ch
The link between multiple filters are implemented by invoking doFilter() on
te
fo
container manages a stack of filter references which are executed one after the
SE
other. The last filter in the stack invokes the service() method of the servlet
of
m
change in the configuration forces the code to change and makes
lu
cu
it mandatory to recompile the source code.
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
cu
Application lifecycle is controlled by the container
ri
ur
To map task execution with application component
lC
ia
state, listeners are exposed.
c
ffi
|O
Container listens to the events occuring and checks if
d.
a corresponding listener is configured for the
Lt
ch
application.
te
fo
the method.
of
s
ht
yrig
op
C
There are certain tasks which are related to the application behaviour rather than
specific execution events. A customer may wish to perform some activity as soon
as the application starts. For example, in an online shopping web application, the
daily discount rates should be assigned as soon as the application starts for the
day.
To achieve this, servlet specification provides few listeners which listen to the
application lifecycle events. The listeners also provide hooks to provide
implementation associated with these events. A developer needs to override
these hooks to enable the application to start listening to the events.
A listener is configured using the web.xml file.
<web-app>
<listener-class>package.listener</listener-class>
</web-app>
The listeners available through the API can be divided into three broad categories:
m
lu
cu
2. Servlet request events
ri
ur
ServletRequestListener
lC
ServletRequestAttributeListener
ia
c
ffi
|O
3. Http session events
d.
HttpSessionListener
Lt
ch
HttpSessionAttributeListener
te
HttpSessionActivationListener
fo
In
HttpSessionBindingListener
ED
SE
of
s
ht
yrig
op
C
Web application creation is a complex task involving lots of manpower with lots of
skill sets. Two basic skills required for web application building are keen logic for
writing the code and strong imagination for building the UI. To ensure a right fit for
right task, the web application is divided into two parts; the code part and the UI
part. To ensure Rapid Application Development with better readability, Java Server
Pages evolved.
This chapter covers the basics of Java Server Pages.
Objectives
At the end of this chapter you will be able to:
Construct a simple JSP application.
Construct a JSP application by customizing the page attributes.
Construct a JSP application following MVC design pattern.
m
a special component of the container called a JSP engine. The Servlets thus
lu
cu
generated are in sync with the JSP file. Any modification to the JSP file later is
ri
ur
reflected in the Servlet that is generated for that particular JSP.
lC
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
cu
Initialization
ri
ur
The jspInit() method is called on the servlet instance to initialize it. It is called
lC
ia
only once during JSP life cycle.
c
ffi
|O
Service
d.
The _jspService() method is invoked for each request received for the JSP.
Lt
ch
This method cannot be overridden.
te
fo
Destruction
In
ED
m
Tag Tag Name
lu
cu
<!- -
ri
HTML
ur
->
lC
Comment
ia
<%- - JSP Comment
c
ffi
--%>
|O
<%!
d.
Declaration
%> Lt
ch
<% %>
te
Expressions
fo
<%@ %>
In
Directives
ED
The different types of JSP tags are mentioned in the table above.
SE
of
There are basically three types of directives to provide information to jsp page.
page directive
page directive is used to provide pre-compilation instruction to the JSP compiler,
while the JSP is getting converted into a servlet. It is used to customize the
resultant servlet execution.
include directive
include directive is used to add an existing resource to current JSP at compile
time. The external resource contents are added to the JSP and then converted into
servlet.
taglib directive
taglib directive is used to provide implementation for custom-tags if they are
being used in the JSP.
m
lu
<%@ page [attribute=“ value”* ] %>
cu
ri
ur
Attributes of page directive are as follows:
lC
iac
Attribute Description
ffi
|O
language It defines the scripting language to be used. This attribute
d.
Lt
exists in case future JSP containers support multiple
ch
te
m
lu
value is false, then this is same as implementing the
cu
javax.servlet.SingleThreadModel interface in
ri
ur
lC
the resulting servlet.
ia
c
ffi
info It defines an informative string that can subsequently be
|O
obtained from the page’s implementation of the
d.
Lt
Servlet.getServletInfo() method.
ch
te
pages.
isErrorPage isErrorPage indicates if the current JSP page is
intended to be another JSP page’s error page. If true, then
the implicit object exception is available and refers to
the instance of the java.lang.Throwable thrown at
runtime by the JSP that caused the error.
contentType ContentType defines the character encoding for the JSP
and MIME type for the response of the JSP page. The
default value for the MIMETYPE is text/html; the default
value for the encoding is ISO-8859-1.
Page directive attributes can be configured as:
<%@ page import=“java.util.*,com.seed.* %>
<%@ page session=“true”%>
<%@ page errorPage=“errorHandlar.jsp” %>
<%@ page isErrorPage=“true” %>
m
lu
Include Directive
cu
ri
ur
The include directive instructs the container to include the content of a
lC
resource in the current JSP, inserting it inline, in the JSP page, in place of the
iac
ffi
directive. The specified file must be accessible and available to the JSP container.
|O
The file attribute specifies the filename of the file to include. This is a relative path
d.
Lt
within the current web application, beginning with a forward slash. This is also
ch
called as static include as the contents are added at time of conversion only. The
te
fo
consequence is that if the resource changes the change will not be reflected in the
In
ED
JSP.
SE
The above code ensures that filename.jsp will be embedded in the parent JSP at
ht
rig
JSP scripting elements allow inserting Java code into JSP which in turn is converted
into servlet code at the time of JSP translation.
A JSP declaration lets a developer define methods or fields that are inserted
into the main body of the servlet class. Since declarations do not generate
any output; they are normally used in conjunction with JSP expressions or
scriptlets.
JSP scriptlets let a developer insert Java code into the JSP which converts
into servlet’s _jspService method (which is called by service).
JSP expression is evaluated, converted to a string, and inserted in the page.
This evaluation is performed at run time (when the page is requested) and
thus has full access to information about the request.
Following is an example of the scripting element:
<%! int i=2;%>
<table>
<%
for(int x=1;x<=10;x++)
m
<td><%=i*x</td>
lu
cu
</tr>
ri
<%
ur
lC
}
iac
%>
ffi
|O
d.
Lt
ch
Even though available, it is strongly recommended to avoid using
te
The JSP action tags enable the programmer to use the built in functionality
provided by the servlet container. These are the XML tags those can be used in the
jsp page.
<jsp:include>
Includes the resources at the time of page request. Also known as dynamic include
as opposed to static include with @include directive.
<jsp:include page=“other.jsp” flush=“true”/>
<jsp: forward>
Forwards the resources at the time of page request.
<jsp:forward page=“other.jsp” flush=“true”/>
<jsp:param>
Passes the parameters to dynamic pages.
<jsp:include page=“SomePage.jsp” flush=“true”>
m
lu
<jsp: plugin>
cu
ri
Plugs the other components like Applets or beans.
ur
lC
<jsp:plugin type=“applet” class=“MyApplet.class”/>
iac
ffi
<jsp:useBean>
|O
d.
Refer discussion related to <jsp:useBean> later in the chapter.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
cu
Responsibilities of Model
ri
ur
Performing DB queries.
lC
Applying the business rules.
iac
ffi
Generating results or exceptions.
|O
d.
View
Lt
ch
View represents the User Interface. Anything to do with user interaction, whether
te
fo
accepting data from the user or sharing data with the user is identified as a view.
In
In specific case of Java web application, a view is any HTML based component like
ED
SE
HTML, JSP.
of
s
ht
rig
Responsibilities of View
y
op
m
lu
no difference to a developer.
cu
ri
ur
lC
ia
Generally, View-Model and Model-View data transfers should be
c
ffi
avoided. This will force the View to have data processing code,
|O
which is not its responsibility. In case of unavoidable
d.
Lt
requirement, custom tags should be preferred over usage of
ch
te
scriptlets.
fo
In
ED
SE
MVC can be implemented in JSP by encapsulating the business rules into a Java
class (POJO or Java Bean) and using it inside the JSP with a ready-made action tag
<jsp:useBean>.
JSP Syntax
jsp:useBean id="beanInstanceName" scope="page | request
| session | application"
class="package.class"|type="package.class"|class="packa
ge.class"|type="package.class"beanName="{package.class|
<%=expression%>}"type="package.class"}{|other
elements/<jsp:useBean> }
This tag undergoes following steps to locate or instantiate the bean:
10. Attempts to locate a Bean with the specified scope and name.
11. Defines an object reference variable with the specified name.
12. If it finds the Bean, stores a reference to it in the variable. If type is specified,
gives the Bean that type.
m
java.beans.Beans.instantiate.
lu
cu
14. If it has instantiated (rather than located) the Bean, and if it has body tags
ri
ur
(between <jsp:useBean> and </jsp:useBean>), executes the body
lC
ia
tags.
c
ffi
|O
Attribute Description Example
d.
id Bean is identified in the JSP id=“address”
Lt
ch
page
te
fo
In
m
lu
cu
Following code explains the <jsp:useBean> action tag which follows MVC
ri
ur
design pattern.
lC
ia
//View
c
ffi
//personInfo.html
|O
<html>
d.
<body> Lt
ch
<form action=”\myWorkSpace\personInfo.jsp”
te
fo
method=”get”>
In
name=”pname”/>
of
s
</form>
ht
rig
</body>
y
op
</html>
C
//Controller
//personInfo.jsp
<jsp:useBean id=“person” class=“pkg.Person”
scope=“session”>
<jsp:setProperty name=“person” property=“*” />
<jsp:getProperty name=“person” property=“pid”/>
<jsp:getProperty name=”person” property=”pname”/>
</jsp:useBean>
//Model
//Person.java
package pkg;
public class Person
{
private String pname,pid;
public Person(){}
m
public String getPname(){
lu
cu
return pname;
ri
}
ur
lC
public void setPid(String pid){
ia
c
this.pid=pid;
ffi
|O
}
d.
public String getPid(){
Return pid; Lt
ch
te
}
fo
In
}
ED
SE
of
exception.
JSP provides certain implicit objects, based on the servlet API. These objects are
accessed using standard variables and are automatically available for use in a JSP
without having to declare/define them.
out
This object is the object that writes into the output stream to the client. To make
the response object useful, this is a buffered version of the
java.io.PrintWriter class, and is of type
javax.servlet.jsp.JspWriter. The buffer size can be adjusted via the
buffer attribute of the page directive.
request
This object represents the request that triggered the service() invocation. This
object is a protocol and implementation specific subclass of
javax.servlet.ServletRequest. It has a request scope.
m
lu
subclass of javax.servlet.ServletResponse. It has a page scope.
cu
ri
ur
session
lC
ia
This object represents the session created for the requesting client. Sessions are
c
ffi
created automatically, and a new session is available even when there is no pre-
|O
existing session object available. The session object is of type
d.
Lt
javax.servlet.http.HttpSession, and has a session scope.
ch
te
pageContext
fo
In
attributes and is a convenient place to put shared data within the page. It is of
of
config
y
op
This object is the ServletConfig for this JSP page, and has page scope. It is of
C
type javax.servlet.ServletConfig.
page
This object is the instance of the page’s implementation servlet class that is
processing the current request. It is of type java.lang.Object, and has page
scope. This object can be thought of as a synonym to this within the page.
Application
This object represents the servlet context. It is of type
javax.servlet.ServletContext and has application scope.
Exception
An error page is essentially the JSP that handles the exception, so the Container
gives the page an extra object for the exception. This object is of type
java.lang.Throwable.
Following code snippet explains how to use implicit objects in an application. It
accepts the username and password from login.html page and print username.
m
<form action=”accept.jsp”>
lu
cu
<!- - ->
ri
</form>
ur
lC
</body>
iac
</html>
ffi
|O
d.
//accept.jsp Lt
ch
<%
te
fo
String name=request.getParameter(“username”);
In
ED
String pass=request.getParameter(“password”);
SE
out.println(“Hello”+” “+name);
of
%>
s
ht
yrig
op
C
When any object is created it is assigned one of the predefined scopes. The scope
of any object defines how widely the object is available and who can access it.
Scopes are associated with container objects. JSP have 4 different scopes. All the
implicit objects as well as the user-defined objects in JSP page exist in one of the
following scopes.
Application Scope
The objects are shared across all the components of web application and are
accessible for the life of the application. Use setAttribute() and
getAttribute() of ServletContext interface.
<% String
userId=context.setAttribute(“userId”,userId);%>
<% String
userId=(String)context.setAttribute(“userId”);%>
m
lu
<% String
cu
ri
userId=session.setAttribute(“userId”,userId);%>
ur
lC
<% String
ia
userId=(String)session.setAttribute(“userId”);>
c
ffi
|O
Request Scope
d.
Lt
Shared across all the components that process the same request and the same
ch
response and maintained as attribute-value pairs by HttpServletRequest
te
fo
interface.
In
ED
<% String
SE
userId=request.setAttribute(“userId”,userId);%>
of
<% String
s
ht
userId=(String)request.setAttribute(“userId”);%>
yrig
op
Page Scope
C
Objects in the page scope are accessible only in the translation unit in which they
are defined, and maintained as attribute-value pairs by concrete subclass of the
abstract class PageContext.
JSPs are great for creating User Interface that is rich, but it has problems in
situations where the output on the client’s browser needs to be customised
depending on requirement and data inputs. Usually, this is implemented using
embedded scriptlets in JSP. This leads to reduced readability and maintainability.
The Java code required for performing customisation is encapsulated into a Java
class and a customised tag for the specific implementation is provided to
developers. This is called as custom tags. To assist functioning of custom tags, a
special data representation language called Expression Language (EL) and a pre-
created set of commonly used custom tags is also provided. JSP Standard Tag
Library (JSTL) helps reduce the need of creating commonly required tasks by
providing pre-built custom tags.
This chapter covers custom tags, Expression Language and JSP Standard Tag
Library.
m
lu
Create an application with Expression Language.
cu
ri
Create an application with JSTL tags.
ur
lC
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
JSP applications can increase dynamic behavior by embedding Scriptlets the Java
code, which responds depending on the data-input. Problem with this approach is
that it reduces the readability and leads to larger testing and debugging times, as
error isolation becomes difficult.
As per Model-View-Controller, it is imperative that the UI component consist only
of programming constructs which deal with generating user interface and there
should not be any code that violates this by providing business rules execution, or
processing code within it. Putting Java code in JSP breaks the assumption that
every component focuses only on its own responsibilities.
In addition to the above problem, there is one more practical problem associated
with this approach. Usually the UI is created by the designers who may not be
well-versed with the programming language. This forces delayed UI creation as
designers have to be dependent on the developer to embed the Java code at
specified location. This may lead to either slower development times or higher
resource requirements.
m
separate Java file and a wrapper over the functionality could be provided in terms
lu
cu
of a reusable tag, the task becomes easier to handle.
ri
ur
lC
In effect the solution that is required calls for a tag to be created which is suitable
ia
for a specific action to be executed. What is required is a custom tag.
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Custom tags are created with a specific usage in focus; hence these cannot be
used for general purpose. The main benefit of using the custom tag is that it helps
separate out the presentation logic from the processing and business logic.
Benefits of using custom tags
Reusable code
The functionality is provided in modularized form. The developer creates java code
for the features, and a designer uses those in form of tags. This combination can
be reused anywhere there is a similar need. The entire custom tag component
package can be reused as it does not depend on any external component.
Extensible JSPs
Reduction in number of scriptlets embedded in the JSP increases its readability
and modularity. This helps in extending JSP functionality in an easier manner. JSP
code can now have a focused approach towards providing better and richer
presentation rather than processing data.
m
lu
both these components are modularized and the same custom tag can be reused
cu
ri
again in similar requirements.
ur
lC
Maintainable JSPs
iac
ffi
Reduced scriptlets means cleaner code, which in turn leads to better maintenance
|O
cycles as error isolations are easier. Maintenance can also have a focus.
d.
Layer of Abstraction Lt
ch
te
fo
A designer does not need to understand the Java code running behind the custom
In
m
The taglib directive written maps all the tags starting with ‘prefix’ to
lu
cu
a specific uri.
ri
ur
Container searches for a tld file containing the uri mentioned in the JSP.
lC
ia
tld file provides a reference of the Java class managing the
c
ffi
implementations.
|O
Container extracts the codes corresponding to the tag start and tag end (and
d.
more if it exists). Lt
ch
This code is embedded with the servlet code that generated at the end of
te
fo
In
Types of Tags
yrig
TagSupport
The TagSupport class is a utility class to be used as a base class for handling
the tags. The TagSupport class implements Tag and IterationTag
interfaces. Many tag handlers extend TagSupport class.
TagSupport API
Following are the some important methods of TagSupport.
Method Description
Default constructor, all subclasses are
required to define only a public
TagSupport()
constructor with the same signature,
and to call the superclass constructor.
int doAfterBody() Default processing for a body.
int doEndTag() Default processing of the end tag
m
returning SKIP_BODY.
lu
cu
ri
The Tag instance most closely
ur
Tag getParent()
lC
enclosing this tag instance.
ia
c
ffi
Object Get the value associated with a key.
|O
getValue(java.lang.Str
d.
ing k)
Lt
ch
te
void
ED
setValue(java.lang.Str
ing k,
of
s
java.lang.Object o)
ht
yrig
void
op
setPageContext(PageCon
text pageContext)
BodyTagSupport
The BodyTagSupport class implements the BodyTag interface having some
additional convenience methods including getter methods for the bodyContent
property and methods to get at the out JspWriter. Many tag handlers will
extend BodyTagSupport class.
BodyTagSupport API
Following are the some important methods of BodyTagSupport.
Method Description
BodyTagSupport() Default constructor, all subclasses are
required to only define a public
constructor with the same signature,
and to call the superclass constructor.
int doAfterBody() After the body evaluation: do not
m
returning EVAL_PAGE.
lu
cu
void doInitBody() Prepare for evaluation of the body just
ri
ur
lC
before the first body evaluation: no
ia
action.
c
ffi
int doStartTag()
|O
Default processing of the start tag
returning EVAL_BODY_BUFFERED.
d.
BodyContent LtGet current bodyContent.
ch
te
getBodyContent()
fo
JspWriter
In
getPreviousOut()
SE
setBodyContent(BodyCon
rig
tent b)
op
C
These tag handler method returns a constant value which decides the JSP
behaviour.
m
public static final Evaluate body into existing out stream.
lu
cu
EVAL_BODY_INCLUDE Valid return value for doStartTag().
ri
ur
lC
public static final
Continue evaluating the page. Valid
ia
int EVAL_PAGE
c
ffi
return value for doEndTag().
|O
d.
public static final Lt Skip body evaluation. Valid return value
ch
for doStartTag() and
te
int SKIP_BODY
fo
doAfterBody().
In
ED
Following code prints “Hello World” with current date and time using custom tag.
This file contains HTML design and custom tag declaration and taglib URI .
//hello.jsp
<%@ taglib uri="/hello" prefix="examples" %>
<html>
<head>
<title>First custom tag</title>
</head>
<body>
<p>This is static output. Tag output is shown in
italics.</p>
<p><i>
<examples:hello>
</examples:hello>
</i></p>
<p>Closing the tag without a body will have the
same effect</p>
m
<p>This is static template data again.</p>
lu
cu
</body>
ri
</html>
ur
lC
ia
This is a tag handler class, to handle the tag operation and perform some business
c
ffi
logic.
|O
d.
//HelloTag.java
package com.seed.tagext; Lt
ch
te
import java.io.IOException;
fo
import java.util.Date;
In
ED
import javax.servlet.jsp.*;
SE
import javax.servlet.jsp.tagext.TagSupport;
of
return EVAL_BODY_INCLUDE;
y
op
}
C
m
lu
<taglib>
cu
ri
<tlib-version>1.0</tlib-version>
ur
lC
<jsp-version>1.2</jsp-version>
ia
<short-name>simple</short-name>
c
ffi
|O
<uri>http://tomcat.apache.org/example-taglib</uri>
<description> A simple tab library for the examples
d.
</description> Lt
ch
<tag>
te
fo
<name>hello</name>
In
ED
<tag-class>com.seed.tagext.HelloTag</tag-class>
SE
<body-content>JSP</body-content>
of
<description>
s
ht
</description>
C
</tag>
</taglib>
Custom tags are good for increasing readability and maintainability of the JSP, but
there are certain tasks which are difficult to manage with custom tags. For
example, if there is a task involving data rendering tasks, then it becomes difficult
to manage that using custom tags. For this, scritplets need to be used for faster
development. Similarly, it becomes difficult to render expressions using custom
tags since the custom tag has to be nested with the JSP expression scriptlet.
To overcome this problem the specification provides components like EL
(Expression Language) and JSTL (JSP Standard Tag Library).
m
nScope application scope attributes otalPrice}
lu
cu
ri
param A map containing a request ${param.name}
ur
lC
parameter String
iac
paramValue A map containing a request ${paramValues.name[“
ffi
|O
s parameter String [] 0”] }
d.
Lt
ch
header A map containing a request ${header.accept}
te
fo
header String
In
es “0”]}
SE
header String
of
to a single object
y
op
JSP Implicit objects are not same EL Implicit objects. JSP and EL
implicit objects have only one object (pageContext) in
common. pageContext has properties for accessing all of the
other eight JSP implicit objects.
m
Logical inversion:! and not
lu
cu
ri
Following code demonstrates using the different operators:
ur
lC
<% //EL Arithmatic %>
iac
${2*3.14} <br>
ffi
|O
${1.5e6/1000000}<br>
d.
<% // EL relational and logical operator %>
Lt
ch
${8.5 gt 4} <br>
te
${(5*5) ==25? 1: 0}
ED
SE
of
s
ht
yrig
op
C
The JSP expression language allows defining a function that can be invoked in an
expression. Functions are defined using the same mechanisms as custom tags.
Methods are invoked by accessing their corresponding XML tags.
Following code demonstrates accessing EL functions within a JSP:
//functionusage.jsp
<%@ taglib uri="http://myFunc/Functions"
prefix="myString" %>
<html>
<body>
<b>Enter text:</b>
<form action="/EL/stringfun.jsp" method="get">
<input type="text" name="x">
<p><input type="submit">
</form>
<table border="1">
<tr>
m
<td>String Length:</td>
lu
cu
<td>${myString:length(param.x)}</td>
ri
</tr>
ur
lC
</table>
iac
</body>
ffi
|O
</html>
d.
Lt
The following code shows creating java files with method implementation:
ch
//StrMethods.java
te
fo
package com.seed.myfunc;
In
ED
{
of
{
rig
return x.toUpperCase();
y
op
}
C
m
<short-name>SimpleTagLibrary</short-name>
lu
cu
<function>
ri
<name>upper</name>
ur
lC
<function-class>myfunc.StrMethods</function-
ia
c
class>
ffi
|O
<function-signature>
d.
java.lang.String upper(java.lang.String)
</function-signature> Lt
ch
te
</function>
fo
In
<function>
ED
<name>length</name>
SE
<function-class>myfunc.StrMethods</function-
of
class>
s
ht
<function-signature>
rig
java.lang.int length(java.lang.String)
y
op
</function-signature>
C
</function>
</taglib>
Rules when creating methods for EL
The method must be public and static.
The class must be public.
Method’s arguments and return value must be valid within EL.
JSTL provides some simple tags which have the core functionality common to
many JSP applications. The tag defined by JSTL works same everywhere. Main
advantage of using JSTL lies in its reusable components. Developers do not have to
create anything other than the linkage between the JSP and the libraries.
JSTL is further sub-divided based on the tag functionality, and there is a predefined
prefix associated with it. Following is a list of the predefined prefixes:
Tag library Description Prefix
core Tags for general purpose processing c
Tags for parsing, selecting and
xml xml
transforming XML data
Tags for Formatting data for international
formatting fmt
use.
sql Tags for accessing relational databases. sql
functions Tags for accessing relational databases. fn
m
lu
but it is recommended to maintain readability and standards.
cu
ri
ur
lC
JSTL cannot be used without the standard jar files required. All web
ia
containers compliant with JSP 2.0 provide these jar files.
c
ffi
|O
jstl.jar
d.
standard.jar
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
The core functionality JSTL is further divided into four major parts.
General purpose
JSTL Tags Description
<c:catch> Catch exceptions within a variable.
<c:out> Displays contents within the page.
Following code snippet shows the use of general purpose tags:
<c:catch var=“e”>
actions that might throw an exception
</c:catch>
<c:out value=“${number}” />
m
<c:set> Sets the value of an EL variable.
lu
cu
ri
<c:remove> Removes an EL variable.
ur
lC
ia
c
ffi
|O
Following code snippet shows the use of variable support tags:
d.
<c:set var=“num” value=${4*4}” />
Lt
ch
<c:set var=“num”>
te
${8*2}
fo
In
</c:set>
ED
<c:set var=“num”>
SE
<c:out value=“${8+8}”/>
of
</c:set>
s
ht
12351
op
C
<c:set>
<c:remove var=“num” scope=“session”/>
Flow control
JSTL Tags Description
<c:if> Alters the processing equaling value.
<c:choose> Alters the processing equaling set of values.
<c:forEach> Repeats processing for each object in a collection.
<c:forTokens> Problems processing for each substring in given text
field.
Following code snippet shows the use of flow control tags:
<c:if test=“${x = =‘9’}”>
${x}
</c:if>
<c:choose>
<c:when test=“${color = =‘white’}”>
Light !
m
</c:otherwise>
lu
cu
<c:forEach var=“num” items=“${numArray}”>
ri
<c:set var=“num” value=“100”/>
ur
lC
</c:forEach>
iac
<c:forTokens var=“num” items=“${numList}” delims=“,”>
ffi
|O
${num}
d.
</c:forToken>
Lt
ch
URL Handling
te
fo
In
<c:import>
of
m
lu
<sql: update>
cu
ri
UPDATE account SET Balance = Balance - ?
ur
lC
WHERE accountNo = ?
ia
<sql:param value="${transferAmount}"/>
c
ffi
|O
<sql:param value="${accountFrom}"/>
</sql:update>
d.
<sql:transaction [dataSource=”dataSource”] Lt
ch
</sql:transaction>
SE
of
s
ht
yrig
op
C
m
This appendix covers web application directory structure.
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
Every web application have a specific directory structure to deploy the web
application .The Application Root have WEB-INF folder. WEB-INF folder contain
classes folder. Same levels to WEB-INF html, jsp, txt etc. files are
maintained. In side WEB-INF and same level to classes folder web.xml is
maintained. In side a classes folder *.class files are available.
web.xml
The web.xml file provides configuration and deployment information for the web
applications/components that describe a web application is called “Deployment
Descriptor (DD)”.
m
<?xml version="1.0" encoding="UTF-8"?> XSD
lu
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-information.
cu
ri
instance" xmlns="http://java.sun.com/xml/ns/javaee"
ur
lC
xmlns:web="http://java.sun.com/xml/ns/javaee/web-
ia
app_2_5.xsd"
c
ffi
|O
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
d.
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5"> Lt
ch
te
<display-name>LoginProject</display-name>
fo
<welcome-file-list>
In
<welcome-file>index.html</welcome-file>
SE
<servlet-name>LoginServlet</servlet-name>
C
<servlet-
class>com.seed.servlet.LoginServlet</servlet-class>
<init-param>
Initialization
<param-name>driver</param-name> parameters
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
m
This appendix covers request-response flow of web application.
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
m
application differentiates the requests meant for specific application
lu
cu
resources.
ri
ur
9. If the request is for a static resource (HTML file) within the application, it
lC
ia
is rendered through an HTTP response immediately.
c
ffi
10. Web Container refers to the mapping information (web.xml) available
|O
in the web application for pin-pointing the specific dynamic resource
d.
within the web application. Lt
ch
11. If an object of the dynamic resource is not available in memory, it is
te
fo
browser.
s
ht
14. Same cycle runs for each and every request generated by the client’s
yrig
browser.
op
C
c
ffi
|O
d.
Sr. Chapter Name Lt Page No.
ch
No.
te
fo
In
m
lu
The lab manual consists of a set of lab exercises defined chapter-wise. Each
cu
ri
exercise has a definite objective defined. These objectives map with the terminal
ur
lC
objectives defined at the beginning of each chapter. The problem statement is
ia
c
defined with clear instructions.
ffi
|O
Some exercises have specific configuration or pre-condition mentioned. Advanced
d.
Lt
lab exercises are also given for some topics.
ch
te
Appendix C given at the end of lab manual contains stepwise instructions to use
fo
In
Configuration
SE
of
m
lu
cu
How to use the Lab Manual?
ri
ur
lC
Whenever a programmer has to transform a problem statement into a program
ia
which a computer can execute, the activity should be split in the following
c
ffi
|O
manner:
d.
Read the problem statement carefully. Hint is given for some problem
Lt
ch
statements to help you to solve the problem.
te
Preparation
fo
In
Write the algorithm or steps to be followed to solve the problem. You can
SE
Also decide how one module (function) would communicate with other
C
module (function).
Give a dry run to the algorithm written.
Write the code.
Execute the code.
Coding practices
The maintenance of code is easy if the code is written using coding practices. You
should follow following coding practices while solving the lab exercises in this lab
manual:
Use meaningful names for variables, functions, file.
Use uniform notation throughout your code.
Code should be properly indented.
Code should be commented. While documenting your code, write the
purpose of your piece of code.
m
lu
cu
Writing a right kind of well-documented software is an art along with your
ri
ur
lC
technical skills. Enough necessary documentation should be done. This makes
ia
the code easily maintainable.
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
Lab Exercise - 1
lu
cu
ri
Objective
ur
lC
Access data from the tables in the MySQL database and perform operations
iac
like insert, update and delete using JDBC.
ffi
|O
Configuration: MySQL should be installed.
d.
Pre-condition Lt
ch
te
employee table should be present in the database. The table should have
fo
In
Problem Statement 1
of
prompt.
y
op
Problem Statement 2
C
m
lu
1001 Prashant 20000
cu
ri
ur
1099 Anuradha 30000
lC
ia
For SQL statements to create the structure, refer ‘script.txt’.
c
ffi
|O
Problem Statement
d.
Lt
Perform the account transaction between Prashant’s account and Anuradha’s
ch
account.
te
fo
In
Hint
y
op
Lab Exercise - 3
Objective
Invoke the stored procedure present in the SQL Server database.
Pre-condition
Stored procedure named “account_rout” to update the record from the
table. It should take accno as a parameter.
For code of the procedure refer‘script.txt’.
Problem Statement
Create a procedure for account table to update the balance.
m
Lab Exercise - 4
lu
cu
Objective
ri
ur
Use of resultset metadata.
lC
ia
Use of database metadata.
c
ffi
|O
Configuration MySQL should be installed.
d.
Pre-condition Lt
ch
te
employee table should be present in the database. The table should have
fo
In
Problem Statement 1
SE
of
Display all employee information in swing application from the employee table
s
ht
Problem Statement 2
C
Display all the database information in swing application like reserved keywords,
table names, indexes etc.
m
lu
Lab Exercise - 5
cu
ri
Objective
ur
lC
Retrieve data from the table in the MySQL database using scrollable
ia
c
ffi
resultset.
|O
Update data in the table in the MYSQL database using updatable resultset
d.
Lt
Configuration MySQL should be installed.
ch
te
Pre-condition
fo
In
employee table should be present in the database. The table should have
ED
SE
Problem Statement 1
s
ht
rig
Display all employees from last record to first record in a swing application from
y
op
Problem Statement 2
Display only first and last record from employee table in swing application.
Problem Statement 3
Update the salary of all employees whose salary is less than Rs.15000 by Rs.2000
to the employee table. Display the updated records at the command prompt.
Lab Exercise - 6
Objective
Perform transactions using batch update.
Pre-condition
account table should be present in the database. The table should have
fields like accno, acc_holder_name, balance.
account table should contain 2 records like:
m
lu
cu
1099 Anuradha 30000
ri
ur
lC
ia
SQL statements refer ‘script.txt’.
c
ffi
|O
Problem Statement
d.
Lt
Perform the account transaction between Prashant’s account and Anuradha’s
ch
te
account.
fo
In
state.
of
s
Hint
The signature of the method as below:
public void transfer (Account from, Account to, int
amount)
{. . .}
Lab Exercise -7
Objective
Insert and retrieve images using BLOB.
Configuration MySQL should be installed.
Pre-condition
employee table should be present in the database. The table should have
fields like employee_id, name, salary and emp_photo.
m
lu
emp_photo=<filename>.
cu
ri
ur
Problem Statement2
lC
ia
Display the all employee information with image from the employee table using
c
ffi
|O
swing UI.
d.
Lt
ch
Lab Exercise - 8
te
fo
Objective
In
ED
Grip Assignment
SE
of
Problem Statement 1
rig
y
op
m
Lab Exercise - 9
lu
cu
ri
Objective
ur
lC
Construct static web pages using HTML and JavaScript.
iac
ffi
Configuration IE or Mozilla Firefox should be installed.
|O
d.
Pre-condition
Lt
ch
Required images should be available.
te
fo
Problem Statement
In
ED
1. home.html
of
s
ht
m
b. Create an image link or button for new users –“register now!”
lu
cu
c. Handle JavaScript validation as follows:
ri
ur
lC
i. Username and password fields are mandatory.
ia
c
ii. Password must be at least 8 characters long.
ffi
|O
iii. Atleast one special character.e.g. is(!,#,$,^,&) should be used in the
d.
password. Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
3. register.html
a. This is registration page and should contain following fields:
fields input type
username text
password password
firstname text
m
lu
lastname text
cu
ri
ur
address1 textarea
lC
iac
address2 textarea
ffi
|O
combobox(select and
d.
city
Lt option tag)
ch
te
combobox(select and
fo
state
In
option tag)
ED
SE
text
ht
mobile number
y rig
op
m
Lab Exercise - 10
lu
cu
ri
Objectives
ur
lC
Construct XML document.
iac
Construct DTDs and XSDs.
ffi
|O
Problem Statement 1
d.
Lt
“BookWorld.com” is an online book shop containing number of books belonging to
ch
te
different categories. It is possible to identify a specific book using the book id.
fo
In
Book Id can identify specific book name, author name, price of that book or
ED
edition of that book. Some books are available in different formats such as html or
SE
Using above details, identify the elements, attributes and create a DTD.
yrig
Problem Statement 2
op
C
m
Lab Exercise - 11
lu
cu
ri
Objective
ur
lC
Construct Servlet life cycle methods.
ia
c
ffi
Pre-condition
|O
login.html should be created.
d.
Lt
ch
Problem Statement 1
te
fo
Problem Statement 2
Enter username and password in login.html and click on submit button. The
request should be passed to LoginServlet which will check whether entered
username and password are valid or not. If they are valid then print message
“Welcome <username>” otherwise print “Incorrect username or password”.
Objective
In
ED
Pre-condition
of
s
Problem Statement1
op
C
Establish a connection with MySQL database and check that entered username
and password are valid or not.
Problem Statement2
Establish a connection with MySQL database and check that entered username
and password are valid or not.
use Hint to solve this problem statement.
Hint
Configure the database using either ServletConfig interface or
ServletContext interface.
m
lu
cu
Pre-condition
ri
ur
Lab Exercise - 12 should be created.
lC
ia
c
Problem Statement
ffi
|O
Create an html page inside GreetingServlet which accepts the username. On
d.
Lt
clicking the submit button the request should be passed to the second Servlet
ch
called ResponseServlet. This Servlet should generate a response Hello,
te
fo
<username>!
In
ED
SE
of
s
ht
rig
y
op
C
d.
the response of the first servlet. Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
Lab Exercise - 14
lu
cu
ri
Objectives
ur
lC
Construct a Servlet application using session tracking mechanisms.
ia
c
ffi
Pre-condition
|O
Lab Exercise-11 should be created.
d.
Lt
ch
te
fo
Problem Statement 1
In
ED
Enter username and password in login.html and click on submit button. The
SE
whether entered username and password are valid or not. When user clicks on
s
ht
HiddenFieldServlet which should accept movie names and show all the
ED
movie names with username. The application should also show the sessionId.
SE
of
Enter username and password in a login.html and click on submit button. The
fo
In
CookiServlet which should accept name and password and should print the
SE
name and value. Clicking on update button, should show the name and value in a
SE
cart. If cookies are disabled then code should automatically execute using URL
of
rewriting. Use same application for session tracking using HttpSession. Print
s
ht
rig
Lab Exercise - 15
Objectives
Construct a Servlet application using filter.
Pre-condition
Lab Exercise-11 should be created.
m
lu
entered username and password are valid or not. Before request is passed to
cu
ri
LoginServlet it should be passed through LoginFilter. If password is
ur
lC
“seed” only then the request should be accepted otherwise the should be
ia
c
passed again to same html page i.e. login.html.
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
m
lu
cu
Pre-condition
ri
ur
Lab Exercise-11 should be created.
lC
iac
Problem Statement 1
ffi
|O
Test Servlet life cycle using listeners.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Pre-condition
Lab Exercise-14 should be created.
Problem Statement 2
Test Session tracking management using listeners.
m
lu
Lab Exercise - 17
cu
ri
Objective
ur
lC
Construct jsp applications using jsp directives and scriplet.
iac
ffi
Problem Statement 1
|O
d.
Write a “pageDirective.jsp” page to check the page directive with its
Lt
ch
attributes. Check errorPage and isErrorPage attribute. If exception occurs
te
then it should automatically pass to errorPage and display the error message.
fo
In
ED
SE
of
s
ht
rig
Problem Statement 2
Include and show the current date and copyright message in include.jsp.
Generate current date in incuded.jsp and copyright message in
copywrite.html.
included.jsp
copyright.html
m
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
Problem Statement 3
rig
y
Check scriplet tags using any simple ‘C’ based program such as printing table of 2.
op
C
Lab Exercise - 18
Objectives
Include and forward action.
Implicit objects.
Problem Statement
Enter username and password in a login.html and click on submit button. The
request should be passed to accept.jsp which should check whether entered
username and password are valid or not. If they are valid, then “welcome
<username>” should be printed otherwise “Incorrect username or password”
should be printed.
Lab Exercise - 19
fo
In
Objective
ED
Using UseBean.
SE
of
Problem Statement
s
ht
rig
Accept a name and favorite programming language from the beans.html page
y
op
m
Objective
lu
cu
Using Custom Tag.
ri
ur
Problem Statement
lC
ia
Develop a “hello world” application which will print current date and time using
c
ffi
custom tag.
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
Lab Exercise - 21
rig
y
Objective
op
C
Problem Statement 2
Develop a JSTL application to check core tags.
m
This document is a guideline to use eclipse.
lu
cu
ri
1. To open Eclipse.
ur
lC
Go to the eclipse folder and click on eclipse icon.
iac
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
cu
Workspace: Eclipse stores your projects in a folder called a workspace.
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
Once you click on the ‘Browse‘button after that new window appear ‘select
Workspace Directory’.
Select your folder if already created or create new folder and than select.
To create new folder click on button ‘Make New Folder’ and finally click on
‘OK’ button.
Once you click on ‘OK’ button .It starts to create workspace for you and eclipse
create workspace on your current directory with a folder name .metadata. At the
same time it opens new window which is something called it as Eclipse window.
Workspace create
m
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
Eclipse is an ID for the different types of applications like using this ID we can
of
s
execute Core Java applications as well as java server based applications and so
ht
rig
on.When we want to execute simple core java related application required core
y
op
m
lu
cu
ri
ur
lC
iac
A
ffi
|O
d.
Lt
ch
B
te
fo
In
C
ED
SE
of
s
ht
yrig
op
C
new Project window appear.Now enter some information to create new Project .
like:
a. Project name :enter your Project name e.g.
HelloServletDemo A
buton.
y
op
C
After that click on ‘next’ button. It will appear New Dynamic Web
Project window.This window contain context root and contet directroy and one
check mark for generate web.xml deployment descriptor automatically.
Once we clcik on finish button web appplication project create with required lib
SE
m
FileNewServlet
lu
cu
ri
ur
lC
iac
ffi
A
|O
d.
Lt B
ch
te
fo
In
ED
SE
of
s
ht
rig
create servlet class window appear.create a new servlet class for that purpose
y
op
like:
a. Project and source folder: enter your folder name or source
location by default it is your project name with src folder. e.g.
\HelloworldDemo\src B
b. Java Pacakge and class name :enter package name if required.If you not
C
maintion package name it will take default pacakge.Enter the class name.It is
mandatory.Servlet class by default extends to HttpServlet.
After that click on ‘next’ button and set url mapping parameter.Keep
is as default or edit the url mappings.
After that click on next button to select required methods in servlet application.
rig
y
op
C
Once we clcik on ‘finish’ button servlet class create under the web application
environment.
m
lu
cu
ri
ur
lC
iac
ffi
|O
d.
Lt
ch
te
fo
m
This document is a guide to use MySQL database.
lu
cu
ri
1. To Open database and establish the connection.
ur
lC
Step 1
ia
c
ffi
Open MySQL database and click on ‘open connection to Start
|O
Querying’ for login purpose.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Step 2
Connect to Database Window opens.
Connect to Database:
Enter database specific information as follows and click on ‘OK’.
m
Password: (the users password) e.g. myroot
lu
cu
After that click on OK button.
ri
ur
lC
iac
Step 3
ffi
|O
Enter the password to connect the MySQL service and click on OK button.
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
lu
using MySQL wizard. Using this wizard tables views SQL stored Procedures can also
cu
ri
be created. This Workbench provides some default schemas custom schemas.
ur
lC
2. To create table in MySQL.
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
Step 1
Click on the ‘Add Table’ to create a new table.
‘new table’ window come into view.
Name: (The name of the table) spaces should be avoided if required use
of
s
mandatory.
y
op
Step 2
Select Column tab to enter field information.
1. Column name
s
ht
2. Datatype
yrig
op
3. Constraints
C
Table will now be created in the database. The snapshot given below.
m
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
Click on the table name so that Query Result window appears.
te
fo
In
ED
SE
of
s
ht
rig
y
op
C
lC
ia
‘Execute All’.
c
ffi
|O
Step 5: Record will be created in the database table.
d.
4. To create stored procedure (Routine). Lt
ch
te
fo
In
ED
SE
of
s
ht
yrig
op
C
m
‘new routine’ window comes into view.
lu
cu
ri
ur
lC
ia
c
ffi
|O
d.
Lt
ch
te
fo
In
ED
SE
of
s
ht
Name: Need not required to enter .the name of routine is passed automatically
C
from the DDL statement. The DDL is passed automatically while you type.
Once you write routine successfully after that click on ‘Apply’ button.
Step 2
Review the SQL script on the database. After that click on ‘Apply’ button.
Once you click on ‘Apply’ button SQL script applying to the database. Click on
‘Finish’ button.