Você está na página 1de 172

Contents

1. Introduction
2. Architecture of an Enterprise Application
3. JDBC
4. JDBC Architecture
5. Database Connectivity steps
6. Database Connectivity using jdbc-odbc
7. Program, Advantages and Disadvantages of Type 1
Driver(Bridge Driver)
8. Submitting SQL statements to the database
9. Program to insert record into the database
10. Type 4 Driver
11. Program and Advantages of Type 4 Driver
12. Driver Manager, Connection and Statement objects
13. Program on database connectivity using File (Generic) concept
14. Steps in retrieving data from database
15. ResultSet object
16. Differences between Statement and PreparedStatement object
17. Steps to implement PreparedStatement
18. Architecture of Web Application
19. Limitations of a Web Server
20. Types of internet programs
21. Servlets
22. Pre requisites for a servlet execution
23. Difference between Web Container and Web Server
24. Servlet Development
25. Servlet Life Cycle (Protocol Independent)
26. Web Application Development Steps
27. Web Application Deployment Steps
28. Different names and functions of a Servlet
29. Program on Servlets
30. Background Process after submitting the form
31. Initialization Parameters
32. Program on Initialization Parameters
33. ResultSetMetaData interface
34. Stored Procedure
35. Program on Callable Statement
36. Generic Servlet in depth
37. ServletContext
38. Program on ServletContext
39. HttpServlet Basics
40. Difference between GET and POST
41. Life Cycle of HttpServlet
42. Program on HttpServlet implementation
43. Servlet Collaboration
44. RequestDispatcher, Forward and Include
45. Program on RequestDispatcher
46. Filters
47. Development and Deployment of Filters
48. Program on Filters
49. Filters in depth
50. JSP Introduction
51. Life Cycle of JSP
52. JSP constituents
53. implicit objects
54. Programs on Jsp
55. Java Beans
56. Using Java Beans in Jsp
57. Program on Java Beans
58. Various scopes of Java Beans in Jsp
59. Jsp architecture
60. MVC architecture
61. Program on MVC architecture
62. Difference between include directive and include standard
action
63. Program on Jsp include directive and include standard action
64. Session Tracking
65. Cookies
66. Program on cookies mechanism
67. HttpSession
68. URL rewriting
69. Difference between Standard action and Custom action
70. Custom tag development
71. Steps to develop Custom tag
72. Custom tag in depth
73. Program on Custom tag
74. Life Cycle and Flow Chart of Custom tag
75. Types of ResultSet
76. Batch Updates
77. Type 2 and Type 3 Drivers
78. Java Server pages Standard Template Library (JSTL)
79. Programs on JSTL
Topics:

JDBC
Servlets
JSP
Beans
Expression Language
JSTL

Introduction:

JAVA:-

 It is Object Oriented Programming Language.


 It is a Platform (Runtime Infra-structure + libraries).
 It is a Technology.

Three flavors of JAVA:-

 J2SE:- Standard Edition- core java


 J2EE:- Enterprise Edition- advanced java and J2EE
 J2ME:- Micro Edition

Usage:-

 C is used in low-level programming like Systems programming,


Compiler designing, etc.
 Java is used in Enterprise Application Development

Enterprise Application:-

 Any Computer Application that helps in automating day to day


operations of a business organization (enterprise) is known as
Enterprise Application.
Ex: - Banking, Insurance, Super Market, Hospital Management,
Hotel Management.
Architecture of an Enterprise Application:

Tier: - A logical partition of the components involved in a system


(application).

Every Enterprise Application has 4 tiers.

 Client tier.(Browser)
 Presentation tier.(Web-Server)
 Business tier.((Rules)
 Data tier.(Data)

HTML Request Servlets


Java Script JSP EJB
Java Beans
Response

Client tier Presentation tier Business tier


JDBC
JDBC

Data tier
Client tier: - In an Enterprise Application, the client tier is mostly the
browser.
End-user of the application interacts with the entire Enterprise Application
using this tier.
Technology used: - HTML, Java Script.
Presentation tier: - This acts as an interface between client tier and the
business tier.
Major responsibilities are as follows:-

 Receiving the requests from client tier.


 Authentication and Authorization.

Authentication: - Validation of user.


Authorization: - Permissions granted to the user.

 Maintaining the sessions.


 For core business logic execution sake, sending the request to
the business tier.
 Preparing the output and driving it to the client.

Business tier: - This tier of the Enterprise application holds the core
business rules implementation. This tier receives request from the
Presentation tier for Business Logic Execution.
Major technology used is EJB.

Data tier: - This is the Enterprise’s information storage.


Mostly it is the Database server.
JDBC (Java Database Connectivity)

 JDBC is a Technology provided by Sun Microsystems.


 JDBC is not a Software Product.
 JDBC is a Specification.
 JDBC defines a *Vendor independent way of communication between
any java program and the database.
Vendors: - MS-SQL, ORACLE.
*Vendor independent: - Java program will not change with the change
in database.
 Java programs (be a stand-alone client or a servlet / jsp or an EJB) are
capable of making only method calls, whereas industry standard
database server can understand only SQL.

JDBC Architecture

There are 5 elements in JDBC architecture:

1) Java Client
2) JDBC API
3) Driver
4) Driver Manager/ Data Source
5) Database Server
JDBC Architecture

Client Java Program

JDBC API

DriverManager/Data Source

Driver

Database Server

I.Java Client Application: - It is any database aware java program.


This can be any of the following:-
a. Stand-alone GUI client
b. AWT/Swings Application
c. A Servlet
d. An EJB
e. A Java Bean
f. A JSP
Responsibilities of Client Java Application:-
 Requesting the database server for connectivity. To make
this request, application uses JDBC API. Server-Socket
Programming is involved internally.
Without Socket, no client can connect to the server.
 Preparing the appropriate SQL statements and submitting
them to the database server by using JDBC API.
 Define the Storage Areas.
Storage Areas are the places to store the data like bringing
data from database and store them in RAM.
 Process/fetch the data that is stored in the Storage Areas.
 Error Handling.
 Controlling Transactions whenever necessary. Transactions
should be ATOMIC (Fully done or not done at all).
 Closing the connection
II. JDBC API: - It is a set of Interfaces and Classes (few). JDBC API is a
collection of library methods that support SQL statements.
To every java program JDBC API support is available through two
packages.
1. java.sql
2. javax.sql

Java libraries are divided into two


1. java- core API
2. javax- Extension API

III. Driver: - It is software. It performs the following things:


 Establishing connection with the Database Server
 Receiving JDBC method calls from the Client Application
 Performing translations
 Submitting the JDBC requests to the database server
 Providing the Client with the requested data
 If required, initiating the transformation
IV. DriverManager: - It is an element in the JDBC
Architecture whose major role is to provide the connection to the Client
Java. Its role ends as soon as connection is established.
V. Database Server: - In the industry strength Enterprise Application, this
is mostly RDBMS.
Examples:-
 Oracle
 Sybase
 SQL Server
 Informix
 DB/2
Informix and DB/2 are IBM databases.
Database Connectivity Steps (Approaches)

DriverManager
Connectivity Approaches
DataSource

Hybrid Approach (jdbc-odbc)


Connectivity Approaches
Pure jdbc approach

DataSource is used in real time rather than DriverManager.

Database connectivity using jdbc-odbc:

Step 1: Loading the driver into java environment


Step 2: Preparing the database connection URL
Step 3: Requesting for the connection
Step 4: Once done with the database operations closing the connection

Loading the Driver Class.forName (“Driver Class”);

Preparing the connection URL


“jdbc: odbc: DSNName”;

Requesting for the connection


DriverManager.getConnection ();

After database operations, close the


connection Connection.close ();
Loading the Driver:-

Driver is a java class. It establishes the connection with the database.


Therefore, we have to bring this class into java environment. Driver class is
not part of JDBC API. In order to load this class into java environment we
make use of following method.

Class.forName (“Fully qualified driver class”);

Once this method call is made, 3 things happen

1) Driver class is dynamically loaded into memory.


2) Driver class is instantiated.
3) Driver instance is registered with the DriverManager.

In case of jdbc-odbc approach of connectivity, the Driver class is as


follows:-

“sun.jdbc.odbc.JdbcOdbcDriver”

This Driver is famously known as Bridge Driver. It is Type 1 Driver as far as


SUN is concerned.

Note: - Class.forName () throws ClassNotFoundException.

Preparing the Connection URL:-

The general form of URL in case of hybrid approach is

Protocol: subprotocol: dsnname

Data Source Name (DSN): It is a named configuration that comprises of


vendor dependent driver, OS, database and few optional settings.
This is done external to the java program.
DSN does not exist in pure JDBC Approach.

Requesting for the Connection:-


Client Application requests the java.sql.DriverManager or
javax.sql.DataSource for the sake of connection with the database

The following static method of the DriverManager class is called by the


Client Application for the sake of connection.

DriverManager.getConnection (String URL, String user, String pwd);

Closing the Connection:-

Once we are done with database operations we have to close this connection
by calling close () on Connection.
/* Program to connect to the Oracle database server using Type 1 driver
(Bridge Driver) */

import java.sql.*;

class HybridConnectivity
{
public static void main (String args []) throws Exception
{
//Step 1:- Loading the Driver

Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
System.out.println (“Driver is loaded, instantiated and registered with the
DriverManager”);

//Step 2:- Preparing the Connection Url

String URL=”jdbc:odbc:student”;

//Step 3:- Requesting for the Connection.


Connection con=DriverManager.getConnection (URL, “Scott”, “tiger”);
System.out.println (“Connection is established”);

//Step 4:- Closing the Connection

Con.close ();
System.out.println (“Connection closed”);
}
}
JDBC
method
calls
-- Bridge
` -- Driver
--
-- Database
-- ODBC SQL Engine
-- function
-- calls
-- Vendor
-- dependent
-- ODBC
-- Driver
Database Server calls
Client Java Database Server
Application

Advantages of Bridge Driver:-

Using this single driver we can get connected to any database.


As it is internally uses ODBC technology which is already a proved
technology, connectivity sake SUN need not have experimented.

Disadvantages of Bridge Driver:-

Because of 2 layers and translations, performance is compromised and hence


barred in the industry.
It cannot be used in the internet and intranet based applications. In every
Client machine, database vendor library should be present. It leads to
maintenance problems.

Role of interfaces in J2EE Applications

 An interface acts as a contract between service provider and service


user.
 An interface acts as a data type. That means its reference can be
created even though its object cannot be created.
 An interface can act as a parent to a class.
 In java, super class (interface) reference can reference to subclass
object.
 An interface is meant for standardization.
 An interface provides the names of the services (only abstract
methods) whereas a class provides the service by implementing the
interface.
 In advanced java programming, we encounter methods returning
interface objects or methods taking interface objects as arguments. In
fact, they are not objects, just they are references.

Note (interview questions):-

Why not directly use ODBC?


It is implemented in C, therefore security and portability is at risk and also C
is procedure oriented and Java is Object Oriented.

Why Connection is interface not a class?


Giving freedom to vendor to implement their own logic. Uniformity is given
to programmer (Standardization).
Submitting SQL statements to the database

Requesting for the Connection

Prepare the SQL Statement

Build the Statement object

Submit the SQL statement with the help of


Statement object

Close the Statement object

Close the Connection

1. Request for the connection:

Class.forName(“Driver class”);
DriverManager.getConnection (“jdbc: odbc: DSNName”);

2. Prepare the SQL Statement:

In a Java Program, SQL Statement is a String. As a programmer we


should know the SQL syntax for building the DML/DDL/DRL/DCL
Statements.

Note: Almost all we never submit DDL Statements from the Java
Program to the Database Server.

3. Building the Statement Object:


According to JDBC API, we have 3 kinds of Statement Objects.
 Java.sql.Statement
 Java.sql.PreparedStatement
 Java.sql.CallableStatement

Statement Interface

PreparedStatement Sub-Interface

CallableStatement Sub-Interface

In order to create Statement Object, we make use of Connection Object.

4. Submitting the SQL Statement:

java.sql.Statement has 2 important methods to submit SQL Statements


to the Database.

public int executeUpdate (String dmlsql) throws SQLException:

This method takes DML Statements as arguments i.e., by using this


method we can submit INSERT UPDATE and DELETE SQL
Statements to the Database. This method returns an integer that
represents the number of rows affected in the database table as a result
of the database operations.

Public ResultSet executeQuery (String SelectStatement) throws


SQLException:

This method takes SELECT SQL Statements as argument and returns


Database records in the form of a ResultSet Object.

5. Closing the Statement Object:


st.close ();

In the above statement st is a reference that refers to an Object that


implements Statement interface.

6. Closing the Connection:

con.close ();

Write a program to INSERT a record into the database table

import java.sql.*;

public class InsertOperation


{
public static void main (string args []) throws Exception
{
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
String Url= “jdbc: odbc: student”;
Connection con=DriverManager.getConnection (Url);
System.out.println (“Connection is established”);
String Sql= “INSERT INTO STUDENT VALUES (1001, ‘adil’, 98);
Statement st=con.createStatement ();
int r=st.executeupdate (sql);
System.out.println(r+“row inserted”);
st.close ();
con.close ();
}
}

Note (interview questions):-

Why Statement is an Interface but not a Class?

When Database is changing, we need to change the Class several times.

Why Statement is always produced from Connection Object?


Dedicated socket Connection is established with the Database Server and
each Statement is given an Address Space in the Database through which all
the communication takes place between that Statement Object and the
Database Server. For recognizing each client uniquely.
JDBC Drivers:

Establishing the connection using pure JDBC approach:

JDBC
method
calls
-- Pure Driver
--
--
--
-- SQL Db engine
--
--
--
--
--
--

Database Server calls


Client Java Database Server
Application

Steps

Loading the Driver

Preparing the Connection URL

Requesting for the Connection

Close the Connection after the Operations


 Type 1 Driver is called Bridge Driver

 When we use Type 1 Driver (Bridge Driver) to get connected,


performance gets down on account of two layers (JDBC and ODBC).
Therefore this type of driver cannot be used in the Real time
Applications.

 To overcome this problem, we have pure JDBC Drivers that eliminate


ODBC completely.

 When we want to connect to the databases we use ORACLE thin


driver. (Type 4 driver). It is pure JDBC driver.

 JDBC driver are manufactured by the database vendors but not sun.

 JDBC is a specification for the driver manufacturers.

 If the driver is manufactured according to JDBC specifications, then


only it is called as JDBC Complaint Driver.

 JDBC complaint driver implement JDBC API, whatever method calls


we make in a program are received by the Driver.

 JDBC is a Specification for Driver manufacturers.

 JDBC is an API for programmers.

Advantages of pure JDBC driver:

 Performance is more.
 Can by used in Internet and Intranet Application.

// Program on getting connected to Oracle Database Server using thin Driver


(Type 4)

import java.sql.*;

class JdbcConnectivity
{
public static void main (String [] args) throws Exception
{
// Loading Driver

Class.forName (“oracle.jdbc.driver.OracleDriver”);
System.out.println (“Driver is created, instantiated and registered with
DriverManager”);

// Preparing the url

String url = jdbc: oracle: thin:@localhost:1521:server;

// Requesting for the Connection

Connection con = DriverManager.getConnection (url, “scott”,”


tiger”);
System.out.println (“Connected”);
Statement st=con.createStatement ();
st.executeUpdate (“CREATE TABLE STUDENT (rollno number (4),
name varchar2 (12), marks number (3))”);
System.out.println (“Table Created”);
// Closing the Connection

st.close ();
con.close ();
}
}

executeUpdate () will return 0 in case of Create Table.

Note:

oracle.jdbc.driver.OracleDriver class is not a part of JDBC libraries.


Therefore, existing class path is not sufficient.

We should specify to the JVM where from this class has to be loaded.
Otherwise ClassNotFoundException rises.
Classpath:-

D:\oracle\ora8i\jdbc\lib\classes111.zip (or)
D:\oracle\ora8i\jdbc\lib\classes12.zip

JVM’s Class Loader will take care of the classpath.

%classpath% - Used for appending to already existing classpath.

Search for the following file in our system to prepare for the
connection URL for oracle thin driver:
D:\oracle\ora8i\network\admin\tsnnames.ora

Syntax for the URL:


Protocol: sub-protocol: driver type: machine ip: port no: Server-id

What is the capability of Class.forName ()?

This method can load any java class into memory dynamically. It
cannot create the object of that class and cannot register the object to
anybody.

In JDBC program, when we say Class.forName (“Driver”), only


Driver class is loaded into memory. It is the responsibility of the
Driver class Developer to ensure that Driver class object is created
and registered with DriverManager automatically whenever the class
is loaded into the memory. Static block should be used for this.

//Sample of a Driver Program

class OracleDriver implements Driver


{
static
{
Driver d= new OracleDriver ();
DriverManager.registerDriver (d);
}
}
What happens in the background when getConnection () is called on the
DriverManager?

getConnection () returns a reference of type java.sql.Connection. That


reference refers to an object that is the abstraction of networking connections
between the client and database server. The kind and type of object will be
Driver independent.

What is a Statement in the context of JDBC Programming?

Java.sql.Statement is an interface. Statement is a jdbc object created by the


Driver in a vendor dependent manner.

Statement st=con.createStatement ();

Responsibility of Statement object is to submit and return the SQL


statements and results respectively within the client connection space in the
database server.

Why to close Connection object?

To release the network resources those are consumed by the client to have
the Socket connection with Database Server.

Why to close Statement object?

To release jdbc resources.

//Program to perform delete and update operations from the java program:

Import java.sql.*;
Class UpdateOperation
{
Public static void main(String args[]) throws Exception
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:Serv
er”, “scott”, “tiger”);
Statement st=con.createStatement();
int rows;

rows=st.executeUpdate(“Update Student set marks=marks+10 where


marks>49”);
System.out.println(rows+”rows expected”);
St.close();
Con.close();

}
}

//write a java program to get connected to oracle database.


Don’t do hard coding in the program regarding driver, connection url,
authentication information:

In industry strength applications javax.sql.DataSource replaces


DriverManager. For DataSource implementations to get connected to the
Database, Driver details, and Database details are not required at
Application level. To implement DataSource, we need JNDI support. In
DriverManager approach also we can avoid hard coding by using two things:

File Concept
Java.util.properties object
import java.sql.*;
import java.util.*;
import java.io.*;

class GenericConnectivity
{
public static void main (String [] args) throws Exception
{
Properties p=new Properties ();
FileInputStream fis=new FileInputStream (“dbprops.txt”);
p.load (fis);
String driver=p.getProperty (“d”);
String url= p.getProperty (“cu);
String user= p.getProperty (“u”);
String pwd= p.getProperty (“p”);
Class.forName (driver);
Connection con=DriverManager.getConnection (url, user, pwd);
System.out.println (“Connected”);
con.close ();

}
}

Dbprops.txt file:

D=oracle.jdbc.driver.OracleDriver
Cu=jdbc:oracle:thin:@localhost:1521:Server
U=”Scott”
P=”tiger”

Jar –cvf classes12.jar classes12.zip


Jar –cvf classes12.jar
Retrieving data from the Database:

Get Connection

Prepare the SELECT Statement

Build the Statement Object

Submit the SQL Statement

Fetch the row and column values

Close Resultset
More
YES NO
Rows

Close Statement

Close Connection
Java.sql.Statement interface has one important method that is used to submit
SELECT statements.

public ResultSet executeQuery (String SQL) throws SQLException

This method takes a table of records in an object oriented manner i.e.


ResultSet object.

What is ResultSet?

It is an interface.
An object of some class that implements ResultSet interface is created by the
Driver and its reference is returned to java program.

ResultSet rs=st.executeQuery (“SELECT * FROM STUDENT”);

ResultSet object is an encapsulation of table of records sent by the Database


Server.

ResultSet when opened, a logical pointer called cursor is placed at the no


record place of ResultSet:

RS

Records

No Record Place
It is the responsibility of the Programmer to move the cursor to the record
existing location of the ResultSet.

Java.sql.ResultSet interface has 2 kinds of methods

Cursor Moving methods


Column values getting methods

Next () method is one important method which does two things

 It moves the cursor by one record in forward direction


 Once cursor goes there, column values are there (or) record is empty
is indicated by this method through Boolean value.

To retrieve column values, we have getXXX () methods in the ResultSet


interface. These methods are overloaded; we can supply either column name
(or) column number to these methods to get data.

//write a program to retrieve data from Database:

import java.sql.*;
class RetrieveData
{
public static void main (String [] args) throws Exception
{
Class.forName (“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:Serverid”, “Scott”, “tiger”);
System.out.println (“Connected”);
Statement st=con.createStetment ();
ResultSet rs=st.executeQuery (“Select * from student where rollno=844”);
If (rs.next ())
{
int r=rs.getInt (1);
String n=rs.getString (2);
int m=rs.getInt (3);
System.out.println(r+ ““+n + ““+m);
else
System.out.println (“Not found”);
rs.close ();
st.close ();
con.close ();
}
}
}
Retrieving all the records from the student table:

ResultSet rs=st.executeQuery (“select * from student”);


While (rs.next ())
{
System.out.println (rs.getInt (1) + “ “+rs.getString (2) + “ “+rs.getInt (3));
}

Note: for the getXXX () methods of the ResultSet, we have to supply the
column numbers based on the records of ResultSet object but not based on
database table columns.

What happens in the background when SQL Statement is submitted to


the Database engine?

a) Database engine parses the submitted SQL Statement looking for


syntactical errors.
b) Query Plan Generation
c) SQL Statement is executed

What is ability of Statement object? What are its


limitations/drawbacks?
Statement object is used to submit SQL Statements to the Database.
Whenever the same SQL Statement is required to submit multiple times with
different set of values, Statement object reduces the performance.
To overcome this problem, we go for java.sql.PreparedStatement

What is the difference between Statement object and


PreparedStatement object?

PreparedStatement differs from Statement object in two ways:

It has pre-compiled or already prepared SQL Statements in it whereas


Statement object is empty.
PreparedStatement has at least one ‘in’ parameters.

Note: ‘In’ parameters are those parameters whose values are not supplied at
query compilation time but supplied at execution time. At the time of
compilation instead of values, place holders (?) are kept.
Steps to implement PreparedStatement:

Request for the Connection

Build the PreparedStatement Object

Set the ‘in’ parameters

Submit the SQL Statement

More Close the


YES Statement NO PreparedStatement
s

Close the Connection


1. Request for the Connection:

Class.forName ()
DriverManager.getConnection ()

2. Building the PreparedStatement:

PreparedStatement ps= con.prepareStatement (“INSERT INTO


STUDENTS VALUES (?,?,? )”);

3. Set the ‘in’ parameters:

Supplying values to the Placeholders of the PreparedStatement object


is known as binding of parameters or setting ‘in’ parameters.

In order to set the ‘in’ parameters, we call setXXX () methods in the


PreparedStatement.

4. Submitting the SQL Statements:

We call executeXXX () methods on the PreparedStatement to submit


the SQL Statement.

5. Close the PreparedStatement:

ps.close ();

6. Close the Connection:

con.close ();
Web Application Development:

Technologies:

Servlets, JSP, JAVA BEANS, Expression Language, JSTL, Struts.

Main goal of Web Application Development is to web enable the Business


Applications i.e., making Enterprise Application Online.

Once we can develop a Web Application, we are Java Professionals and our
main role will be Web-Component Developers.

Web-Application:

Any Business Application that can be accessed from web interactively is


known as Web Application.

Architecture of Web:
Related
Http HTML
request Program <Html>
fetching from -
Hard Disk -
-
Http -
response & sending to -
Client -
Program -
<Html>

Web Client Web Server Web Page

Web Client:

It is a Browser Software. It is also known as Http Client. The main


functionality of web client is to establish Socket Connection with the Web
Server & making request for the sake of web resources (mostly web pages).
The communication protocol used by the Client is Http.
Web Server:

It is Software.
The main functionality of the Server:

 Accepting the incoming Web Client Connections.


 Processing the http request made by the browser (http client)
 Give the http response.

Note:

Browser is a Web Page Requesting Program and Web Server is web page
fetching.

Web Page:

It is an html document.

We have two kinds of web pages:

1. Pre-created html files stored in the computer hard disk.


These are developed by web designers using tools- flash, dream
weaver, etc.
These are the passive/static resources an end user want.
These are known as static resources because their contents never get
changed upon end users interaction.

2. Dynamic Web Pages are not pre-existing html documents i.e., these
web pages are programs and on the fly created whenever the request
comes from the Client. A Servlet or a JSP creates the Dynamic Web
Content Programmatically. They are known as Dynamic because their
content changes with end user interaction.
Limitations of a Web Server:

A web server provides http connection to the web clients. Its basic
limitations are that it can fetch web pages to the clients. If they are present in
the system of the server machine i.e., pre existing web pages. It cannot
handle complex Client requests that involves end users input with this
limitation following scenarios can’t be handled by the Web Server.

 User Authentication
 Online Bill Payments
 Online Reservations
 Online Banking

Types of Internet Programs:

Client side Program:

Validating the forms through Java Script / jscript is known as Client.

Server side Program:

Web Server should be able to handle any kind of http request. Whenever the
request involves end user’s input on its own it cannot process that request.

To overcome this problem it takes the help of external programs. These


external programs are nothing but server side Programs.

Server side technologies:

 CGI-Perl
 Asp
 Servlets
 JSP etc.

Drawback of CGI programs:

 Number of processes are more


 Process termination after response
 Running external to web server process
Servlets

 Servlet is a Web Technology.


 Servlet is one of the Components of Java Enterprise Edition.
 A Servlet is a Server side Program which is a replacement for the CGI
Programs.
 Servlet API is one of the JAVA API used to web-enable the Business
Application.
 According to specification (J2EE), a Servlet is known as Web
Component. Servlets Developer is known as Web Component
Developer.
 A Servlet is a Server Side Program that extends the functionality of a
Web-Server.
 Servlet produces Dynamic Web Content.
 Servlet is an active resource in a Web Application.
 A Web Application has 2 kinds of Web resources:

 Static/Passive (Html, Images)


 Active/Dynamic (Servlet/JSPs)

Q) If I want to write a Servlet and execute it. What are required in my


System (Computer)?

A) We need

 Servlet API
 Web Container that provides execution environment for Servlets

Note: A Web Container is Server Software.


Ex: Tomcat 5.0.x

Classpath: After loading the Tomcat Server, set the classpath to the
following jar file

C:\Apache\tomcat\common\lib\servlet-api.jar
Q) What is a Web Container? What is the difference between Web
Container and Web Server?

A) It is a Server Software, i.e., Web Server along with Servlet engine and
JSP engine.

Web Server cannot alone execute Servlets and JSP.

Request
S
E
R
V
L
Response E
T

Http service/ Servlet JSP


Web Client/ Web server engine engine
Browser

Web Container

Database
Server
Servlet Development

A Servlet is a java class that is written (defined) according to Servlets


Specification by using SERVLET API.

Servlet API is made available to java programs through 2 packages:

 javax.servlet.*
 javax.servlet.http

We have 2 kinds of servlets in java:

 Protocol independent
 Protocol dependent

A Servlet is said to be protocol independent. If it is capable of helping


(extending the functionality) of any kind of servers irrespective of protocol.
i.e., ftp server. Http server or SMTP server.

javax.servlet.GenericServlet class is an example of Protocol Independent


servlet.

A Servlet is Protocol Dependent if it is extending the functionality of only


one kind of server. We gave sun support only to Http Server.

javax.servlet.http.HttpServlet class is an example of Protocol Dependent


servlet.
Servlet Life cycle (Protocol Independent):

A Servlet is a Container managed Web Component. That is, Servlet instance


creation, initialization, destruction, etc. are done by the Servlet Container
(Engine).

Container can manage a Servlet if and only if the Servlet is defined


according to Servlet Specification.

According to Servlet Specification, a Servlet is any java class that directly or


indirectly implements javax.servlet.Servlet interface.

Indirectly means that calling this interface in our servlet which is already
implemented or extended in other classes or interfaces.
Ex: GenericServlet implements Servlet interface.

This interface provides 3 life-cycle methods.

 Init ()-at the time of initialization


 Service ()- at the time of processing the request
 Destroy () - container calls this method at the time of Servlet
destruction.

If we directly implements the Servlet interface, at that time it is mandatory


to implement all the above 3 methods.

Therefore to avoid this we need to use or implement indirectly or sub class


i.e., Generic classes.

Servlet interface specifies the Component contract between Servlet Engine


and our own Servlet.

Servlet

GenericServlet

Our Servlet
In Direct we have problem

Override all methods


Default implementation provided by GenericServlet is lost.

We cannot instantiate GenericServlet as it is abstract class so we should


instantiate our own servlet class.

When we write a Protocol Independent servlet our class extends


GenericServlet

javax.servlet.GenericServlet class implements Servlet Interface. This class


overrides all the abstract methods of Servlet Interface except service ()
method.

Service () method is declared as abstract in GenericServlet as the


programmer should compulsorily override that method.

Therefore GenericServlet class has become abstract class. It contains service


() as an abstract method. This enforces our own servlet class to override
service () method.

A Servlet life cycle comprises of 4 phases:

1. Instantiation
2. Initialization
3. Service
4. Destruction
Our Servlet life cycle

Container loads Servlet class into memory


Instantiation
phase
Servlet engine creates the instance of the Servlet class

Container creates instance of ServletConfig


Initialization
Phase
Container calls init () method

Container creates two objects ServletRequest and


ServletResponse

Container calls Service () method


Service
Phase

More
YES Requests?
Servlet is
Running

NO

Servlet is Is Servlet
NO Undeploye
Running
d?
Destruction
Phase

YES

Container calls destroy () method


1. Instantiation Phase:

According to the instruction given to the container it loads the Servlet


class into the memory dynamically.

Class c=Class.forName (“our servlet”);


Class.forname (“our servlet”) is used to load into memory
dynamically.

Servlet engine creates the servlet instance.

c.newInstance ()

Instance of ordinary class are called as objects but servlet, ejb, Java
Bean’s instances are not called as objects, but they are called
Components.

Sample Program to create instance of a Class:

Class A
{
A ()
{
System.out.println (“Instance of class A created”);
}
}
Public class B
{
Public static void main (String args []) throws Exception {
Class c=Class.forName (“A”);
c.newInstance ();
}
}
2. Initialization Phase:

When Container creates the instance of the Servlet, that Servlet instance
does not possess any Servletness. It cannot process any Client Request
because it does not have any idea about the Server environment. It is the
responsibility of the Container to provide such information to the Servlet
and fetch Servletness to the instance.

Servlet engine creates the proprietary object that implements ServletConfig


interface. This object holds initialization and context information.

Servlet engines calls the init () method on Servlet instance by supplying


ServletConfig object as argument. Once init () method completes its
execution, Servlet instance gets Servletness and it ready to serve any Client
Request.

3. Servicing Phase:

Servlet engine receives the request from http service that includes Client info
and the data sent by the Client. Based on this information, Servlet engine
creates two Proprietary objects that implement ServletRequest and
ServletResponse interfaces respectively.
Container calls service method as the Servlet instance by supplying these
two objects as arguments.

As a Servlet developer, we write Application logic in the service method.


This method is executed every time when the request comes to the Servlet.

4. Destruction Phase:

When the Web Application is undeployed by the Administrator, Servlet


instance is Garbage Collected. Before Servlet instance is Garbage Collected,
Container calls destroy () method on the Servlet instance. In this method,
Servlet Programmers write cleanup code.
Skeleton structure of a Servlet:

import javax.servlet.*;
import java.io.*;

Public class OurServlet extends GenericServlet


{
Public void init (ServletConfig config) throws ServletException
{
//code to retrieve initialization info
//code to provide resources to the Servlet
}
Public void service (ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
//Application logic varies from Web Application to Web Application
}
Public void destroy ()
{
//clean up code
}
}//OurServlet
Web Application Development Steps:

Every Web Application comprises of

 Html document
 Image files
 Servlets
 Jsps
 Other helper classes
 Xml document(s)

Step 1:

Creation of a hierarchy of directories according to the specification

Root Directory (any name)

*.html

JSPs

Image files
Servlet class files
WEB-INF

Bean class files


classes

Helper class files

lib *.jar

web.xml
The root directory acts as Web Application’s root context. It has 2 parts.

I. Public Area: Directly under the root directory all the web resources
that can be accessed from the client are placed.
a. Htmls
b. JSPs
c. Image files
II. Private Area: Directly under the root directory we should create a
directory by the name WEB-INF whose contents are exclusively
meant for the container access. These files cannot be accessed from
the client.

Step 2:

Defining the Web Component

We need to write a servlet class or a JSP.

This Web Component is primarily responsible to make the Web Application

When we want to generate Dynamic web Component using a Servlet, we


have to do the following:
a) write the servlet source code(.java)
b) Compile the source code and copy the .class file of the servlet in the
classes’ directory.

Step 3:

Deployment Descriptor (web.xml)

According to specifications, for every Web Application, one (only one)


Deployment Descriptor is mandatory. That file name and extension together
should be web.xml only.

The need of web.xml in a Web Application is basically to declaratively


instruct the container what to do?

Inside the web.xml we do the following things:

1) Servlet registration with the Web Application


2) Authentication Configuration
3) Session timeout details
4) Listeners Configuration
5) Initialization parameters supplying
6) Filters Configuration
7) Servlets pre-initialization
8) Welcome files Configuration etc.

Web Application Deployment Steps:

Step 1:

Create the war file. War file is a special kind of jar file. According to
specification, every Web Application has to be packaged into a war file.

Currentworkingdir > jar –cvf greeting.war .

Step 2:

Start the Tomcat Server

Step 3:

Open the browser and type the following:

http://localhost:8080/manager/html

Upon that request, we get a web page (Tomcat Web Application Manager)

Step 4:

In the Tomcat Web Application Manager tool, we have to select the war file
to deploy. Specify the location of the war file and click on the deploy button.
Q) What are the functions of a servlet in general?

A) A servlet in general performs 3 things:

1. Evaluating the ServletRequest object for incoming form data

String value=request.getParameter (“name”);

2. Executing the Application logic

3. Generate the dynamic content and drive the output to the client

Q) How many names does a servlet have in a Web Application?

A) A servlet has three names in a web application

1. Registration/ alias/internal secret name


2. Servlet class name
3. Public url name

Q) Develop and deploy a Web Application in which when requested by


the Client, Server should give one form prompting the end user to enter
name. Upon entering name when end user click on the submit button,
Server should send the greeting message accordingly?

Step 1:

Creating the hierarchy of directories

GreetingApp
Greet.html
WEB-INF
classes
nit
servlets
GreetingServlet.class
web.xml
Step 2:

Defining the web resources

Greet.html

<html>
<body bgcolor=cyan>
<form action=”. /gotit”>
Name :< input type=”text” name=”t1”><br>
<input type=”submit”>
</form>
</body>
</html>

GreetingServlet.java

Package nit.servlets;

Import javax.servlet.*;

Public class GreetingServlet extends GenericServlet


{
Public void service(ServletRequest request,ServletResponse response)
throws ServletException,IOException
{
String name=request.getParameter(“t1”);
//evaluating the request object form data
String message=”WELCOME”+name+”TO OUR WEBSITE”;
//application logic
Response.setContentType(“text/html”);
PrintWriter out=response.getWriter();
Out.println(“<html>”);
Out.println(“<body bgcolor=wheat>”);
Out.println(“<h2>”+message+”</h2>”);
Out.println(“</body>”);
Out.println(“</html>”);
Out.close();

}//service()
}//GreetingServlet

Compilation

>javac –d . GreetingServlet.class

Step 3:

Writing the Deployment Descriptor

Web.xml

<web-app>
<servlet>
<servlet-name>Greet</servlet-name>
<servlet-class>nit.servlets.GreetingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Greet</servlet-name>
<url-pattern>/gotit</url-pattern>
</servlet-mapping>
</web-app>

Web Application Deployment

Root Directory

D:\GreetingApp>jar –cvf greetingapp.war .

Step 1: creation of war file


Step 2: start the server
Step 3: open the browser
http://localhost:8080/manager/html
Step 4: deploy the war file

Note: As an end user we should get the html form


http://localhost:8080/greetingapp/greet.html
Q) What happens in the background when the form is submitted to
Container (Server)?

A) As the part of html form, the action attribute value specifies the address
of the web component, to which the form request has to be submitted. In the
above example

<form action= “. /gotit” >

The value of the action attribute has got 2 parts:

Dot indicates the current Web Application from which this web-page is
retrieved i.e.

http://localhost:8080/greetingapp

The other part indicates the public name of the servlet. This name is
specified as <url-pattern>/gotit</url-pattern> in the web.xml. Therefore we
used that name in the action attribute.

Upon receiving the request, Http service (Web-Server) transfers (delegates)


the control to the servlet engine because the request involves end user’s
input and the address also is specified in the request. Servlet engine receives
the request and picks up the Web Application name from the request. Once
Web Application is matched with the existing installed Application, servlet
engine reads the web.xml to resolve the request. In the web.xml as we have
already specified the public URL name, the corresponding servlet is
assigned the duty of processing the client request.

Url-pattern gives public name to the servlet. This is mapped to alias name.

NOTE: War file is needed only by Tomcat server.

Q) How does the response generated by the servlet reach the Client?

A) Never ever, servlet directly sends the output to the Browser. The dynamic
content generated in the servlet i.e., given to the web server via servlet
engine. Web-server sends that dynamic content to the Browser.
Q) What is the significance of ServletRequest and ServletResponse
objects in the Client request processing by the Servlet?

A) Servlet captures the incoming client data and Http header information
through request object.

ServletResponse object provides methods to customize the output to be sent


to the client.

For example the type of content Multipurpose Internet Mail Extension


(MIME) is specified by using the response object.

response.setContentType (“file type/extension”);

Servlet is writing response header between the server and the request
sending browser. Stream object is created by using the response object only.

PrintWriter pw=response.getWriter ();


Passing initialization parameters to Servlet

Initialization parameters:
Name, value pair of strings supplied to the servlet from the descriptor
(web.xml) is called as initialization parameters.

Q) How to apply init parameters to the servlet?


A) In the web.xml, we make use of the following parameters:

<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>

Q) How does a servlet receives initialization parameters supplied from


web.xml?
A) Servlet engine reads the web.xml as soon as the Web Application is
installed. For a particular servlet, how many init programs are there, it
calculates and creates those many string objects. During servlet initialization
phase of the servlet it supplies them to the servlet via ServletConfig object.0
We have two important methods in the javax.servlet.ServletConfig interface
to retrieve the init params

String getInitParameter (String name) - this method takes the init param
name and returns the corresponding value.

Enumeration getInitParameters () - this method returns all names of the


init parameters as an enumeration of String objects.

Q) What are the uses of the init parameters?

They avoid hard coding and there by recompilation and redeployment of


servlets can be prevented whenever ceratin values are required to be
changed.
Basic idea of init parameters is that during the initialization phase itself, we
can provide some information to the servlet so that it can use that info during
its servicing phase.

<servlet>
<servlet-name></servlet-name>
<servlet-class></servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
</servlet>

Q) Develop and deploy a web application in which servlet should be able


to retrieve initialization parameters?

A) InitparamApp
emp.html
WEB-INF
classes
DatabaseServlet.class
lib
Classes12.jar
web.xml

http://localhost:8080/InitParamApp/emp.html

emp.html

<html>
<body>
<form action=”. /dbs”>
Id : <input type=text name=txtId><br>
Name: <input type=text name=txtName><br>
Salary<input type=text name=txtSalary><br>
<input type=”submit”>
<form>
</body>
</html>

web.xml

<web-app>
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>Database Servlet</servlet-class>
<init-param>
<param-name>d</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:server</param-value>
</init-param>
<init-param>
<param-name>user</param-name>
<param-value>scott</param-value>
</init-param>

<init-param>
<param-name>pwd</param-name>
<param-value>tiger</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>init</servlet-name>
<url-pattern>/dbs</url-pattern>
</servlet-mapping>
</web-app>

DatabaseServlet.java

import javax.servlet.*;
import java.io.*;
import java.sql.*;

public class DatabaseServlet extends GenericServlet


{
Connection con;
public void init (ServletConfig config) throws ServletException
{
String driver=config.getInitParameter (“d”);
String url=config.getInitParameter (“url);
String u= config.getInitParameter (“user”);
String p=config.getInitParameter (“pwd”);
try
{
Class.forName (driver);
con=DriverManager.getConnection (url, u, p);

}
catch (Exception e)
{
}
}
public void service (ServletRequest req, ServletResponse res) throws
ServletException, IOException {
try
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter();
pw.println ("<html>");
pw.println ("<body bgcolor=wheat>");
pw.println ("<center>");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from emp where
ename="+req.getParameter ("empno"));
ResultSetMetaData metadata=rs.getMetaData ();
int count=metadata.getColumnCount ();
if (rs.next ())
{
pw.println ("<h2>EMPLOYEE DETAILS</h2>");
pw.println ("<table border=1 cellpadding=3 cellspacing=0>");
pw.println ("<tr>");
for (int i=1;i<=count;i++)
pw.println ("<th align=right width=100>"+metadata.getColumnName (i)
+"</th>");
pw.println("</tr>");
pw.println ("<tr>");
for (int i=1; i<count; i++)
pw.println ("<td align=right width=100>"+rs.getString (i)+"</td>");
pw.println ("</tr>");
pw.println ("</table>");
}
else
pw.println ("<h3>Employee record not found</h3>");
pw.println ("</center>");
pw.println ("</body>");
pw.println ("</html>");
pw.close ();
}//try
catch (Exception e)
{
System.out.println ("Some Exception");
System.out.println (e);
}
}//service ()

Public void destroy ()


{
try
{
if (con! =null)
con.close ();
}
catch (Exception ex)
{
}
}
}
}
Note:

War file creation is not mandatory for tomcat Server


In such case copy our own web application root directory into
D:\tomcat\webapps. Then we start the Server. Container installs the
application. This is known as Cold Deployment.

As far as classes12/classes111 files are concerned we can copy one of them


in d:\tomcat\common\lib. Once we do this for every web application Oracle
Driver is available. Therefore we need to create lib directory in every web
application.

Java.sql.ResultSetMetaData interface:

ResultSet interface provides methods to retrieve data from the table of


records. But it does not provide ant data about that data i.e., it does not
provide any methods to deal with column names, their number, size, etc.

ResultSetMetaData encapsulates the information about the columns. We get


the reference to this object as follows:

ResultSetMetaData rsmd=rs.getMetaData ();


Calling a Stored Procedure from a java program:

Stored Procedure:

It is a database object that encapsulates business logic in the database server.


We can think of Stored Procedure as a java method.

From a java program, in order to call a Stored Procedure, we make use of


java.sql.CallableStatement interface which is a sub-interface of
PreparedStatement.
Making use of CallableStatement to call a Stored Procedure involves the
following steps:

Requesting for the Connection

Prepare the special syntax known as Escape Syntax

Building the CallableStatement object

Bind the in parameters, if any

Register the out parameters

Executing the call to the Stored Procedure

Retrieve the out parameters values

Close the CallableStatement

Close the Connection


1) Requesting for the connection:
Class.forName (“Driver Class”);
Connection con=DriverManager.getConnection (“url”,”user”,”pwd”);
2) Preparing the Escape Syntax:
In order to call a Stored Procedure, we need to create a
CallableStatement object. In order to create that object, we need to
prepare special SQL statement known as Escape syntax.
String str= “{call proc1 (?,?)}”;
3) Building the CallableStatement object:
To create the CallableStatement object, we make the following
method call on the connection object.
CallableStatement cst =con.prepareCall (String escape-syntax);
4) Binding the in parameters:
It is similar to PreaparedStatement process.
5) Registering the out parameters:
We should inform to the CallableStatement object about the out
parameters to be expected from the Stored Procedure so that while
extracting the values we can call appropriate getXXX() on that object.
All this is done by calling registerOutParameter () on the
CallableStatement object.
Whenever a Stored Procedure definition involves out parameters or
in-out parameters, this step is mandatory.
6) Executing the call to the Stored Procedure:
CallableStatement object contains a call to the Stored Procedure. In
order to make a call to the Stored Procedure we should say
cst.execute ();
7) Retrieve the out parameters:
On the CallableStatement object we make a call to getXXX ()
methods basing upon the registered out parameters.
8) Closing the CallableStatement:
cst.close ();
9) Closing the Connection:
con.close ();
1) Example program on CallableStatement:

import java.sql.*;
class StoredProcedure
{
public static void main (String args[])
{
Connection con=null;
try
{
Class.forName ("oracle.jdbc.driver.OracleDriver");
System.out.println ("Driver Loaded. ...”);
String url="jdbc:oracle:thin:@90.0.0.4:1521:oracle";
con=DriverManager.getConnection (url,"scott","tiger");
System.out.println ("Connection Established.......");
CallableStatement cst=con.prepareCall ("{call proc2 (?,?)}");
cst.registerOutParameter (2, Types.VARCHAR);
cst.setInt (1, 1001);
cst.execute ();
String str=cst.getString (2);
System.out.println ("Employee Name:"+str);
cst.close ();
}
catch (ClassNotFoundException cfe)
{
System.out.println ("Driver class not found");
System.out.println (cfe);
}
catch (SQLException e)
{
System.out.println ("SQL"+e);
}
finally
{
try
{
if (con!=null)
{
con.close ();
}
}//try
catch (SQLException e)
{
System.out.println ("SQL final"+e);
}
}//finally
}//main ()
}//end of class

SQL Statements needed for Example 1 Program:


create table emp10 (id number, name varchar(12));
insert into emp10 (1001,'adil');
create or replace procedure proc2 (n number, nm out varchar)
as
begin
select name into nm from emp10 where id=n;
end proc2;
/

2) Example program on CallableStatement:

import java.sql.*;
class StoredProcedureSample
{
public static void main (String args [])
{
try
{
int accno=Integer.parseInt (args[0]);
Class.forName ("oracle.jdbc.driver.OracleDriver");
System.out.println ("Driver Loaded....");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@90.0.0.4:1521:oracle","scott","tiger");
System.out.println ("Connection Established.....");
CallableStatement cst=con.prepareCall ("{call addinterest(?,?}");
System.out.println ("Callable Statement created....");
cst.registerOutParameter (2, Types.FLOAT);
cst.setInt (1, accno);
cst.execute ();
System.out.println ("Stored procedure executed....");
System.out.println ("New Balance of A/c "+ accno+"is:
Rs."+cst.getFloat (2));
cst.close ();
con.close ();

}
catch (ArrayIndexOutOfBoundsException aie)
{
System.out.println ("Supply Account number please");
System.out.println ("USAGE: java StoredProcedureSample 1001");
}
catch (Exception e)
{
System.out.println (e);
}
}//main ()
}//class

SQL Statements needed for Example 2 Program:

create table account (id number (4), balance number (7,2));

insert into account values (1001, 5000);

create or replace procedure addinterest (id in number, bal out number)


as
begin
select balance into bal from account where is=id;
bal:=bal+bal*0.5;
update account set balance =bal where id=id;
end;
/
Q) What is the Servlet init () code that retrieves all the initialization
parameters and their corresponding values?

A) Enumeration params=config.getInitParameterNames ();


While (params.hasMorElements ())
{
String pname= (String) params.nextElement ();
String pvalue=config.getInitparameters (pname);
System.out.println (pname+”:”+pvalue);
}

Q) What is wrong with the following code?

public void init (ServletConfig config) throws ServletException


{
String driver=getInitParameter (“driver”);
}

A) We are calling getInitParameter () method on the Servlet instance. It


should have been called on config instance.
Even then, compiler does not report an error. However, once the Servlet is
deployed, we get the NullPointerException.

Q) How many interfaces GenericServlet implements?

A) GenericServlet implements 3 interfaces:

java.io.Serializable
java.servlet.Servlet
javax.servlet.ServletConfig

 GenericServlet implements Servlet interface to follow the


specification
 It is implementing Serialization interface to become persistent, if
required
 It implements for the sake of programmers conveniences.

i.e., whatever methods ServletConfig object possess all those methods can
directly be called on the Servlet interface.
Serializable Servlet ServletConfig

GenericServlet

Our Servlet

Q) What is the problem with the following code?

Public class A extends GenericServlet


{
Public void init (ServletConfig config) throws ServletException
{
}
Public void service (ServletRequest request, ServletResponse
response) throws ServletException, IOException
{
String value=getInitParameters (“d”);
}
}

A)
a) Compile time error
b) No error at compilation
c) Runtime error
d) No runtime error

The above code generates null pointer exception


Q) What is the Default implementation of GenericServlet?
A) public abstract GenericServlet implements
Servlet,Serializable,ServletConfig
{
ServletConfig _config;
public void init () throws ServletException
{
}
public void init (ServletConfig config) throws ServletException
{
_config=config;
init ();
}
…………
…………
…………
public String getInitParameter (String name)
{
returns _config.getInitParameters (name);
}
…………
…………
…………
}
GenericServlet class provides 2 init methods to the child classes.
1. Dummy implementation in the zero argument init () method.
2. In parameterized init() method, it does 2 things :
1) Storing the Container provided ServletConfig object
globally within the class
2) Making a call to zero argument init () method.

GenericServlet provides implementation for all the methods of


ServletConfig interface. This is done to facilitate the programmers to call
any ServletConfig method directly on the Servlet instance without the need
of ServletConfig object.

Zero argument init () is not life cycle method.


Parameterized init () is part of life cycle method which the Container calls.
javax.servlet.ServletContext

Container creates the object of some class that implements ServletContext


interface at the time of our Web Application installation. The reference of
this object is encapsulated in the ServletConfig object. Therefore if we want
to get the reference of ServletContext, we have to call getServletContext ()
on the ServletConfig object. ServletContext object represents the Web
Application Environment i.e., ServletContext is an abstraction of the Web
Application itself.

A servlet can view the Web Application and its contents via ServletContext
object. Servlet can communicate with the Container via ServletContext
object. ServletContext objects is only one per Web Application, where as
ServletConfig object is one per Servlet.

ServletContext object acts as Global Memory Area (Shared Information


Repository) for all the Servlets and Jsps of the Web Application.
Application Level State is stored in the ServletContext object. One servlet
can store data in this object and other servlet can share that information.

ServletContext interface provides the following methods:

1) Methods to deal with Application Level State:

I. set Attribute(String name, Object value)


II. Object get Attribute(String name)
III. removeAttribute (String name)
IV. String getInitParameter (String name)
V. Enumeration getInitParameterNames ()

2) Methods to communicate with the environment:

I. String getServerInfo ()
II. Log (String information)
III. RequestDisaptcher getRequestDispatcher (String path)
Q) Web Application on ServletContext?

A)

ServletContextApp
Data.html
WEB-INF
Web.xml
Classes
StorageServlet.class
RetrieveServlet.class

http://localhost:8080/ServletContextApp/data.html

//data.html

<html>
<body bgcolor=pink>
<center>
<h1>PERSONAL DETAILS</h1>
<form action=”./store”>
EMAIL ID<input type=text name= “email”><br>
PHONE<input type=text name=”phone”><br><br>
<input type=submit value=SUBMITDETAILS>
</form>
</center>
</body>
</html>

//web.xml

<web-app>
<context-param>
<param-name>admin</param-name>
<param-value>adil@pinnacleblue.com</param-value>
</context-param>
<servlet>
<servlet-name>storage</servlet-name>
<servlet-class>StorageServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>retrieval</servlet-name>
<servlet-class>RetrieveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>storage</servlet-name>
<url-pattern>/store</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>retrieval</servlet-name>
<url-pattern>/retrieve</url-pattern>
</servlet-mapping>
</web-app>

//StorageServlet.java

import javax.servlet.*;
import java.io.*;
public class StorageServlet extends GenericServlet
{
public void service (ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
String email=request.getParameter ("email");
String phone=request.getParameter ("phone");
response.setContentType ("text/html"):
PrintWriter pw=response.getWriter ();
ServletContext sc=getServletContext ();
sc.setAttribute ("mail”, email);
sc.setAttribute ("telephone”, phone);
String adminmail=sc.getInitParameter ("admin");
pw.println ("<html>");
pw.println ("<body bgcolor=wheat>");
pw.println ("<h3>Web site admin available at "+adminmail+"</h3>");
pw.println ("<h2><a href=./retrieve>GET YOUR DETAILS HERE</h2>
pw.println ("</body>");
pw.println ("</html>");
pw.close ();
}
}

//RetrieveServlet.java

import javax.servlet.*;
import java.io.*;
public class RetrieveServlet extends GenericServlet
{
public void service (ServletRequest request, ServletResponse response)
throws

IOException, ServletException
{
response.setContentType ("text/html"):
PrintWriter pw=response.getWriter ();
ServletContext sc=getServletContext();
String mail=(String)sc.getAttribute("mail");
String phone=(String)sc.getAttribute("telephone");
String adminmail=sc.getInitParameter ("admin");
pw.println ("<html>");
pw.println ("<body bgcolor=cyan>");
pw.println ("<h2>YOUR PERSONAL DETAILS</h2>");
pw.println ("<h3>EMAIL ID:"+mail+"</h3>");
pw.println ("<h3>TELEPHONE#:"+phone+"</h3>");
pw.println ("<h3>Web site admin available at "+adminmail+"</h3>");
pw.println ("</body>");
pw.println ("</html>");
pw.close ();
}
}
HttpServlet Basics:

Web Client and Web Server communicate with each other by using protocol.
Therefore they are known as Http Client and Http Server respectively.

HttpRequest

Http Client Http Server

HttpResponse

Depending upon the way the request is made by the Client to the Server, the
request is famously categorized into 2 areas known as HttpRequest methods.

We have 2 important Request methods:


1. GET method
2. POST method
Both are HttpRequest methods from Bowser to Server.

Q) Differences between GET and POST methods?


A)

GET
POST

It is default method
We need to explicitly specify it
This request can be made either
by typing the url directly or by Only with html form this
clicking on hyperlink or through request is possible.
a form
Primary purpose of this method It is basically meant for posting data
is to get data from the server. into the server for updations.
Therefore it should not be used for
data updations.
Request headers have no body. Any It has body. Data is not appended to
data should be associated to request the url
line in the form of query string
Sensitive information like password We can send
and credit card information should
not e sent through this method.
Amount of data transfer from client No limitations
to server is limited.
It is idempotent(no side effects) It is not idempotent(side effects can
raise as we update the database)

Side Effects:
If due to network delay, we are typing/clicking the same button again and
again then the data can have effect repetitively

Q) How to write (create) a form that makes get request/ post request?
A) <form action= “ “ method = “post”
If we don’t specify the method attribute in the html form tag, by default it is
get request method only.

Q) What is the basic functionality of a Servlet?


A) To extend the functionality of a web server.
GenericServlet is not http protocol specific. Therefore by using
GenericServlet we cannot provide the functionality to the http server.
For example, session tracking, http request headers reading etc.
Therefore we make use of javax.Servlet.http.Httpservlet class.

Servlet

GenericServlet

HttpServlet

Our Servlet
Life cycle of HttpServlet

Javax.servlet.http.HttpServlet class extends GenericServlet. As


GenericServlet implements Servlet interface. HttpServlet also become
eligible to act as a Servlet.

HttpServlet provides http specific behoviour to our own servlet. That is the
reason why our servlet can provide complete support for the Web
Server(HttpServer)

When we are discussing HttpServlet life cycle means we are discussing our
own servlet that extends HttpServlet.
HttpServlet Life Cycle:

Loading of Servlet Class

Servlet instance creation

ServletConfig object creation

init () method calling

ServletRequest, ServletResponse object creation

Public service method calling

Calls the protected service (req, res)

Call doGet(),DoPost() methods

If
More administrator
request undeploys
? Servlet

Call destroy () method


Public service method calling

HttpServlet class provides default implementation for the abstract service


method of the GenericServlet. In this method implementation only http
specificness starts. The following is the implementation.

Public void service(ServletRequest request,ServletResponse response)


throws ServletException,IOException
{
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) response;
Service(req,res);
}

Calls the protected service (req, res)

In the public service method a call is made for the protected service ()
method.
Converting ServletRequest and ServletResponse to HttpServletRequest and
HttpServletResponse
Calls its own protected service(httpServletRequest req,HttpServletResponse
res) methods belongs to HttpServlet class only.
HttpServlet class has given following default implementation for the
protected service method:
Protected void service(HttpServletRequest req,HttpServletresponse res)
throws ServletException,IOException
{
String requestmethod=req.getmethod()
If(requestmethod.equals(“GET”))
doGet(req,res);
If(requestmethod.equals(“POST”);
doPost(req,res);
}

Call doGet() doPost() methods

Depending upon the incoming http request method from the Browser, either
doGet() or doPost() method is called.
The following is the default implementation for these methods given by the
HttpServlet
Protected void doGet(HttpServletRequest request,HttpServletResponse
response) throws ServletException,IOException
{
PrintWriter pw=response.getWriter();
Pw.println(“GET REQUEST ISW NOT SUPPORTED”);
Pw.close();
}
Protected void doPost(HttpServletRequest request,HttpServletResponse
response) throws ServletException,IOException
{
PrintWriter pw=response.getWriter();
Pw.println(“POST REQUEST ISW NOT SUPPORTED”);
Pw.close();
}

Q) public class OurClass extends HttpServlet


{
}
OurClass has how many implemented methods approximately? Name
them.

The following methods are inherited from HttpServlet by OurClass

Init()
Init(ServletConfig config)
Public void service(ServletRequest req,ServletResponse res)
Protected void service(HttpServletRequest req,HttpServletResponse res)
Calls 2 more service methods-doGet() and dpPost() depending on the
evaluating the request object call doGet/doPost

Protected void doGet(HttpServletRequest res,HttpServletResponse res)


ServletConfig interface methods as GenericServlet implements this

getInitparameters
getServletNames
getServlet

other 3 methods of Servlet interface i.e. destroy()


From now onwards whenever we write a Servlet class, we extend only
HttpServlet and override doGet() or doPost() or both.

Web Application on HttpServlet implementation

LoginApp
login.html
WEB-INF
web.xml
classes
LoginServlet.class

http://localhost:8080/LoginApp/login.html

login.html

<html>
<body bgcolor="pink">
<center><h2>LOGIN TO WEB APPLICATION</h2>
<form action=". /login" method="post">
USER NAME : <input type="text" name ="user"><br>
PASSWORD : <input type="password" name="pwd"><br><br>
<input type="submit" value="CLICK HERE">
</form>
</center>
</body>
</html>

web.xml

<web-app>
<servlet>
<servlet-name>authenticate</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>authenticate</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
LoginServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class LoginServlet extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String user=request.getParameter ("user");
String pwd=request.getParameter ("pwd");
response.setContentType ("text/html");
PrintWriter pw=response.getWriter ();
if (user. equals (pwd))
{
pw.println ("<html>");
pw.println ("<body bgcolor=cyan>");
pw.println ("<h2>Welcome to our Shopping Mall</h2>");
pw.println ("</body>");
pw.println ("</html>");
}
else
{
pw.println ("<html>");
pw.println ("<body bgcolor=pink>");
pw.println ("<h3>Invalid user name</h3>");
pw.println ("<a href=login.html>TRY AGAIN</a>");
pw.println ("</body>");
pw.println ("</html>");
}
pw.close ();
}
}
Web Application on RequestDispatch

Directory Structure

RequestDispatch
emp.html
caption.html (to use it in second servlet)
WEB-INF
web.xml
classes
GrossServlet.java
NetServlet.java

http://localhost:8080/RequestDispatch/emp.html

emp.html

<html>
<body bgcolor=”wheat”>
<center>
<form action=”. /gross”>
Employee Basic <Input type=text name=”basic”> <br>
<input type=”submit”>
</form>
</center>
</body>
</html>

caption.html

<html>
<body bgcolor=”cyan”>
<marquee>
<font size=6 color=green>
Welcome to HR systems
</font>
</marquee>
</body>
</html>
GrossServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class GrossServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response ) throws

IOException, ServletException {
String b= request.getParameter("basic");
float basic = Float.parseFloat(b);
float da=0.5f*basic;
float hra=0.4f*basic;
float gross = basic+hra+da;
Float f= new Float (gross);
request.setAttribute("gross", f);
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/net");
rd.forward(request, response);
}
}
NetServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class NetServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response ) throws

IOException, ServletException {
Float gross=(Float) request.getAttribute("gross");
float net = gross.floatValue() - 500;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
getServletContext().getRequestDispatcher("/caption.html").include(request,r
esponse);
out.println("<html>");
out.println("<body bgclor=wheat>");
out.println("<h3> Employee net salary is : " + net +"</h3>");
out.println("</body");
out.println("</html>");
out.close();
}
}
web.xml

<web-app>
<servlet>
<servlet-name>source</servlet-name>
<servlet-class>GrossServlet</servlet-class>
</servlet>

<servlet>
<servlet-name>target</servlet-name>
<servlet-class>NetServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>source</servlet-name>
<url-pattern>/gross</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>target</servlet-name>
<url-pattern>/net</url-pattern>
</servlet-mapping>

</web-app>

Also do: -
Convert this to include mechanism in source.
Use include instead of forward method in source.
Filters

A Filter is a Container Managed Object that acts as interceptor between the


Client and the Web Component in the request-response cycle.

A Filter is not a Web Resource by itself i.e., Client never addresses the
request to the Filter. For that matter, Client does not know that Filter exists.
Similarly Web Component (Servlet/ jsp) also does not know that a Filter
exists.

Any request before reaching the Servlet is passed through Filter object.
Similarly any response coming from the Servlet passes through the Filter
before it is delivered to the Client.

Req Req Req

S
E
R
V
L
E
T
Res Res Res
Filter 1 Filter 2

Client Servlet Container

A Filter can do any of the following things:

 After receiving the request on its own can give the response back to
the Client without forwarding the request to the Servlet.

 After receiving the request it can forward the request to the Servlet for
processing

 It can redirect the request to other Web Component.


Development and Deployment of Filter in a Web Application:

Any java class that implements javax.servlet.Filter interface can be a Filter


class.
This interface provides three life cycle methods:
1. init (FilterConfig)
2. doFilter (ServletRequest, ServletResponse, FilterChain)
3. destroy()

A Filter has life cycle similar to the Servlet life cycle. Servlet Container
creates the instance of our own developed Filter class at the time of Web
Application installation.

Servlet Engine creates the FilterConfig instance. Container calls the init ()
method on the Filter instance by supplying the config object. FilterConfig
instance is capable of retrieving init parameters and context information
(similar to the ServletConfig)

A Filter servicing phase is nothing but performing filtering. Container calls


doFilter () method whenever the request comes from the Client to that Web
Component (Servlet/jsp) to which this Filter is associated.
Container creates 3 instances - request, response and Filter Chain and these
objects are passed to the filter via doFilter () method.

FilterChain object is used by the Filter to continue filtering or passing the


request to the Web Component.

Deployment of a Filter

Deployment of a filter into a Web Application is a 2 step process


Copying the Filter class file into the classes directory
Registering the Filter with the Web Application in the web.xml and perform
mappings with the required web resource to which we want to apply the
Filter.
Web Application on the implementation of Filter that is associated to a
Servlet:

FilterApp
login.html
relogin.html
WEB-INF
classes
WelcomeServlet.class
AuthenticateFilter.class
web.xml

http://localhost:8080/FilterApp/login.html

Note:
Filter should be registered before Servlet.

web.xml

<web-app>

<filter>
<filter-name>authenticate</filter-name>
<filter-class>AuthenticateFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>authenticate</filter-name>
<url-pattern>/login</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

</web-app>

login.html

<html>
<body bgcolor=cyan>
<center>
<form action=". /login" method=POST>
User Name : <input type=text name="user">
<br> Password : <input type=password name="pwd"><br>
<input type=submit value="login here">
</form>
</center>
</body>
</html>

relogin.html

<html>
<body bgcolor=cyan>
<center>
<h2>INVALID USER OR PASSWORD</h2>
<form action="./login" method=POST>
User Name : <input type=text name="user">
<br> Password : <input type=password name="pwd"><br>
<input type=submit value="login here">
</form>
</center>
</body>
</html>

AuthenticateFilter.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class AuthenticateFilter implements Filter
{
FilterConfig fc;
public void init (FilterConfig config) throws ServletException
{
fc=config;
System.out.println("Filter is instantiated and initialized");

}//init()
public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException
{
String user=request.getParameter ("user");
String pwd=request.getParameter ("pwd");
if (user. equals (pwd))
chain.doFilter (request, response);//forward to Servlet
else
{
response.setContentType ("text/html");
ServletContext sc=fc.getServletContext ();
RequestDispatcher rd=sc.getRequestDispatcher ("/relogin.html");
rd.forward (request, response);
}//Filter sending response to client
}//doFilter
public void destroy ()
{
fc=null;
}
}

WelcomeServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class WelcomeServlet extends HttpServlet


{
public void doPost (HttpServletRequest request, HttpServletresponse
response) throws ServletException.IOException
{
response.setContentType ("text/html");
PrintWriter out=response.getWriter ();
out.println ("<html>");
out.println ("<body bgcolor=cyan>");
out.println ("<h2>WELCOME TO THIS SITE</h2>");
out.println ("</body>");
out.println ("</html>");
out.close ();
}
}

Q) How does a filter work?


A)  When ever a request comes to a particular web resource servlet engine
pickup the URP pattern and searches for the filter association with the URL
patern. If the filters are found for that servlet inside of routing the request to
the servlet it routs to the filter.
 
Q) How to supply initialization parameters to t a filter?
A)   In the web.xml we make the following entries to initialization
parameters:-
<filter>
            <filter-name>      </filter-name>
            <filter-class>                </filter-class>
 
            <init-param>
            <param-name>             </param-name>
            <param-value> </param-value>
            </initparam>
 
            <init-param>
            <param-name>             </param-name>
            <param-value> </param-value>
            </initparam>
 
</filter>
 
Q) How does a filter receive initialization parameters?
 
A)      public void init(FilterConfig congig)
{
String driver = config.getInitParameter(“d”);
String URL= config.getInitParameter(‘url”;
---
---
---
}
 
Q) What is chaining of Filter? How to implement it?
A) Associating more than one Filter to a Servlet is known as Filter Chaining.
To implement Filter Chaining we need not program anything, either in the
Filter class or in the Servlet class.
In the web.xml we make following entries:

<filter>
<filter-name>x </filter-name>
<filter-class> </filter-class>
</filter>
<filter>
<filter-name>y</filter-name>
<filter-class> </filter-class>
</filter>
<filter-mapping>
<filter-name>x</filter-name>
<servlet-name>registration name of servlet</servlet-name>
[Can also give url-pattern]
</filter-mapping>
<filter-mapping>
<filter-name>y</filter-name>
<servlet-name>registration name of servlet</servlet-name>
[Can also give url-pattern]
</filter-mapping>
Java Server Pages

 JSP is a specification.
 A JSP page is a Web Component.
 It is as active Web Resource in a Web Application
 A jsp serves the Web-Client
 A jsp produces the dynamic Web-Context.
 A jsp is meant for extending the functionality of Web-Server.
 A jsp contains html plus java code.

Disadvantages of Servlets:

Servlets are excellent in the execution of application logic and there by


generating the dynamic content. But they are very poor in context
presentation.
Context generation logic and presentation logic is tightly coupled. As a
result of such tight coupling, we encounter the following problems:
 Tools cannot be used effectively for web page creation nor for servlet
java code.
 Development and maintenance problems arise for the website.

Advantages of jsp:

Almost all the disadvantages of servlets are addressed in this server side
technology.

Key points about jsp programming:

 Jsp is not a replacement for servlets but it is only an extension.


 A jsp cannot serve a client on its own. Web Container converts the jsp
into a servlet in the background and that Container generated servlet
only can serve the client request.
 We author a jsp.
 Writing/authoring a jsp page is other way of writing a servlet. Instead
of us writing the servlet, we are instructing the container to write a
servlet for us.
 Generally saying, a servlet is nothing but writing html code inside
java code whereas a simple jsp is nothing but writing java code
inside html code.
 A Web Container that has servlet engine, jsp engine and http service
can host jsps and serve client requests.

Life Cycle of JSP


Life cycle of JSP is developed in 6 phases and 3 life cycle methods. Life
cycle phases are:

 Translation phase
 Compilation phase
 Instantiation phase
 Initialization phase
 Servicing phase
 Destruction phase

Life cycle methods are:

 jsp_Init ()
 _jspService ()
 jspDestroy ()

Whenever client is making a request to the jsp file, jsp engine performs two
things:

1) Translating jsp into .java file. This is the source code of


container-generated servlet.
2) Compiling the servlet source code into .class file.

Translation Compilation

First.jsp First_jsp.java First_jsp.class

Once container generated .class file is created, jsp engine role ends.
After translation and compilation phases servlet engine takes the control and
the other 4 phases are similar to normal servlet life cycle.
Tabular representation of jsp Life Cycle:

Case/context Request# Transla Compilat Instanti Initializa Servicing


tion ion ation tion
Jsp first R1     
authored R2 * * * * 
Container R1 * *   
restarted R2 * * * * 
Jsp modified R1     
R2 * * * * 

Constituents of a jsp declaration


html
(template scripting expression
text) element
scriptlet
Constituents
Of jsp tags include
jsp (elements) include
forward
directives page
length param
standard plugin
java
actions useBean

setProperty

custom getProperty
1) Scripting elements:

According to JSP specification we have 3 kinds of scripting elements. They


are known as scripting elements because inside the jsp, embedding of java
code is possible through them.

I. Declaration:

Anything enclosed between


<%! and %> is a declaration according to JSP specifications.
Inside a declaration we can write any valid java variable
declaration/definition and method definition

For example:

<%! int a; //variable declaration


int b=10; //variable definition
void x ()
{
}//method declaration
%>

Whatever we write inside declaration becomes a direct member of the


Container generated servlet class.

int a; instance variable

static int b=10; class variable

class c inner class


{
}

void x () instance method


{
}

In a declaration if a variable is initialized that initialization happens only in


the first request to this jsp.
In the subsequent request to the jsp, initialization does not happen again.

II. Expression:

Anything enclosed between <%= %> is an expression. Expression acts as


place holders for java expression

An expression is evaluated every time the request comes to jsp


When the expression is executed two things happen in the background:

1. Java expression is evaluated


2. The request of the evaluation is written to the output stream of jsp.

Note:

Inside the jsp expression, java expression statement should not end with
a semicolon [;]

For example:
<% = a+b %>

Ex: code on declaration and expression

<%! String names [] = {“adil”,”baber”,”mohammad”};


String getNames (int index)
{
Return names [index]
}
%>
<%= getName (1) %>

III. Scriptlet:

Anything that starts with <% and ends with %> is a scriptlet according to
JSP specification.

Inside a scriptlet we can write *free form of java code.

*free form means any logic but no class or method declarations.


In a jsp we can have any number of scriptlets.

A scriptlet is inserted into _jspService of the container generated servlet.

Ex:
<% for (int i=0;i<0;i++)
System.out.println (“hello”);
Int a=10;
%>

We can declare variables. We cannot declare functions as this goes into


service method. Therefore function within function is not acceptable hence
do not write method in scriptlet.

Comments in a jsp:

When we author a jsp, we can have 3 kinds of comments:

i. Java comments: Inside declaration, scriptlet but not in the


expression.
//, /* */
ii. Html comments:
<! - -html comments - ->
are ignored by jsp engine.

When jsp o/p is sent to the browser and when we view the source from view
menu, we can’t see the jsp comments but can see html comments.
Jsp comments can’t be sent to the browser. Wherever jsp comments are
declared, we can declare the html comments.

Implicit objects in jsp:

As the container converts jsp to servlet it declares and initializes 9 objects to


get the request, response, config, context objects, etc. to get the values from
form elements.

In the _jspService () method of the container generated servlets, 9 non


primitive variables are locally declared and initialized.
Non primitive variables means references declared. If references are
initialized then they become objects.

These nine objects are by default available to every jsp*.

(*conditions apply)

Q) Can we write here?

<%! void x ()
{
request.getParameter (“hello”);
}
%>

A) No we can’t as the implicit objects are valuable in expression and


scriptlet.

Inservlet class
{
Void x ()
{
request.getParameter (“-“);
}
_jspService()
{
}
}
}

As declaration falls under the part of initialization but expression and


scriptlet falls under the part of _jspService () method where we have 9
implicit objects hence can’t use the statement in declarations.

These objects are known as implicit Objects in a jsp, implicit objects are
available only for expressions and scriptlets but not for declarations.
9 implicit objects (case sensitive):

1. out: It is the output stream for the jsp. This object is of type
javax.servlet.jsp.JspWriter class

<% out.println (“Hello world”); %>

But it is not available as normal text can be included in html only. If any
information calculated by servlet and given back to browser in that case we
can use this statement.

<%! Void x ()
{
Print (“hai”);
}
%>

2. request: This is of type HttpSrvletRequest for accessing the client data.

3. response: This is of type HttpServletResponse

4. application: javax.servlet.ServletContext

ServletContext is a global area to Web Application.

Q) How a jsp can retrieve data from ServletContext?

Use <% application.setAttribute %>


It is directly available in jsp but in Servlets we need to create an object using
getServletContext () method.

5. config: javax.servlet.ServletConfig

config.getInitParameter (-----);

getServletConfig () method is used in servlet to create but this object is


directly available in jsp.

6. session: javax.servlet.httpSession
request.getSession () in servlet to get session but in jsp it is directly
available.

7. page: refers to the current servlet instance. This is of type


java.lang.Object

Just like this. refers to current object, a present servlet instance can be
referred as page.

8. exception: This is of type java.lang.Throwable

This is available only to those jsp which possibly error thrown while act as
error pages. All jsp will not get this object (*conditions apply policy come
here).

This object is not available to every jsp. Those jsp which act as error
handling pages can get this implicit object.

9. pageContext: This is of type javax.servlet.jsp.pageContext class.


It represents entire jsp page environment.
Web Application using jsp pages:

WelcomeJspApp
welcome.jsp
WEB-INF
web.xml
classes

http://localhost:8080/WelcomeJspApp/welcome.jsp

web.xml

<web-app>
</web-app>

welcome.jsp

<html>
<body bgcolor=cyan>
<h2>First JSP Example</h2>
<%
out.println ("welcome to jsp");
%>
</body>
</html>

Jsps are placed in the public area of the root directory of the Web
Application.
Never ever jsp is sent to the client. Jsp is the server side component. The
output (html) generated by the jsp is sent to the client.

Tomcat5.0/work -> go on clicking if you will find welcomeJspApp in that


you will find container generated servlet.
Example Web Application to explore the declarations and expressions
of a jsp

SecondJspApp
two.jsp
WEB-INF
web.xml
classes

http://localhost:8080/SecondJspApp/two.jsp

two.jsp

<html>
<body bgcolor = wheat>
<%! int count=0;
String names [] = {"adil","baber"};
private String getName (int index)
{
return names [index];
}
%>
<h2>Number of times this page visited <%= ++count %> </h2>
<h3>The user is <%= getName (1) %>< /h3>
</body>
</html>

Whatever variables, arrays, and methods we define in a jsp, they become


direct members of the Container generated servlet class. Variable
initialization occurs only once.

Expression of the jsp is inserted in the service method of the Container


generated servlet in the given order. They are evaluated and their output is
sent to the client every time the page is requested.
Application on scriptlet, expression and implicit variable (object)

third.jsp:

<html>
<body bgcolor = wheat>
<h2>DATE AND TIME <%= new java.util.Date () %> </h2>
<h2>SERVER DETAILS : <%= application.getServerInfo () %>< /h2>
<% for (int i=1; i<=5; i++)
{
%>
<h2> WELCOME TO JSP</h2>
<%
}
%>
</body>
</html>

Web Application in which a jsp captures the form data, generates the
dynamic web content and sends the output to the Client

GreetingApp
user.html
greet.jsp
WEB-INF
web.xml
classes

http://localhost:8080/greetingApp/user.html

user.html

<html>
<body bgcolor=yellow>
<form action="./greet.jsp">
User : <input type=text name=t><br>
<input type=submit>
</body>
</html>

greet.jsp

<html>
<body bgcolor=wheat>
<h2>hello <%= request.getParameter ("t") %>< /h2>
</body>
</html>
USING JAVA BEANS IN A JSP

Java Bean: A java bean is a specialized java class with some standard
naming conventions.
A normal java class becomes a bean class if we define the class according to
java bean specifications.

The following are the rules:

1. Class must be public.


2. Class should have public default constructor.
3. Properties of the class must be private.
4. Each property of the class should have public setXXX () and getXXX
() methods.
5. The class has to implement java.io.Serializable interface.

Example java bean:

public class Employee implements java.io.Serializable


{
private int empno;
private String name;
private float salary;
public void setEmpno(int empno)
{
this.empno=empno;
}
public int getEmpno ()
{
return empno;
}
public void setName(String nm)
{
this.name=nm;
}
public int getEmpno ()
{
return name;
}
public void setSalary(float salary)
{
this.salary=salary;
}
public float getSalary()
{
return salary;
}
}//bean class

Note:
Java beans make use of Servlet or jsp. On its own the beans will not execute.

Important points for a java bean:

A java bean is used in a Web Application by the Web Components.


A java bean acts as a model (data holding and data accessing entity) in a
Web Application that is developed using MVC architecture.
Model-Java beans
View-jsp
Controller-Servlet
In a medium range to large (not very large) range Web Applications, MVC
architecture is mandatory and java bean usage is inevitable.
In a Web Application, if we are using java beans, it is mandatory that bean
class must be under user defined package.
A java bean when used in a jsp or in a Servlet, bean instantiation fails if user
defined package is not defined.
While defining a bean class, for each bean field we write one setter method
and one getter method.
Setter method is meant for populating the beans instance (giving values to
the variables) getter method is to get the state of the bean.
A java bean is instantiated and populated by servlets or jsp.
When we make use of java bean in a jsp, container takes care of bean
instantiation populating it and getting the bean sate.
We instruct the container to do so through jsp tags (useBean, setProperty,
getProperty).
In a Web Application, a bean represents a record in a database.
A bean is populated in two ways
A Servlet or jsp does it with form data.
Bean should contact the database and populate itself.
Java Beans

Limiting or eliminating java code form jsp:

A jsp contains java and html. We need to limit the java from directly in jsp
and send it to indirectly at background.

A jsp contains template text for presentation and direct java code to provide
dynamism for the page. There are some draw backs in this approach:

 Tools cannot be used for java code development


 Error handling and testing is not convenient
 Code re-usability is not possible.

To minimize or totally eliminate java code from the foreground of the jsp we
have many approaches:

 Normal java class encapsulating the application logic.


 Java bean
 Custom actions
 Expression language

First approach:

MyApp
Html
Jsp
WEB-INF
Classes
Xyz.class- write application logic here
Second approach

Using a java bean in a jsp:


In a jsp if we make use of a java bean in place of a normal java class, we
will have the following benefits:

 We can eliminate java code completely from the jsp


 Data sharing across jsps is more flexible
 Excellent synchronization between bean fields and html form fields.

Whenever we want to deal with a java bean in a jsp we make use of 3


standard actions.

1) useBean
2) setProperty
3) getProperty

1) useBean:

It is used to create a java bean instance or to retrieve the existing bean


instance. This standard action is in the following form:

<jsp: useBean id=”ref” class=”beanpack.BeanClass” />

The above instruction when received by the jsp engine, 2 things happen:

I. Bean class instance is created and it is bound to the reference referred by


the attribute ‘id’.
II. The bean class instance is stored in pageContext object.

2) setProperty:

This is a standard (pre defined by the specification) instruction given by the


jsp author to the jsp engine to populate the bean instance. This is of the
following form:

<jsp: setProperty name=”ref” property=”beanproperty” value=”anyvalue” />

Once this instruction is received by the jsp engine a particular property of


the bean instance with the specified name is populated with the given value.
Note:
In place of value we can mutually exclusively (either of them but not both)
use param attribute.
param attribute is used to deal with html form data.

3) getProperty:

This standard action is used to retrieve beans state with an xml kind of
syntax without need of writing any java code directly in the jsp. This is of
the following form:

<jsp: getProperty name=”ref” property=”beanproperty” />

The above instruction performs 2 things:

I. Retrieving the bean field data


II. Sending the output to the client

Q) Between bean fields ans html form ields god synchronization exists.
Exlain?

Html form

Emp No

Name

Salary

CLICK

Jsp gets data and stores data to object.


Employee emp =new Employee ();->In the background employee object is
created
<jsp: useBean id=”emp” class=”mypack.Employee” />
<jsp:setProperty name=”emp” param=”ti” /> -> In html form instead of each
parameter we get a param
Employee emp=new Employee();
Emp.setEmpno(Integer.parseInt(request.getParameter(“t1”);->In the
background the bean instance is cerated and setting the value.

Web Application

BeanApp
Book.html
View.jsp
WEB-INF
web.xml
Classes
Bookpack
Book.class

Book.html

<html>
<body>
<center>
<H2>Book Details Form</H2>
<form action ="View.jsp">
ISBN: <input type="text" name="isbn"><br>
Title: <input type="text" name="title"><br>
<input type="submit" value="submit book details">
</center>
</body>
</html>

Book. java

package Bookpack;
public class Book implements Serializable
{
private int isbn;
private String title;
public void setIsbn (int isbn)
{
this.isbn=isbn;
System.out.println (“Bean is populated”);
}
public int getIsbn ()
{
return isbn;
}
public void setTitle (String title)
{
this.title=title;
}
public String getTitle ()
{
return title;
}
}
web.xml

<web-app>
</web-app>

View.jsp

<html>
<body bgcolor=cyan>
<center>
<h1>Book details from the bean </h1>
<%@ page import="Bookpack.Book" %>
<jsp: setProperty name="b" property ="*" />
<h2>Book ISBN: <jsp: getProperty name="b" property ="isbn" /></h2>
<h2>Book Title: <jsp: getProperty name="b" property ="title" /></h2>
<br><br>
<input type="submit">
</center>
</body>
</html>
Once control went to jsp and bean is instantiated
If any constructions will execute when the setProperty are called using * all
the setXXX () properties are called.

Note:

In the above jsp we have used page directive. This directive is used here to
import the package of the book bean class.
Every jsp implicitly imports 4 packages

1. java.lang.*
2. javax.servlet.*
3. javax.servlet.http.*
4. javax.servlet.http.jsp.*

If we need any other package (standard/user defined) to be implemented into


the jsp, we make use of page directive
Example:
<%@ page import =”java.util.*” %>
To include more than one package we can separate them using comma (,)

As far as synchronization of bean fields and html form fields are concerned,
we used the following statement in the View.jsp
<jsp: setProperty name=”b” property=”*” />
The above instruction makes the container implicitly calling all the setter
methods of the bean instance whose reference is “b”. But one condition here
is that request parameters names (text field name) and bean variable names
must match for using *.

In this statement properties “*” can’t be used to normal classes if we want to


setProperty use the param or value attribute.

Equivalent jsp code

b.setIsbn (Integer.parseInt (request.getParameter (“isbn”)));


b.setTitle (request.getParameter (“title”);
If html names and bean variables are not matching “*” will not work in that
case we use 3 attributes
<jsp: setProperty name=”b” property=”isbn” param =”is” />
<jsp: setProperty name=”b” property=”title” param =”ti” />

Sharing a java bean instance across multiple jsp

useBean standard action is capable of performing 2 things:


1) Creating new bean instance every time when the request comes to the jsp.
2) If the bean instance already exists, it retrieves the existing one and does
not create new one.
useBean has one more attribute called scope. We can give 4 possible values
to it. This attribute decides whether new bean instance has to be created or
existing instance is to be used/ retrieved.

Values:

1. page
2. request
3. application
4. session

In the useBean standard action if we don’t mention scope attribute, by


default it takes page scope.
If scope is page, the bean is non shareable.

Q) Why is the bean not shareable across pages if its scope is page?

A) If the bean scope is page (by default), it is stored in the pageContext


object in binding to the reference specified by the id attribute of the useBean
standard action.
PageContext object is separate for every jsp and pageContext
object is dead as soon as response is given to the client. Therefore, bean
stored in this object also will be dead. Therefore bean is not shareable across
jsps.

Q) Develop and deploy a Web Application in which two jsps sharing the
same bean (state) when the scope is “request”?
A) SharingbeanApp
Emp.html
Source.jsp
Target.jsp
WEB-INF
web.xml
Classes
Emppack
Employee. class

http://localhost:8080/sharingbeanApp/emp.html

Source code of Employee bean

Package emppack;
Public class Employee implements Serializable
{
private int empno;
private String name;
public void setEmpno(int empno)
{
this.empno=empno;
}
public int getEmpno()
{
return empno;
}
public void setName(String name)
{
this.name=name;
}
public int getName()
{
return name;
}

}//Employee

c:>/javac –d . Employee.java
Source code of emp.html

<html>
<body>
<center>
<h1>EMPLOYEE DETAILS FORM</h1>
<form action=”source.jsp”>
EMPLOYEE NO<input type=”text” name=”empno”><br>
EMP NAME<input type=”text” name=”name”><br>
<input type=”submit”>
</form>
</center>
</body>
</html>

Source code of Source.jsp

<%@ page import =”emppack.Employee” %>


<jsp:useBean id=”emp” class=”emppack.Employee” scope=”request” />
<jsp:setProperty name=”emp” property=”*” />
<jsp:forward page=”target.jsp”>

Source code of target.jsp

<html>
<body bgcolor =”wheat”>
<%@ page import=”emppack.Employee” %>
<jsp:useBean id=”emp” class=”emppack.Employee” scope=”request” />
<center>
<h1>EMPLOYEE DATA</h1>
<h1>EMPLOYEE NUMBER : <jsp:getProperty name=”emp”
property=”empno” /></h1>
<h1>EMPLOYEE NAME : <jsp:getProperty name=”emp”
property=”name” /></h1>
</center>
</body>
</html>

web.xml
<web-app>
</web-app>

Note:

When the scope is request, the bean instance is not only bound to the
reference variables but also it is stored in the request object. When control is
switched to another jsp using forward mechanism, the second jsp gets the
same request object in which the bean and the state is stored. In the second
jsp when we make use of useBean, new instance is not created; the existing
bean is retrieved from the source jsp.

Q) Web Application to explore session scope concept of sharing of beans


across multiple jsps?
A) In the previous Web Application within the two jsps make the scope as
session.
When the scope is session, bean instance is stored in the session object. How
many jsps are participating in the same session, all those jsps shares the bean
instance.
Jsp model 1 architecture

jsp 2

5
4
Java
Bean

3
Web Client Web Container

DATABASE

In this architecture, jsp is the core element. It is responsible for receiving the
client request, instantiating the bean, populating the bean, retrieving the
database data from the bean and driving the output to the client.

Jsp model 2 architecture

This is famously known as MVC architecture. In this model of Web


Application loose coupling is implemented.
It defines separation of concerns (who has to do which job) very clearly.
As a result, Web Application development becomes flexible, easier and
enhancements of services become cheaper.
1

Servlets
2

jsp Java
5 Bean
6

3
Web Client Web Container

DATABASE

Explanation as per the numbers:

1. Servlet receives the Client request, does the preliminary processing.


2. Servlet creates the bean instance and populates it with the form data.
3. Bean contacts the database gets the necessary data and populates
itself.
4. Servlet switches the control to the jsp making it responsible to drive
the output to the client.
5. Jsp contacts the bean for the sake of data that is required to prepare
the output.
6. Jsp prepares the output and gives to Client.
In MVC architecture, java bean acts a model, jsp acts as a view, servlets acts
as Controller.
Model: data holding or data oriented logic holding entity is known as a
Model. Java bean play this role.
View: For the end user, not only interaction but also appealing web page
should be given. Jsp is excellent in giving a beautiful output (it is mixed
with html and jsp). Jsp is good at this. Therefore it acts as View.
Controller: Servlet plays the role of Controller in the MVC architecture of
Web Application because it is excellent in application logic execution, it is
responsible for receiving the client request, does preliminary processing,
dealing with bean and asking the jsp prepare the output.

Q) Web Application on MVC architecture

A) Refer to Hand-out

MVCApp
Emp.html
View.jsp
WEB-INF
web.xml
Classes
Nit
Servlets
ControllerServlet.class
Beanpack
Employee.class

http://localhost:8080/MVCApp/emp.html

Source code of emp.html :

<html>
<body bgcolor=”./mvc”>

</html><html>
<body bgcolor="cyan">
<form action="./mvc">
<center>
EMPLOYEE NUMBER<input type="text" name="eno"><br><br>
<input type=SUBMIT value="SNDEMPNO">
</center>
</body>
</html>

Source code of Employee.java :

package beanpack;
import java.sql.*;
public class Employee implements java.io.Serializable
{
Connection con;
private int empno;
private String name;
private float salary;
public Employee()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
}
catch(Exception e)
{
}
public void setEmpno(int empno)
{
this.empno=empno;
results();
}
public int getEmpno()
{
return this.empno;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return this.name();
}
public void setSalary(float salary)
{
this.salary=salary;
}
public float getSalary()
{
return this.salary;
}
public void results()
{
try
{
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select * from employee where

empno="+empno);
rs.next();
name=rs.getString("name");
salary=rs.getFloat("salary");
}
catch(Exception e)
{
}
}
}//class

Source code of ControllerServlet.java :

package nit.servlet;
import javax.servlet.*;
import javax.servlet.*;
import beanpack.Employee;
import java.io.*;
public class ControllerServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException,IOException
{
int empno=Integer.parseInt(request.getParameter("eno");
Employee ebean=new Employee();
ebean.setEmpno(empno);
getServletContext().setAttribute("ebean",ebean);
getServletContext().getRequestDisapatcher("/view.jsp").forward(request,res
po

nse);
}
}

Source code of View.jsp :

<html>
<body>
EMPLOYEE DETAILS<br><br>
<%@ page import="beanpack.Employee" %>
<jsp:useBean id="ebean" class="beanpack.Employee"
scope="application" />
EMPNO : <jsp:getProperty name="ebean" property="empno" /><br>
NAME : <jsp:getProperty name="ebean" property="name" /><br>
SALARY : <jsp:getProperty name="ebean" property="salary" /><br>
</body>
</html>

Source code of web.xml :

<web-app>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>nit.servlets.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/mvc</url-pattern>
</servlet-mapping>
</web-app>
Web Application development and deployment steps :

Create the Root directory “MVCApp”


Compile the Employee class >javac –d . Employee
Copy the beanpack in the classes directory
Before compiling the servlet class set the classpath
Set classpath=D:\WorkingDir;%classpath%
Compile the Servlet class D:\WorkingDir>javac –d . ControllerServlet.java
Copy the nit package into the classes directory
Copy the emp.html and view.jsp in the MVCApp
Copy the MVCApp into the webapps directory of Tomcat installtion
directory
http://localhost:8080/MVCApp/emp.html
Include mechanism in jsp

In industry strength Web Application pages are not created in monolithic


manner. A page may include other page context. This mechanism is known
as include mechanism.

Code duplication is avoided and web page development becomes


faster with include mechanism.

Include mechanism in a jsp is implemented in 2 ways:

1) By using include directive


2) By using include standard action

<%@ include file=”target.jsp” %>


<jsp:include page=”target.jsp” />

1) include directive: when we use directive the source code of the included
file (target) is copied into current jsp at translation time.

2) include standard action: the response of the target jsp is included in the
current jsp’s response at request processing time.
Q) What are the differences between include directive and include
standard action?

A)
S.No Criteria Directive Standard Action

1 syntax <%@ include file <jsp:include


=”target.jsp” %> page=”target.jsp”
%>
2 What is included Source code of target Output of target page
file
3 When is it included Translation time Runtime
4 How many servlets 1 2
created
5 Does source jsp file Yes No
size increase
6 Can handle changes No Yes
to target file(jsp)
7 Comparative More Less
performance

Web Application on the implementation of include directive


IncludedirApp
Source.jsp
Header.jsp
Footer.html
WEB-INF
web.xml
Classes

http://localhost:8080/includedirApp/source.jsp

Source code of Header.jsp

<html>
<body>
<marquee><font color=”green” size=8> WELCOME TO OUR
SITE</font></marquee>
</body>
</html>

Source code of footer.html

<html>
<body>
<br><br>
<br><br>
<br><br>
<br><br>@copy Naresh Information Technologies
</body>
</html>

Source code of source.jsp

<html>
<body bgcolor=cyan>
<%@ include file=”header.jsp” %>
<h1>HERE GOES THE BODY OF THE JSP</h1>
<@ include file=”footer.html” %>
</body>
</html>

web.xml

<web-app>
</web-app>

Web Application on include standard action

IncludeactionApp
Source.jsp
Target.jsp
WEB-INF
Web.xml
Classes

http://localhost:8080/includeactionApp/source.jsp
Source code of source.jsp

<html>
<body bgcolor=”wheat”>
<h1>INCLUDE ACTION USAGE</h1>
<jsp:include page=”target.jsp”>
<jsp:param name=”user” value=”nit@nit.com” />
</jsp:include>

</body>
</html>

Source code of target.jsp

<html>
<body bgcolor=wheat>
<h1><% out.println(“request.getParameter(“user”)); %></h1>
</html>

Session tracking

Protocols are of two types:


Stateless protocol
Stateful protocol

A protocol is said to be Stateless if it has no memory of prior connections in


the server side and server cannot distinguish one client request from that of
the other.

When http client makes a request to the http server, it gives response to the
client. Once request-response cycle is over, client is disconnected form the
server. This nature poses some challenges to the Web Application
developers.

Client interaction with the Web Application must be Stateful. Then only,
across series of requests a client is uniquely recognized and previous data
can be associated with the current request.
Session tracking is the ability of the Container to recognize the Client and its
associated data across multiple series of interactions.

To make Client interactions Stateful with the Web Applications, SERVLET


API provides support for the following techniques:

Cookies
Httpsession
url rewriting

cookies mechanism

a cookie is a name value pair of textual information created bythe server and
exchanged between client and server with every interaction

SERVLET API provides the following to implement cookies mechanism

Javax.servlet.http.Cookie
Javax.servlet.http.HttpServletRequest interface
Javax.servlet.http.HttpServletResponse interface

We have 2 kinds of cookies


Persistent cookies
Session cookies(browsing)

A cookie is said to be persistent if it is stored in the file system of the client


machine.

Session cookies is a cookie which will die as soon as browsing session is


over.

Steps to implement cookies mechanism

Step 1: instantiating the Cookie class.


Cookie c=new Cookie(“bgcolor”, “red”);

Step 2: Setting the life span of the Cookie(if required)


c.setmaxAge(365*24*3600);
Step 3: Sending the cookie to the client

Response.addCookie(c);

Step 4: Whenever required, retrieval of Cookie(s)


Cookies c[]=request.getCookies();

Q) Web Application on the implementation of cookie mechanism?

CookieApp
CookieExample.html
Welcome.html
Web-INF
Web.xml
Classes
CreateCookie.class
CheckCookie.class

http://localhost:8080/CookieApp/CookieExample.html

Source code of CookieExample.html

<html>
<body bgcolor=cyan>
<center>
<h2>WELCOME TO SHOPPING MALL</h2>
<form action=”./create” method=”post”>
<b>User Name</b>
<input type=text name=”user” > <br> <br>
<input type=submit value=”welcome” > <br> <br>
</center>
</body>
</html>

Source code of Welcome.html

<html>
<body>
<marquee>
<font color=green size=6>
WELCOME TO SHOPPING MALL
</marquee>
</body>
</html>

Source code of CreateCookie.java

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class CreateCookie extends HttpServlet
{
Public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
String name=req.getParameter(“user”);
Res.setContentType(“text/html”);
PrintWriter pw=res.getWriter();
Cookie c=new Cookie(“user”,name);
Res.addCookie(c);
Pw.println(“<html>”);
Pw.println(“<body bgcolor=wheat><center>”);
Req.getRequestDispatcher(“welcome.html”).include(req,res);
Pw.println(“<h2><a href=”./check”>SHOPPING GOES HERE</a></h2>”);
Pw.println(“</center></body></html>”);
Pw.close();
}
}

Source code of CheckCookie.java

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class CreateCookie extends HttpServlet
{
Public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
Res.setContentType(“text/html”);
PrintWriter pw=res.getWriter();
Cookie c[]=req.getCookies();
Pw.println(“<html>”);
Pw.println(“<body bgcolor=wheat><h2>”);
For(int i=0;i<length;i++)
{
Cookie c1=c[i];
If(c1.getName().equals(“user”))
{
Pw.println(“Hai”+c1.getValue() + ! Hope enjoying shopping here </h2>”)
Break;
}
}

Pw.println(“</body></html>”);
Pw.close();
}
}

Web.xml

<web-app>
<servlet>
<servlet-name>create</servlet-name>
<servlet-class>CreateCookie</servlet-class>
</servlet>
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>CheckCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>create</servlet-name>
<url-pattern>/create</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
</web-app>

Q) what are the uses of Cookies in Web Application development?


A)
Remembering the user preferences
To promote targeted Online advertisements
Uniquely identifying a client
Note: Browser is intelligent enough to send cookies to the server from where
they are generated
A browser can store a maximum of 300 cookies
From each server a maximum of 50 cookies are allowed
Limitation of cookies is it cannot hold more than 4 kb of information

Q) How to destroy a cookie in a servlet?

A) c.setMaxAge(0);

Cookie Example in jsp:

CookieApp
Userdetails.html
Readdetails.jsp
Getcookies.jsp

userdetails.html

<html>
<body bgcolor=wheat>
<form action=”./readdetails.jsp”>
Email ID: <input type=text name=”mail”><br>
Phone: <input type=text name=”phone”><br><br>
<input type=submit value=”submit details”>
</form>
</body>
</html>
Source code of readdetails.jsp

<%
String emailid=request.getParameter(“mail”);
String phone=request.getParameter(“phone”);
Cookie c1=new Cookie(“mail”,emailed);
Cookie c2=new Cookie(“phone”,phone);
Response.addCookie(c1);
Response.addCookie(c2);
Out.println(“<a href=”./getcookies.jsp”>CLICK HERE TO GET YOUR
DETAILS</a>””);
%>

Source code of getcookies.jsp

<%
Cookie c[]=request.getCookies();
Out.println(“EMAIL ID:” +c[0].getValue());
Out.println(“PHONE NUMBER:+”c[1].getValue());
%>

Session tracking using HttpSession

Session tracking is the ability of the container to associate series of requests


with a particular client uniquely. In this process 2 things are to be taken care
of

1) Recognizing the client


2) Associating client data with the client request

HttpSession is an interface. Its object is created by the Container. This


session object represents the association between client and its request.

Steps to implement Session Tracking using HttpSession object.

Step 1: Create the HttpSession object and get its reference.


HttpSession session=request.getSession ();

Step 2: Retrieve the client data in the current request and add it to the
session object.
session.setAttribute (String name, Object value);

Step 3: Whenever we want to retrieve client data after a series of client


interactions, we say
session.getAttribute ()
Or
session.getAttributeNames ()

Step 4: When the end user explicitly wants to logout, destroy the session
object.

Q) How does session tracking working behind the scenes?

A) When getSession () method is called on the request object, it does lot of


work in the background.
1. It checks the incoming http request headers for session id.
Case 1: if session id is encountered, container does not create the new
session object. It gives the reference to the existing session object.
Case 2: If session id is not encountered, this method creates one new session
object, its associated id. This key value pair is internally maintained in a
table kind of form.

For each client, a separate session object is created.

When the response is given to the client, container sends the associated
session id through response header. For sending session id, cookie
mechanism is internally used.
Q) What is seesion time-out in Session tracking?
A) For each client one session object is dedicated. It will consume few
server resources. Between the last client request and current system time,
if a specified amount of time is lapsed which is known as max inactive
interval, container destroys the session object associated with that client.
This is known as session time-out. When the session object is destroyed,
session id as well as client state gets discarded.
By default tomcat gives 30 minutes for session time-out. We
can also configure session time in two ways:

Declaratively
Programatically

In the web.xml, we make the following entry:

<session-config>
<session-timeout>
45
</session-timeout>
</session-config>

In a servlet we can say as follows:


Session.setMaxInactiveInterval(2700);

Q) Explain overloaded methods of HttpServletRequest to get the


HttpSession reference?

A) To get the HttpSession reference of a session object, we make use of the


overloaded versions of req.getSession() method. There is no difference
between the zero argument method and parameterized method if the
argument is true.If the argument is false, getSession() method behaves
differently from that of zero argument one. It works as follows:
Container looks for the session id in the incoming request header. If it is
found the reference to the existing session object is returned. If it is not
found, session object is not created. Instead, it returns null.

Q) If we use HttpSession mechanism for session tracking, will it work


fine all the times?
A) No. if cookies are disabled in the browser, session tracking fails.
Remedy for this is url-rewriting.
Web Application on URL Rewriting

rewritingApp
WEB-INF
Web.xml
Classes
SessionDetailsServlet.class

web.xml

<web-app>
<servlet>
<servlet-name>details</servlet-name>
<servlet-class>SessionDetailsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>details</servlet-name>
<url-pattern>/details</url-pattern>
</servlet-mapping>
</web-app>

Source code of SessionDetailsServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class SessionDeatilsServlet extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
HttpSession session=request.getSession();
Integer count=(Integer) session.getAttribute("requestcount");
if(count==null)
count=new Integer(1);
else
count=new Integer(count.intValue()+1);
session.setAttribute("requestcount",count);
pw.println("<html><body bgcolor=cyan>");
pw.println("<h3>Number of times this page visited:" +count + "</h3>");
pw.println("<h2>Your session details </h2>");
pw.println("<h2>session id: +session.getId() +"</h2>");
if(session.isNew())
pw.println("<h2> It is a New Session</h2>");
else
pw.println("<h2> It is an existing session </h2>");
pw.println("<h2>Created Time: ");
pw.println(new Date(session.getCreationTime())+"</h2>");
pw.println("<h2>Last accessed Time: ");
pw.println("new Date(session.getLastAccessedTime())+"</h2>");
pw.println("<h2>Time out in seconds:"+session.getMaxInactiveInterval()
+"</h2>");
pw.println("<h3>Is session ID coming from cookie:
"+request.isRequestedSessionIdFromCookie()+"</h3>");
pw.println("<h3>Is session ID coming from URL:
"+request.isRequestedSessionIdFromURL()+"</h3>");
pw.println("<a href=\""+response.encodeURL(request.getRequestURI())
+"\">RELOAD THIS PAGE</a>");//url rewriting
pw.println("</body></html>");
}
}
URL rewriting: It is the mechanism of appending session id to the URL to
which the request is going to be submitted. To implement this mechanism
we call encodeURL method on the response object as follows:

Response.encodeURL (String URL);

This method does not do anything if cookie mechanism is working. If


cookies are disabled, this method appends session id to the URL so that
client can be uniquely identified.

Custom Action

An action is a functionality provided by the container whenever its


associated tag is encountered.

In jsp we have 2 kinds of actions (tags):

1) Standard actions
2) Custom actions

1) Standard actions

Standard actions are runtime instructions given by the jsp author to the jsp
whose meaning is already known to the container. The advantage of these
actions is that by using xml kind of syntax tags, we can get the functionality.
There is no need of writing java code directly in the jsp. This makes jsp
development easier, flexible, and maintainable.

2) Custom actions

Our own defined actions are known as custom actions.

Syntax and working of custom actions is similar to that of standard actions.

Standard actions are excellent in their functionality but they ate confined to
few areas. In practical industry strength Web Applications, this limited
functionality is not sufficient.
Complex functionality has to be provided. Hence the need of our own
defined actions.

Q) What are the differences between standard action and custom actions?

Standard actions Custom actions


Their meaning is already known to We need to explain
the container
Tags and associated java code is We should develop tags plus java
shipped along with the container code
Functionality is limited Can be used for any complex
functionality
Common for every jsp in every web Specific to certain Web Application
application
We need not import any library in We have to
order to use them

Custom Tag Development

While dealing with custom tags, we encounter the following terminology.

1) Tag

It is an instruction given by the jsp author to the container

Tag has 2 parts

I. Prefix
II. Action name

For example,

<jsp: forward>

Here jsp is the prefix and forward is the tag name


<own: printhello>

2) Tag Handler
It is a java class that provides the action (functionality) for the tag.
3) Tag library Descriptor

It is an xml file with any name but with .tld extension.

In this file tags and their properties are described. Mapping between tags
and corresponding tag handlers specified. Tag library information is
specified.

4) Tag library

Combination of tags, tag handler and tld.

Steps to develop Custom Tag:

There are 5 steps to develop and use a Custom tag

Step 1: Define the Tag handler


Step 2: Write the Tag Library Descriptor
Step 3: Deploy the Tag Library
Copy the class file of the Tag handler in the classes directory
Copy th etld file under WEB-INF
Step 4: Register the Tag Library with the Web Application by making an
entry in the web.xml
Step 5: Using a Custom Tag in a jsp.
In order to use the Custom tag, e have to import the tag library
into th ejsp by using taglib directive.
Developing a tag Handler for a Custom Tag

A Tag Handler is any java class that implements javax.Servlet.jsp.target.tag


interface directly or indirectly.

TagSupport class implements Tag interface and thereby provides default


functionality to our own Tag handler classes. Therefore, our own Tag
Handler classes extend javax.Servlet.jsp.tagext.TagSupport class.
Tag interface provides the following life cycle methods.
Void setpageContext(PageContext)
Int doStartTag()
Int doEndTag()
Void release()
Flow chart for Tag interface

SetPageContext(PC)

SetAttributes()
………………

Tag.EVAL_BODY_INCLUDE
DoStartTag()

Container evaluates
the body of the tag

Tag.EVAL_PAGE Tag.SKIP_PAGE
DoEndTag()

After the Custom Tag, further Return from the current


contents of jsp to be jsp without evaluating
evaluated

Q) Web Application to implement a Custom Tag and use it in a jsp

A) Refer to the hand-out

Step 1: Develop tag Handler


Public class HelloHandler extends TagSupport
{
………..
}
Step 2: Writing the Tag Library Descriptor(.tld)
<taglib>
…………
</taglib>
These files has 2 sections
Description about the library
Tags definiton and mapping to Tag Handler
Step 3: Deploying the Tag Library
Step 4: Registering the Tag Library with the Web Application
In the web.xml, we make use of <taglib> element for Tag Library registration
Step 5: Using the Custom Tag we have to import the Tag Library
<%@ taglib prefix=”nit” uri=”mapping name to tld file” %>

customtagapp
WEB-INF
Web.xml
Tld
Ourtaglib.tld
Classes
Hellopack
HelloHandler.class

http://localhost:8080/customtagapp/hello.jsp

source code of hello.jsp

<html>
<body bgcolor=wheat>
<%@ taglib prefix="nit" uri="http://www.nit.com/customtags" %>
<h3><nit:hello />WELCOME TO CUSTOM TAGS</h3>
</body>
</html>

source code of web.xml

<web-app>
<taglib>
<taglib-uri>
http://www.nit.com/customtags
</taglib-uri>
<taglib-location>
/WEB-INF/tld/ourtaglib.tld
</taglib-location>
</taglib>
</web-app>

source code of ourtaglib.tld

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>hello</name>
<tag-class>hellopack.Hellohandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

source code of HelloHandler.java

package hellopack;
import jaax.servlet.jsp.*;
import jaax.servlet.jsp.tagext.*;
import java.io.*;
public class HelloHandler extends TagSupport
{
public int doStartTag() throws JspException
{
try
{
JspWriter out=pageContext.getOut();
out.println("hello");
}
catch(IOException e)
{
System.out.println(e);
}
return SKIP_BODY;
}
}

Q) How does a Custom Tag works?


A) Whenever Custom tag is encountered in jsp, the Container performs the following
things:
Picks up the prefix of the Custom Tag and looks fro the match in the taglib directive
Once match is found it picks up the uri value of the taglib directive
With that uri value it looks in the web.xml for the uri match
Once the match is found, it picks up the location of the tld file from the web.xml
Container looks in the tld file for the encountered custom tag( in the jsp)
Once the tag is found, it looks for the corresponding tag handler.
Tag Handler is loaded into memory instantiated and initialized
Our application looks written in the Life Cycle method gets executed. This is how a
particular Custom gets the functionality.

Q) What is the Life Cycle of the Custom Tag?


A) Container loads the java class (tag handler) and instantiates it.
Container calls the setPageContext() on the Tag Handler instance. Through this method,
Container provides the entire jsp environment to the Tag Handler via PageContext object
tag Handlers responsibility is to hold this object our own Tag Handler extends AgSuport
class and that class provides some default functionality is, holding (saving globally
within the class) the PageContext object.
PageContext object provides getXXX() methods to retrieve all the implicit objects.
Once setPageContext() method is completely executed, Tag Handler is initialized.
As the start Tag is encountered Tag is encountered by the Container, it callsteh
doStartTag() on the Tag Handler instance.
In this method, we write our required logic. This logic is the background functionality for
the Custom Tag.
This method returns any one of the 2 integer constants of the tag interface.
Tag.EVAL_BODY_INCLUDE
Tag.SKIP_BODY

These constants are indicators totheContainer what to do next


When jsp engine encounters the end Tag in the jsp, it calls the doEndTag() method on the
Tag Handler instance.

This method returns any of the 2 consants.


Tag.EVAL_PAGE(default)
Tag.SKIP_PAGE

Q) Web Application on Custom Tag without body but with attributes?

A) Refer to hand-out.
Whenever attributes are there for a tag, we have to do two things in the Tag Handler.
Declare those many private variables as there are attributes.
For each variable, one setter method.
Step 2: In the tld file we have to make entries regarding the attributes
<tag>

</tag>

ClassicTagWithAttributes
Greet.jsp
WEB-INF
Web.xml
Tld
Ourtaglib.tld
Classes
Greetpack
GreetingHandler.class

source code of greet.jsp

<html>
<body bgcolor=wheat>
<%@ taglib prefix="nit" uri="htp://www.nit.com/customtags" %>
<h2><nit:greet name="Adil" Age="23" /></h2>
</body>
</html>

source code of web.xml

<web-app>
<taglib>
<taglib-uri>
http://www.nit.com/customtags
</taglib-uri>
<taglib-location>
/WEB-INF/tld/ourtaglib.tld
</taglib-location>
</taglib>
</web-app>

source code of ourtaglib.tld

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>greet</name>
<tag-class>greetpack.GreetingHandler</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>age</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

Source code of GreetingHandler.java


package greetpack;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class GreetingHandler extends TagSupport
{
private String name;
private int age;
public void setName(String name)
{
this.name=name;
}
public void setAge(int age)
{
this.age=age;
}
public int doStartTag() throws JspException
{
try
{
JspWriter out=pageContext.getOut();
out.println("Hello "+name+" your are "+age+" yearsold");
}
catch(IOException e)
{
System.out.println(e);
}
return SKIP_BODY;
}
}
<attribute> element has 3 child elements:

1) <name>: This is an Optional Element. Its value is by default false. If we


specify it as true, it means that for the custom tag this attribute and
corresponding is mandatory.

2) <required>: This is an optional element. Its values are by default false.


If we specify it as true, it means that for the custom tag this attribute and
corresponding is mandatory.

3) <rtexprvalue>: It is also an optional element. Its value is by default


false. If we specify it as true, it means that the attribute value can be
supplied at request time processing only.

Q) Web Application on custom tag implementation. Its Tag Handler


performs database access. It receives html form data also?

A) Refer to the hand-out.

Databaseapp
Results.html
Results.jsp
WEB-INF
Web.xml
Mytaglib.tld
Classes
Students
Resultshandler.class

http://localhost:8080/databaseapp/results.html

Source code of results.html :


<html>
<body bgcolor=cyan>
<h2>ENTRANCE EXAM RESULTS</h2>
<form action=”./results.jsp”>
HallTicketNO<input type=text name=”htNp”><br>
<input type=”submit” value=”get results here”>
</form>
</body>
</html>

Source code of results.jsp :

<html>
<body bgcolor=cyan>
<%@ taglib uri=”customtags” prefix=”nit” %>
<h2>ENTRANCE SCORE CARD</h2>
<h3><nit:results /></h3>
</body>
</html>

Source code of web.xml :

<web-app>
<taglib>
<taglib-uri>customtags</taglib-uri>
<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
</taglib>
</web-app>

Source code of mytaglib.tld :

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>nit</short-name>
<tag>
<name>results</name>
<tag-class>students.ResultsHandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Source code of ResultsHandler.java :

Package students;
Import javax.servelt.jsp.*;
Import javax.servlet.jsp.tagext.*;
Import java.sql.*;
Public class ResultsHandler extends TagSupport
{
Connection connection;
Public ResultsHandler()
{
Try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:15
21:orcl”,”scott”,”tiger”);
}
Catch(Exception e)
{
}
Public int doStarttag() throws JspoException
{
Try
{
JspWriter out=pageContext.getOut();
String htNo=pageContext.getRequest().getparameter(“htNo”);
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(“select * from entrance where htNo=”+htNo);
Rs.next();
Out.println(“HAL:L TICKET NUMBER :” +htNo);
Out.println(“CANDIDATE NAME:”+rs.getString(2));
Out.println(“MARKS:”+rs.getString(3));
Rs.close();
St.close();
}
Catch(Exception e)
{
}
Return SKIP_BODY;
}//doStartTag()
Public void release()
{
Try
{
If(connection!=null)
Connection.close();
}
Catch(Exception e)
{
}
}//release
}
Life Cycle and Flow Chart of Iteration Tag:

Javax.servlet.jsp.tagext.IteartionTag interface is a child of Tag interface.


TagSupport class implements this interface also.

Tag
Interface

Extends

Implements
IterationTag TagSupport
Interface

IterationTag has one constant and one Life Cycle method.


1. IterationTag.EVAL_BODY_AGAIN
2. public int doAfterBody()
setPageContext(PC)

setAttributes()
………………

EVAL_BODY_INCLUDE
doStartTag(
)

Container evaluates
the body of the tag
EVAL_BODY_AG
AIN SKIP_BO
DY
doAfterBody
()

EVAL_PAGE SKIP_PAGE
doEndTag()

Evaluate the rest of the jsp Return from the current jsp
without evaluating
Q) Web Application on IterationTag
A) Refer to the hand-out.

Iterationapp
Loop.jsp
WEB-INF
Web.xml
Tld
Mytaglib.tld
Classes
Iterationpack
IterationTagHandler.class

http://localhost:8080/iterationapp/loop.jsp

Source code of loop.jsp :

<html>
<body bgcolor=pink>
<%@ taglib prefix=”nit” uri=”customtags” %>
<nit:iterate count=”5” > THIS IS EVALUATED
REPETITIVELY</nit:iterate>
</body>
</html>

Source code of web.xml

<web-app>
<taglib>
<taglib-uri>customtags</taglib-uri>
<taglib-location>/WEB-INF/tld/mytaglib.tld</taglib-location>
</taglib>
</web-app>
Source code of mytaglib.tld

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<Tag>
<name>iterate</name>
<tag-class>iterationpack.IterationTagHandler</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>count</name>
<required>true</required>
</attribute>
</Tag>
</taglib>

Source code of IterationTagHandler.java

Package iterationpack;
Import javax.servlet.jsp.*;
Import javax.servlet.jsp.tagext.*;
Public class IterationTagHandler extends TagSupport
{
Private int count;
Public void setCount(int count)
{
This.count=count;
}
Public int doStartTag() throws JSpException
{
If(count>0)
Return EVAL_BODY_INCLUDE;
Else
Return SKIP_BODY;
}
Public int doAfterBody() throws JSpException
{
If(--count>0)
Return EVAL_BODY_AGAIN;
Else
Return SKIP_BODY;
}
}

TYPES OF RESULTSET

We have the following kinds of ResultSet:

1) Non Scrollable Non Updatable


2) Non Scrollable Updatable
3) Scrollable Non Updatable
4) Scrollable and Updatable

A ResultSet is Scrollable if the cursor can be moved in the ResultSet in


forward and between directions. We can also move the cursor to any row in
ResultSet object.

A ResultSet is said to be Updatable if we can modify the rows


programmatically without the need of SQL Statements directly.

Q) How to create Non Scrollable and Non Updatable ResultSet?

A) Normal way of creating the ResultSet object is Non Scrollable and Non
Updatable ResultSet.

Q) How to create the Scrollable and (Non) Updatable ResultSet object?

A) At the time of ResultSet object creation, we don’t do anything special.

ResultSet rs= st.executeQuery (“Select …….”);


However we need to create the Statement objects in a special manner so that
they can produce Scrollable and Updatable ResultSets. We make use of
overloaded versions of Connection interface to create the Statement objects.

Statement st=con.createStatement
(ResultSet.SCROLLABILITYCONSTANT,
ResultSet.UPDATABILITYCONSTANT);

PreparedStatement ps=con.prepareStatement (String selectStatement,


scrollabilityconst, updatabilityconst);

Note:

Once we create the Statement objects in such a specialized manner, they can
produce scrollable or updatable ResultSet objects.

Q) Create the java.sql.Statement object that can produce Scrollable and


Non Updatable ResultSet

A) Statement st=con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Or
Statement st=con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

Q) Create the Statement object that can produce Non-Scrollable but


Updatable ResultSet?

A) Statement st=con.createSatement
(ResultSet.TYPE_SCROLL_FORWARDONLY,
ResultSet.CONCUR_UPDATABLE);

Q) What are the benefits of Scrollable ResultSet object?

A) There are few benefits if we can move the cursor in both the directions. If
we can move the cursor to the required row.
We can create a GUI tool using which we can browse through the records of
the ResultSet object.
Even after reading the row of the ResultSet object, we can read the data
again.
We can move to a particular row in order to update it.

Q) How many kinds of methods we have in ResultSet interface?

A) Cursor Movement methods


Data accessing methods
Metadata accessing methods.

Cursor Movement methods:

Next()
Previous()
Relative(-/+ number)
Absolute(-/+ number)
First()
Last()
beforeFirst()
afterLast()

To find out the cursor position

Int getRow()
Booloean isLast()
Boolean isFirst()
Boolean isBeforeFirst()
Boolean isAfterlast()

Q) Write some piece of code to know the number of records in a tbale


progarmatically

Class.forName();
Connection con=DM.getConnection();
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultS
et.CONCUR_READ_ONLY);
ResultSet rs=st.executeQuery(“select * from employee”);
Rs.last();
Int noofrows=rs.getRow();

Q) Piece of code to print the records of the ResultSet in the reverse


order.

ResultSet rs=st.executeQuery(“Select * from employee”);


Rs.afterLast();
While(rs.previous())
{
//Data Accessing Code
}
Q) What is the difference between TYPE_SCROLL_SENSITIVE and
TYPE_SCROLL_INSENSITIVE?

A) The ResultSet object which contain a set of records is open to all the
applications. If the modifications made to the ResultSet are also available to
the external program then we say that the ResultSet is sensitive or else
insensitive.

Updating records of the ResultSet programmatically :

Normally ResultSet is read only. We cannot make modifications to the


records of the ResultSet. But, if we can produce a ResultSet object that is
updatable we can make modifications to the records of not only the
ResultSet but also of the table. To make tese modifications we need not use
insert, delete or update Statements. In an object oriented way
programmatically we can make modifications.

Inserting a row programmatically

Every ResultSet object is associated with a special row known as insert row.
It is considered as a special buffer into which we can compose column
values of a record.

Step 1: Move the cursor to the buffer row( insert row) to compose the
column values.
Rs.moveToInsertRow();
Step 2: Compose the new row with column values. We call updateXXX()
methods to do this job.

Step 3: Call the following method.


Rs.insertRow(); This method call does two things :
Inserting the record into the ResultSet.
Inserting the record into the table.

Deleting a record programmatically

Step 1: move the cursor to the record that we want to delete


Step 2: rs.deleteRow();

Record will be deleted both from the REsultSet and database (table) . The
above all things are not all used in real time projects, but will be useful in
GUI tools.

Batch Updates
Batch Update is a facility offered by the JDBC. By using this facility we can
submit SQL Statements as a batch to the database server to perform update
operations.
OLTP(Online Transaction Processing)
Batch Processing- Number of trips to the server can be reduced.
This is the advantage of Batch Processing
To implement Batch Update concepts we have 2 methods.
1. addBatch(String DMLStmt)
2. int[] executeBatch()

Statement object is associated with a list (some internal data structure). This
list is initially empty. We can add any number of SQL Statements to the list.

St.addBatch(“insert……..”);
St.addBatch(“update……”);
St.addBatch(“delete…….”);

Once the bacth is formed, to submit the batch we say


Int rows[]=st.executeBatch();

Q) Can we add a Select Statement to a Bacth?


A) Yes, we can add even a Select Statement to a Batch without any problem
it will not give any compile time error. But as a result of the execution of
Select Statemnet, the set of records given that are given cannot be holded in
the array compartment, so it will raise SQLException.
Int[] excuteBatch()

This array would contain various compartments, each compartment for each
Statement. Each compartment would contain a number that would indicate
the number of rows that are effected by each of the Batch Statement.

OLTP- When the user expects the response to be given immediately after he/
she gives request.
Ex: ATM

Batch update operation implementation code snippet

Statement st=con.createStatement();
St.addBatch(“insert into Student values(1, ‘Adil’);
St.addBatch(“delete from Student where sno=1”);
St.addBatch(“Update student set sname= ‘adil’ where sno=2”);
Int affectedRows[] =st.executeBatch();
Int rows=0;
For(int i=0;i<affectedRows.length;i++)
Rows+=affectedRows[i];
System.out.println(“Number of rows affected : “ +rows);

executeBatch() method throws 2 kinds of exceptions:

1. SQLException
2. BatchUpdateException

For some reasons if any of the SQL Statement is unable to be excuted, the
method throws BatchUpdateException

In the batch is any SQL Statement returns other than integer, i.e., DDL or
DRL Statement, this method throws SQLException
Simple Transaction Management

Transaction: A unit of interaction between the Client Application and the


database server in which a group of SQL Statements are submitted whose
effected changes are either all are made permanent or none of them are made
permanent.

Or

Either all or none is a Transaction

Try
{
Statement st =con.createStatement();
St.executeUpdate(“Update cur_acct set bal=bal-40000 where
acct_no=501”);
St.executeUpdate(“update sav_acct set bal=bal+40000 where
acct_no=956”);
}
Catch(Exception e)
{
System.out.println(e);
}
Note: When SQL Statements are submitted through java i.e., JDBC
and once the result is given then changes are made permanent to the
database. This is the advantage of submitting SQL Statements through java.
In SQL, i.e., at the SQL prompt whatever changes are made to the database
they aree not permanent, if we want to make the changes permanent we need
to use commit.
In case of transaction failure changes are rolled back.
Every transaction has 2 boundaries. Controlling these boundaries is known
as transaction demarcation or transaction management.
The 2 boundaries of the transaction are:
1. Beginning of the Transaction
2. End of the Transaction

In java when the Connection is established with the database the Connection
object is opened with auto commit mode enabled. As a result each SQL
Statement submitted to the database behaves as an individual transaction.
Therefore, we cannot logically group SQL Statements into one unit of
interaction.

In order to group a set of SQL Statements into one unit we have to disable
the commit mode of the Connection object.

Con.setAutoCommit(false);

Try
{
Statement st=con.createStatement();
Connection con=DM.getConnection();
Con.setAutoCommit(false); //making the changes permanent is stopped
St.executeUpdate(“update cur_acct set bal=bal-40000 where acct_no=501”);
St.executeUpdate(“update sav_acct set bal=bal+40000 where
acct_no=956”);
Con.commit();//ending the transaction
}
Catch(Exception e)
{
Con.rollBack();
}

Once the above method call is made our unit of interaction ( transaction)
starts.
In order to end a transaction we have to call either
Con.commit() – successful ending
or con.rollback() – unsuccessful ending

Piece of JDBC code

try
{
Connection con=DM.getConnection();
Statement st=con.createStatement();
con.setAutoCommit(false);
st.excuteUpdate("update cur set bal=bal-40000 where acct_no=501");
st.excuteUpdate("update sav set bal=bal+40000 where acct_no=956");
con.commit();
}
catch(Exception e)
{
try
{
con.rollback();//this will again raise exception
}
catch(Exception e)
{
System.out.println(e);
}
}

Whenever a Transaction is started, it should be ended whether that ending


may be successful or unsuccessful ending in order to release the locks.

Q) What is type 2 Driver? Give example.

A) It is known as Native API partly java Driver.


This driver eliminates ODBC layer altogether and therefore it offers better
performance over Type 1 driver.

Type 2 Drivers

Database Server
Native Library

Client Server
This driver converts JDBC method calls of the Client Application (JDBC
program) into database server vendor dependent library calls

Disadvantages:

In every Client machine we should have DBServer library. Therefore it


cannot be used in Internet applications.

OCI- Oracle Callable interface

Example:

For Oracle, type 2 driver is oracle.jdbc.driver.OracleDriver

Connection URL:

Jdbc:oracle:oci8: @localhost: 1521:orcl

Type 3:

Used in Application Server Environment.


Java Server pages Standard Library (JSTL)
JSTL is a group of 4 standard tag libraries.

Core library
Database accessing library
Xml data processing library
I18n and formatting library

Core library provides tags to perform the following actions in a JSP

Accessing data from memory


Taking decisions
Looping over data
Redirecting control to other pages etc.

Steps to make use of JSTL Tags

Step 1: Copy 2 jar files into the lib directory of our Web application root
directory.

Standard.jar
Jstl.jar

Step 2: Import the JSTL library into the jsp

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

Step 3: Make use of Expression language whenever necessary while using


the tags of the library.

Expression language: It is a separate language used in the jsps along with


JSTL Tags to make accessing with JSTL tags to make accessing data from
memory very easier. EL totally eliminates the need of java code in the jsp.
EL expression start with “{$” and ends with “}”

Example Web Applications to use JSTL Tags:

Refer to Hand out.


Sending Batch Updates

The batch update facility provided by the JDBC 2.0 core API allows a
Statement object to submit multiple update commands together as a
single unit, or batch, to the underlying DBMS. This ability to submit
multiple updates as a batch rather than having to send each update
individually can improve performance greatly in some situations.

The following code fragment demonstrates how to send a batch update to a


database. In this example, a new row is inserted into three different tables in
order to add a new employee to a company database. The code fragment
starts by turning off the Connection object con's auto-commit mode in
order to allow multiple statements to be sent together as a transaction. After
creating the Statement object stmt, it adds three SQL INSERT INTO
commands to the batch with the method addBatch and then sends the
batch to the database with the method executeBatch. The code looks
like this:

Statement stmt = con.createStatement();


con.setAutoCommit(false);

stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");


stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");

int [] updateCounts = stmt.executeBatch();

Because the connection's auto-commit mode is disabled, the application is


free to decide whether or not to commit the transaction if an error occurs or
if some of the commands in the batch fail to execute. For example, the
application may not commit the changes if any of the insertions fail, thereby
avoiding the situation where employee information exists in some tables but
not in others.

In the JDBC 2.0 core API, a Statement object is created with an


associated list of commands. This list is empty to begin with; commands are
added to the list with the Statement method addBatch. The commands
added to the list must all return only a simple update count. If, for example,
one of the commands is a query (a SELECT statement), which will return a
result set, the method executeBatch will throw a
BatchUpdateException. A Statement object's list of commands
can be emptied by calling the method clearBatch on it.

In the preceding example, the method executeBatch submits stmt's list


of commands to the underlying DBMS for execution. The DBMS executes
each command in the order in which it was added to the batch and returns an
update count for each command in the batch, also in order. If one of the
commands does not return an update count, its return value cannot be added
to the array of update counts that the method executeBatch returns. In
this case, the method executeBatch will throw a
BatchUpdateException. This exception keeps track of the update
counts for the commands that executed successfully before the error
occurred, and the order of these update counts likewise follows the order of
the commands in the batch.

In the following code fragment, an application uses a try/catch block,


and if a BatchUpdateException is thrown, it retrieves the exception's
array of update counts to discover which commands in a batch update
executed successfully before the BatchUpdateException object was
thrown.

try {
stmt.addBatch("INSERT INTO employees VALUES (" +
"1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260,
'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");

int [] updateCounts = stmt.executeBatch();

} catch(BatchUpdateException b) {
System.err.println("Update counts of successful commands: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i ++) {
System.err.print(updateCounts[i] + " ");
}
System.err.println("");
}
If a printout was generated and looked similar to the following, the first two
commands succeeded and the third one failed.

Update counts of successful commands:


1 1

JDBC drivers are not required to support batch updates, so a particular driver
might not implement the methods addBatch, clearBatch, and
executeBatch. Normally a programmer knows whether a driver that
he/she is working with supports batch updates, but if an application wants to
check, it can call the DatabaseMetaData method
supportsBatchUpdates to find out. In the following code fragment, a
batch update is used only if the driver supports batch updates; otherwise,
each update is sent as a separate statement. The connection's auto-commit
mode is disabled so that in either case, all the updates are included in one
transaction.

con.setAutoCommit(false);
if(dbmd.supportsBatchUpdates) {
stmt.addBatch("INSERT INTO . . .");
stmt.addBatch("DELETE . . .");
stmt.addBatch("INSERT INTO . . .");
...
stmt.executeBatch();
} else {
System.err.print("Driver does not support batch updates; ");
System.err.println("sending updates in separate statements.");
stmt.executeUpdate("INSERT INTO . . .");
stmt.executeUpdate("DELETE . . .");
stmt.executeUpdate("INSERT INTO . . .");
...
con.commit();

Você também pode gostar