0% found this document useful (0 votes)
1 views

advance java ebook(jdbc+servlet+jsp)_PISBMS03

The document provides an overview of Advanced Java technologies, focusing on JDBC, Servlets, and JSP for web application development. It explains the differences between various storage types, emphasizing the advantages of database storage over file storage, and details the JDBC driver types and their functionalities. Additionally, it covers JDBC statements, transaction management, connection pooling, and batch processing, along with practical examples for implementing these concepts in Java applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

advance java ebook(jdbc+servlet+jsp)_PISBMS03

The document provides an overview of Advanced Java technologies, focusing on JDBC, Servlets, and JSP for web application development. It explains the differences between various storage types, emphasizing the advantages of database storage over file storage, and details the JDBC driver types and their functionalities. Additionally, it covers JDBC statements, transaction management, connection pooling, and batch processing, along with practical examples for implementing these concepts in Java applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Advance Java

->In advance java we will learn about 3 technologies

o JDBC (java database connectivity)


o Servlet
o JSP
->using advance tech stack we can develop web application.

What is web application ?


->In simple word the application which is executing in the internet environment or
web environment is know as WebApplication . in which request and response play a
major role.

Here

JDBC:-stands for java database connectivity which helps to interact with


database.

Servlet:-Servlet is a server side program which accept the request from


client/user through web browser.

JSP:-JSP stands for Java server page and which is response from web
application to client.
JDBC
->Before understand about JDBC let understand about storage first.

Types of Storages related to JAVA


o Field Storage
o Object Storage
o File Storage
o Database Storage

Field Storage:-Field Storage are related to our variable and this memory is generated to
hold single data value and this is also a temporary storage in program. All primitive
datatype variables are nothing but field storage only.

Object Storage:-The memory generated to hold group of members is know as Object


Storage.this generated in heap memory and it also a temporary storage .

Note:- both Field Storage and Object Storage are temporary storage because these
storage will be destroyed automatically when JVM shutdown.

When we have to store something permanent then we have two type of


storage .

o File Storage
o Database Storage
File Storage:- It is a Storage which is managed by operating System and it is
recommended for Files storage Not for Web application Data ,

->File Storage is ok for local files and data but if we talk about any web
application perspective then there is lot of limitation due to which we are
unable to use File Storage for web application.

Few Limitation/disadvantage of File Storage

Data Redundancy:-

->redundancy means duplication of data ,in file system it is possible to have


duplicate data which leads to memory wastage.
Data Inconsistency:-
->Data Inconsistency means data are not present in well organized manner as
well as not proper consisant state.

Limited Data Sharing:-


->all file and data may present in scattered form unorganized manner which
create problem to share data properly.

Atomicity Problem:
->Any operation on database must be atomic , which means it must
happen entirely or not at all. It is possible in database but in file storage
atomicity is impossible.

Multiple-access
->In database multiple users are allowed to access data at same time
simultaneously means they can perform reading /writing operation same
time which is not possible in File Storage.

Security
->as compared to File Storage Security is very high in database .

Database Storage
->database is the permanent storage which is installed into computer.which is
used to store data of web application (client details,application details..etc).
->There are lots of database available in market like Mysql,Oracle..etc.

->In database we can store data in well organized format which make easy to
insert and fetch data from it.

->it solves all the data storage issue present in File Storage.
->lets talk about JAVA application.
Developer can use any database its depends on there requirement. So when we want to
establish communication between database like(Mysql,Oracle..etc) then java app must
be developed with such Classes and Interfaces that which helps to establish
communication between java application and database.

->java need to take help of “java.sql” package and need support of JDBC driver.

Driver:-
->JDBC driver is a software it enable java application to interact with
database.

->Driver is acting as a translator between java application and database . and


it converts java style SQL queries into Database supported style SQL queries.
JDBC drivers are categorized into following.

o JDBC-ODBC bridge driver(type -1 driver)


o Native API driver (type-2 driver)
o Network Protocol driver (Type -3 driver)
o Thin driver (Type-4 driver)
JDBC-ODBC bridge driver(Type-1):
-> In Type-1 driver,JDBC Call is converted into ODBC Call and this ODBC call is
converted into Database Specific call for Connection.
DisAdvantage:

->Type-1 driver having more number of conversions and consumes more execution
time and degrades the performance.

-> we need to install Microsoft provided ODBC native library in our Machine.

->more conversion happens like Java to ODBC and from ODBC to database native.

->Type 1 driver is discontinued from java 8 version.


->ODBC Stands for 'Open DataBase Connectivity' and which is used to Convert Java
Calls(JDBC calls) into Native ODBC calls.

->ODBC is PlatForm dependent driver,becuase which internally having c/c++ code.

Native API driver(Type-2)

-> In Type-2 driver,the Client Machine is installed with DataBase related Libraries these
Libraries will Support Type-2 driver to convert JDBC calls into DataBase Specific calls for
connection.

DisAdvantage:

->In Type-2 driver the Application will become DataBase dependent application.

Network Protocol driver(Type-3):

-> In Type-3 driver,we make a call to MiddleWare-Server and this


MiddleWare Server will establish connection to DB product.
DisAdvantage

-> In Type-3 driver,more number of N/W components are participated in


execution process and increases the execution time and degrades the
performance of an application.
Thin driver(Type-4): (imp)
->This Type -4 driver is also called as Thin Driver or Pure Java Driver

->This is pure Java based driver

->It is most portable as compared to other 3 drivers Types.


->This type-4 driver not requires any middleware and all.

->We can use Type-4 driver for any kind of Java application development.

->it is Fast.

->here JDBC calls are converted into database specific calls directly.

->high performance driver.


->now we have already learn Oracle so in advance java we will use Oracle and
in spring boot we use Mysql.

->if you have not downloaded Oracle database software then first download
it.

->as you download Database we need its database jar file support to connect
with that database.

Every database comes with its jar file like Oracle

Oracle:-ojdbc.jar (version may different)

Mysql:-mysql-connector-java.jar (version may diff)


Postgresql:- postgresql.jar

Etc.

These Jar files is compressed format of Classes related to database.

Note:-DB Jar file is available at lib of Oracle product:


C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib
(in you case location may be different .. if unable to find then you can directly download
from internet also).

->Database Port and Service Name


->every database have its own port no and serviceName.

To know port no and service name of oracle open ‘tnsnames.ora’ file present
inside oracle folder .

Ex:- C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN (location depend on which drive


your oracle present)
DataBase API:

->'java.sql' is known as DataBase API or JDBC API,which provides related


classes and Interfaces used to develop JDBC Application.

->’java.sql.Connection’ is an interface and which is root of JDBC api.

These are some important method of Connection Interface


(a)createStatement()

(b)prepareStatement()

(c)prepareCall()

(d)setAutoCommit()

(e)getAutoCommit()

(f)commit()

(g)rollback()

(h)setSavepoint()

(i)releaseSavepoint()

(j)close()
->as we discuss ‘Connection’ is an interface and we also know that we can’t create
object for Interface .

->we can use ‘getConnection()’ method to create the implementation object of


‘Connection interface’.

->This getConnection() method is available from ‘java.sql.DriverManager’.

Method Signature of getConnection() method:


public static java.sql.Connection getConnection(java.lang.String,

java.lang.String,java.lang.String)throws java.sql.SQLException;
Types of Statements in JDBC:
=>Statements in JDBC are categorized into three types:

o 1.Statement
o 2.PreparedStatement
o 3.CallableStatement
Above three statements contains various method which helps us to deal with
database queries. Let see some imp methods.

Statement:
->'Statement' is an interface from java.sql package and which is used to
execute normal queries like create , insert , reterive (select), update and
delete by providing some method support.

These are some important methods from ‘Statement’ .

o executeQuery()
o executeUpdate()
o execute()

executeQuery():
->executeQuery() method is used to execute ‘select’ queries.
executeUpdate()
-> executeUpdate() method is used to execute Non-Select queries like
Create,Insert,Update and Delete.

Execute()
->execute() method can be used to execute any kind of sql statements ‘select’
as well as ‘non-select’.

Difference between these 3 methods:


Constructing JDBC Application Using IDE Eclipse:

Step 1:-Open IDE eclipse .select workspace and launch it.

Step2:-create java project

Click on File new projectjavajava projectclick nextname the


project click finish.

Step3:- add Database –jar libarary to our java project in our case (ojdbc).

Right click on projectbuild pathconfigure build pathlibrariesselect


classpathclick on ‘ add external jars’browser and select db jarapply and apply
close.

Step 4:- you are ready to construct program.

Task:- create a java program to fetch all records of employee table

Our db table

forName() is not needed since JDBC


4.0. In previous versions of JDBC, to
obtain a connection, you first had to
initialize your JDBC driver by calling
the method Class. forName.
ResultSet?

-> ResultSet is an interface from java.sql package and which holds the result
of 'select' query.

->executeQuery() method return the implementation object of ResultSet


interface. That object will hold select query result.

Following important methods of ResultSet


(i)getString()

(ii)getInt()

(iii)getFloat()

(iv)getLong()

(v)next()

next() method:

=>next() method move the cursor row-by-row on ResultSet object

=>return type of next() method is 'boolean'

=>next() method returns 'true' when record available,else returns 'false'


Task: create java program to insert data in employee table
->you can use finally block to close the connection.

PreparedStatement:
-> PreparedStatement is an interface from java.sql package and which is

also used to execute normal queries with IN Parameters.(which means

parameterized queries).

->it is the sub interface of statement interface used to execute parameterized


query.

->it is faster and performance wise improved then statement.

-> we use prepareStatement() method from 'Connection' interface to create

the implementation object of 'PreparedStatement' interface.

The following are two important methods of PreparedStatement interface:

(i)executeQuery()

(ii)executeUpdate()

executeQuery(): as we already discuss executeQuery() method is used to execute


select Queries.
syntax:

ResultSet rs = ps.executeQuery();

executeUpdate():

=>executeUpdate() method is used to execute Non-Select queries.


Task:-fetch employe details based on id

CallableStatement:
->'CallableStatement' is an interface from java.sql package and which is used
to execute 'Procedures and Functions' on DataBase product.

define Procedure?

=>procedure is a set-of-queries executed on DataBase product and after


execution it will not return any value.

->to execute procedure and function we will use execute() method. This
method is available in PreparedStatement only. internally CallableStatement
inherits PreparedStatemnt so it is available in it also.
create or replace procedure Proc_name

(para_list) is

begin

query1;

query2;

...

end;
/

define Function?

Function is a set-of-queries executed on DataBase and after execution it will


return the value.

Note:Functions in SQL will use 'return' statement to return the value after execution.
structure of Function:

create or replace function Func_name

(para_list)return data_type as var data_type;

begin

query1;

query2;

....

return var;

end;
/
Types of Procedures:

=>Procedures are categorized into two types:

(a) IN Parameter Procedures

(b) OUT Parameter Procedures

(a) IN Parameter Procedures:

=>The Procedures which take the data from JavaPrograms and update DataBase tables
are known as 'IN Parameter Procedures'.

->Note:- by default procedure and function parameter are ‘IN’ .

(b) OUT Parameter Procedures:

=>The Procedures which take the data from DB Tables and send to the Java Programs
are known as 'OUT Parameter Procedures'.

ex
define registerOutParameter() method?
->registerOutParameter() method specify the type of data recorded in
Parameter-Index-fields and registerOutParameter() method is available
from 'CallableStatement'.

Task: Construct and Execute function to retrieve


Function
Hierarchy of JDBC Statements:

Transaction Management in JDBC:


Define Transaction?

Transaction is a 'set of statements' executed on a resource or resources, by


applying ACID properties.
A-Atomicity

C-Consistency

I-Isolation

D-Durability:

A-Atomicity
=>The process of Commiting the Transaction after completing all the
"SubStatements execution",is known as Automicity.

Note:

=>Any operation on database must be atomic,which means it must happen


entirely or not at all.

C-Consistency

=>The resources which are selected for Transaction will be same until the
transaction is completed is known as Consistency.
I-Isolation

=>The process of running the Transaction independently is known as


Isolation.
D-Durability:

=>Once the transaction is commited,the details of Transaction is stored and


available for the user,is known as Durability.

define Transaction Management?


->In simple and short words The process of controlling transaction from
starting to ending of transaction is known as Transaction Management.

->To deal with the transcation management we use the following methods
from ‘java.sql.Connection’ interface .

o setAutoCommit()
o getAutoCommit()
o commit()
o rollback()
o setSavepoint()
o releaseSavepoint()
setAutoCommit():- actually java application will perform commit operation
automatically . so by using this method we can set it to false.

getAutoCommit():-This method is used to know the status of commit


operation.
Commit():-we use commit method to update data from instance buffer to
database to store permanently.

Rollback():-we use rollback() method to get original state of buffer when the
transcation failed. We specify the rollback operation using savepoint.

setSavepoint():-This method is used to set savepoint for rollback operation.

releaseSavepoint():This method is used to delete save point from the buffer.

Task:-transfer amount from one customer account to another customer


account.
Connection Pooling in JDBC:

-> The process of organizing pre-initialized DataBase connections among


multiple users is known as Connection Pooling.

->In connection pooling the users take connection from the pool and uses
that connection to perform some operations and return connection to the
pool.

Batch Processing in JDBC:

-> The process of collecting multiple queries as a batch and executing


onDataBase product is known as 'Batch Processing in JDBC'.

Batch Processing using ‘statement’


=>we use the following methods from 'java.sql.Statement' to perform 'Batch Processing':

(a)addBatch()

(b)executeBatch()

(c)clearBatch()
1) addBatch():
=>This method is used to add the query to the batch.
Method Signature:

public abstract void addBatch(java.lang.String)throws java.sql.SQLException;

syntax:

stm.addBatch("query");

2) executeBatch():

-> This method is used to execute batch on DataBase Product.


Method Signature:

public abstract int[] executeBatch() throws java.sql.SQLException;

syntax:

int k[] = stm.executeBatch();

3) clearBatch():

-> This method is used to delete(clear) the batch.


Method Signature:

public abstract void clearBatch() throws java.sql.SQLException;

syntax:

stm.clearBatch();
Batch Processing using 'PreparedStatement'

->we use the following methods to perform Batch processing using


PreparedStatement.
(a)addBatch() - PreparedStatement

(b)executeBatch() - Statement

(c)clearBatch() - Statement
Note:

->'Batch Processing using Statement' we can update multiple DB tables.

->'Batch Processing using PreparedStatement' we can update same DB Table.


Batch processing executes all the queries from batch, in this process execution time is
saved and generate high-performance of an application.

->batch processing is also know as batch update processing.

Note:-using batch processing we cannot perform ‘select’ operation, but we


can perfrom create,insert,update and delete.

Note: using procedure we can perform all DB operation like


select,insert,update and delete.

ResultSet
->based on Control over the cursor, the ResultSet Object are
Categorized into two types.
o Non-Scrollable ResultSet Object.
o Scrollable ResultSet Object.
Non-Scrolable ResultSet Object:-
->In this non-scrollable resultset Object the cursor is moved only in
One direction, which means the cursor moves from top-of the table
data to bottom-of the table data.(Top-Bottom)
Scrollable ResultSet Object:-
->In Scrollable ResultSet Object the cursor can be moved in two
directions , which means top to bottom of the table data and bottom
to top table data.
Note:-we use scrollable resultSet with statement & prepared
statement.
Ex:-
Ex:-Statement stm = con.createStatement(type,mode);
Ex:-PreparedStatement ps = con.prepareStatement("query",type,mode);

Ex:-
Type:
public static final int TYPE_FORWARD_ONLY=1003

public static final int TYPE_SCROLL_INSENSITIVE=1004

public static final int TYPE_SCROLL_SENSITIVE=1005

Mode:
public static final int CONCUR_READ_ONLY=1007

public static final int CONCUR_UPDATABLE=1008

Note:

'type' specifies the direction of the cursor and 'mode' specifies the
action to be performed(read or update).
The following are some Methods used to control cursor on Scrollable
ResultSet object:

afterLast() =>Moves the cursor after the Last row

beforeFirst() =>Moves the cursor before the First row

previous() =>Moves the Cursor in the BackWard Direction


next() => Moves the cursor in the ForWard Direction
first() => Moves the cursor to the First row
last() => Moves the cursor to the Last row
absolute(int)=>Moves the cursor to the specified row number
relative(int)=>Moves the cursor from the current position in forward or backward
direction by increment or decrement.
SERVLET PROGRAMMING

->In simple terminology we can say a independent java program running in


server environment and accepting the request from the client through
webbrowser is know as “servlet programming”

Server:- server is also a code running on different machine or in same


machine (localhost) which accepts the request from the client and generating
response.

Web Applications:

->The applications which are executing in Web Environment or Internet

Environment are known as Web Applications.


->we use servlet to create controller of the web-application.

->These Web Application are executed in ‘Web Container’.

->WebContainer is available from WebServers and Application Servers.

->Web Container internally has two SubContainers.

1. Servlet Container. (Catelina)

2. JSP Container.(Jasper)

Installing Tomcat Server


Step1.Download tomcat9.xx version which is compatable with jdk1.8 and
above.

Step2:- install tomcat server.

Step3:-start the tomcat server.


Goto 'bin' and Click on 'startup' or 'Tomcat9w' to start the Tomcat Server

step-4 : Check the Tomcat Server is responding to WebBrowser or not,using

the following address: http://localhost:8081


Step5:-to stop it goto ‘bin’ and click on ‘shutdown’.
Servlet API
->”javax.servlet” package is the Servlet Api.

->”javax.servlet.Servlet” interface is the root of Servlet API.

->The Following are the methods from “Servlet” interface.


Note:- if you are using recent version then you will get
o Init()
all this inside jakarta package.
o service()
Note:- you can you any version it’s upto you . try to
o destroy()
understand concepts version may be change in time
o getServletConfig() but concepts always remain same go with concepts ..
o getServletInfo()
Note:-init(),service() and destroy() methods are the Life-cycle methods and
executed automatically in the same Order.
-> In the process of Constructing ServletProgram the user defined class must be
implemented from 'Servlet' or extended from 'GenericServlet' or extended from
'HttpServlet'.

Steps to create First Servlet Program which implements Servlet Api

Step1:- Open eclipse IDE select workspace and launch .

Step2:-create dynamic web project.

File->new ->dynamic web project and click on next->name the project and finish.

If dynamic web project option is not displaying directly then

File->new->project->web->dynamic web project->name the project and finish.


Step3:- add Servlet-api.jar because we are creating servlet program.All Servlet related
predefined classes and interface available in that jar.

->select project go to build path ->configure build path->liberaries->add external jar.

->go to tomcat folder (in my case it is installed in c drive) and select Lib folder inside that
select servlet-api.jar file.
Note:- while adding
servlet-api.jar file .
please take care that if
you are getting option of
class path inside libraries
then you need to select
class path and add there
.in my case no classpath
inside libraries so using
directly

Now we have added servlet api in our project we are ready to create servlet
program.

Step4:- Now we need to add Tomcat server to Eclipse IDE because servlet is
a server side program to execute it we need server environment .

->select console and choose server option and click on given blue link.
Select tomcat9

->now select tomcat folder (in my case it is present in c drive)

Step5:-now to execute program just right click and run as server.


Run:- http://localhost:8081/Servlet_App1/xyz
Explanation:-

->above diagram is explaning every thing.this big box is web container means as we run
our program web container came into picture. Inside webcontainer lots of object are
created few are most important to understand.

As webcontainer started ServletContext object is created which holds server


information.
->after that our servlet program loads and as our servlet program loads one
ServletConfig object created which hold our Servlet information like name and all. And
now our servlet execution started . as we know in our servlet init(),service(),destroy()
methods are servlet life-cycle method which invokes automatically.and two more new
object will be created i.e request, response ...all these work will be done by web
container just we need to use it.

ServletContext:

=>ServletContext is an interface from 'javax.servlet' package and which is

instantiated automatically when the web App is deployed into Server.

=>This ServletContext object is loaded with Server Information.

ServletConfig:

=>ServletConfig is an interface from 'javax.servlet' package and which is

instantiated automatically when the Servet program is loaded for execution.

=>This ServletConfig object is loaded with Servlet_name


ServletRequest:

=>ServletRequest is an interface from 'javax.servlet' package and which is

instantiated automatically while service() method execution.

=>This ServletRequest object will hold the data submitted from HTML forms.
ServletResponse:

=>ServletResponse is an interface from 'javax.servlet' package and which is

instantiated automatically while service() method execution.

=>ServletResponse object will hold the data which we sending as


output(response).

define getWriter() method?

->getWriter() method is available from ‘ServletResponse’ and which is used to


create object for PrintWriter class.
syntax:

PrintWriter pw = res.getWriter();

->this PrintWriter object is internally linked to ServletResponse object.

setContentType() method ?

->this method is available in ‘ServletResponse’and which specify the type of


data sending as response.
syntax:

res.setContentType("text/html");

program2:-Read data from html form

create html file in webcontent folder.

->now create servlet program which accept request came from this form submittion.

Note:- it is mandatory to provide “name” attribute in form elements . because based on


that only we catch form element in servlet program.
->in servlet program we use printwriter object and use it’s println() method to send
response.

What is getParameter() method?


->getParameter() method is from 'ServletRequest' and which is used to get the

data from ServletRequest object into Servlet program.


Syn:- String val = req.getParameter("para_name");
Note:
=>Servlet-url-pattern is holded by
o (i)Annotation ex:- @WebServlet("/url-pattern")
o (ii)xml file(web.xml)

As off now we have created one servlet program by implementing Servlet. Means by
using ‘javax.servlet.Servlet’ interface. But this interface is not preferable because the
objects are Not-Serializable which means Object cannot travel over network.

->The limitation of ‘Servlet’ interface can be Overcomed using ‘GenericServlet’ and


‘HttpServlet’.

->The Object generated through GenericServlet & HttpServlet are serializable.

Constructing Servlet programs using 'GenericServlet'

GenericServlet program..
RequestDispatcher
->RequestDispatcher is an interface from ‘javax.servlet’ package and which
provides the following methods to establish communication b/w servlet
programs.

Methods of requestDispatcher.

o forward()
o Include()
Note:- RequestDispatcher is an interface which means we cannot create it’s object .

->We use ‘getRequestDispatcher()’ method from ‘ServletRequest’ interface to create


the implementation object of ‘RequestDispatcher’ . getRequestDispatcher() method is
factory method.

Method Signature of getRequestDispatcher():


Public abstract RequestDispatcher getRequestDispatcher(java.lang.String);

Syn:-

Forward Communication Process.


->in simple words in forward communication process FirstServlet will take the request
and Forward the request to the SecondServlet. In this process the response is
generated by second servlet.

->The second servlet can also be replaced with JSP file or HTML file.

->we use forward() method from RequestDispatcher to establish forward


communication.

syn
RequestDispatcher rd = req.getRequestDispatcher("html/jsp/servlet");

rd.forward(req, res);
Include Communication process:
->in simple words in include communication process the response is
generated from FirstServlet , but the generated response is added with the
response of secondServlet .

->in place of second servlet jsp/html can be used.


->we use include() method from RequestDispatcher to perform

include communication process.

syntax:

rd.include(req,res);
Ex_Application:(Demonstrating forward() and include() methods)

->
ServletContext:
->ServletContext is an interface from javax.servlet package and which is
instantiated automatically when application is deployed.
->there is only one ServletContext object per web application.

->if any information is shared in many serrvlet then servlet context is better
place.

->The information in ServletContext object can be used by all the servlets in


the web application.

->we use getServletContext() method to access ServletContext Object.

->this getServletContext() method is available from GenericServlet ,


ServletRequest , ServletConfig and HttpSession.

Method Signature of getServletContext() from ServletRequest:


syntax:

ServletContext sct = req.getServletContext();


=>we use <context-param> tag in web.xml to intialize parameter-values to

ServletContext object.

=>we use 'getInitParameter()' method to access initialized parameter from

the ServletContext object.


syntax:

String var = sct.getInitParameter("para_name");

ServletConfig:
=>ServletConfig is an interface from 'javax.servlet' package and which is

instantiated automatically when the Servlet program is loaded on to Web

Container for execution.


=>This ServletConfig object is loaded with Servlet_name.

=>Every Servlet program will have its own ServletConfig object.

=>we use getServletConfig() method to access ServletConfig object into

Servlet program.

=>This getServletConfig() method is available from 'GenericServlet'.


syntax:

ServletConfig sc = this.getServletConfig();

=>we use <init-param> sub-tag part of <servlet> tag to initialize

parameter-values into ServletConfig object.

syntax:
wt is the diff b/w
o (i)getParameter()
o (ii)getInitParameter()

=>getParameter() method is used to access the parameters from


ServletRequest

object.

=>getInitParameter() method is used to access the parameters from

ServletContext and ServletConfig objects.


"attribute" in Servlet programming:
=>"attribute" is a variable in Servlet programming which can be added to
ServletContext object , ServletRequest Object and HttpSession object.

->There are some methods related to ‘attribute’.

o setAttribute()
o getAttribute()
o removeAttribute()
setAttribute():- this method is used to set data (attribute) to the objects like

HttpSession,ServletContext,ServletRequest from java code

instead of web.xml.

getAttribute():-This method is used to get the attribute from the objects.

removeAttribute():-This method is used to remove attribute from the object.


Scopes of Attributes

o ‘attribute’ in ServletContext can be used by all the servlets in web


application.
o ‘attribute’ in ServletRequest of one servlet is available to next Servlet
program in forward communication process.
o ‘attribute’ in HTTPSESSION is available from session start to end.(ex:-
login,logout).

DAO(Data Access Object) Layer:


=>DAO stands for Data Access Object and which is separate layer in MVC

(Model View Controller) to hold DataBase related operations like Connection,

create,Select(retrieve),insert,update and delete.

Task:- create one web application includes database and complete flow.
HttpServlet
->HttpServlet is an abstract class from ‘javax.servlet.http’ package.
This is protocol dependent (HTTP protocol dependent).
->as we know we have Servlet,GenericServlet and now HttpServlet
..so like wise others we need to extend our servlet with HttpServlet .
->HttpServlet provides method like doPost() , doGet()..etc.

define request?

=>The query which is generated from user through WebBrowser is known as


'request'.

-> request is categorized into two types:


o 1.POST request
o 2.GET request

POST request:

->The request which is used to post(send) the data to the Server is known as POST
request. The Post request is generated by declaring method=”POST” on form tag.

syntax:

<form action="url" method="post">

</form>

->we use doPost() method from "javax.servlet.http.HttpServlet" interface to hold POST


request.

-> Through POST request we can send any type of data (Text,Audio,Video,Image and
Animation) and UnLimited data.

-> The data which is sent through the POST request is secured.
GET request:
->The request which is used to get the data from the Server is known as GET request.

The GET request is generated in the following ways:


1. By declaring method="GET" in <form> tag of HTML file.

syntax:

<form action="url" method="GET">

....

</form>

2. By using Hyper Link ex:- <a href="index.jsp">NewUser?</a>

3. By using url-pattern in address bar

Exp:

http://localhost:8082/codemines/abc

4. Submit the HTML form without declaring "method" attribute


syntax:

<form action="url">

</form>

-> we use doGet() method from "javax.servlet.http.HttpServlet" interface to hold GET


request.

Note:
->Through GET request we can send only text data and we can send only limited data
upto few kb.(Based on Browser).

-> The data which is sent through the GET request is NotSecured because which is
attached to the query-string and display in the address bar.
Session Tracking /session management
->session tracking is a way to maintain state(data) of an user . in simple word
process of tracking the status of user from login to logout is know as session
tracking.
->following are the techniques used in session tracking.

o URL Re-writing.
o Hidden Form Fields
o Cookie (imp)
o HttpSession (imp)
->session tracking technique are used to send the information from one
servlet to another servlet in the process of Tracking users.

Url Re-Writing :
=>The process of adding parameter-values to the url-pattern is known as

URL Re-Writing process.

Syn

url-pattern?para1_name=value&para2_name=value&para3_name=value&...

ex

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="firstServlet" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
@WebServlet("/firstservlet")

public class FirstServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

String uName = req.getParameter("uname");

String mId = req.getParameter("mid");

long phNo = Long.parseLong(req.getParameter("phno"));

pw.println

("<a href='secondservlet?uname="+uName+"&mid="+mId+"&phno="+

phNo+"'>ViewInfo</a>");
}

@WebServlet("/secondservlet")

public class SecondServlet extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

pw.println("UserName:"+req.getParameter("uname"));

pw.println("<br>MailId:"+req.getParameter("mid"));

pw.println("<br>PhoneNo:"+req.getParameter("phno"));}}
Hidden Form fields:
->The process of declaring <input type="hidden"> in form tag of HTML is known as
Hidden Form Field.

->The data in Hidden form fields are not displayed to the End-Users.Using these Hidden
form fields we can send information from one Servlet to another Servlet.
input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="firstservlet" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

@WebServlet("/firstservlet")

public class FirstServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

String uName = req.getParameter("uname");

String mId = req.getParameter("mid");

long phNo = Long.parseLong(req.getParameter("phno"));

pw.println("<form action='secondservlet' method='post'>");

pw.println

("<input type='hidden' name='uname' value='"+uName+"'>");

pw.println("<input type='hidden' name='mid' value='"+mId+"'>");


pw.println("<input type='hidden' name='phno' value='"+phNo+"'>");

pw.println("<input type='submit' value='ViewInfo'>");

pw.println("</form>");

@WebServlet("/secondservlet")

public class SecondServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

pw.println("UserName:"+req.getParameter("uname"));

pw.println("<br>MailId:"+req.getParameter("mid"));

pw.println("<br>PhoneNo:"+req.getParameter("phno"));

Cookie
->The small piece of information available b/w multiple client request is know as
‘Cookie’.

->The Cookie is Stored in WebBrowser to track the user or client.

->we use ‘javax.servlet.http.Cookie’ class in creating cookie.

How Cookie Works


->By default, each request is considered as a new request. In Cookies technique. We
add cookie with response . So cookie get stored in the browser. After that if any request
is sent by the user, Cookie is added with request by default. Thus our server program
can easily recognize that the user is a old user.
The following are some important methods from Cookie class:

public void setMaxAge(int); -set maximum age of the cookie in seconds.

public int getMaxAge();- help to get maximum age of cookie.

public void setValue(java.lang.String);-changes or set the value of cookie.

public java.lang.String getValue();- return the value of cookie.

public java.lang.String getName();- return the name of the cookie.

We use the following steps in cookie Session Tracking process:

step-1 : Creating cookie by creating object for 'Cookie' class as follows:


Cookie ck = new Cookie("name","value");

step-2 : Add the Cookie to the response using addCookie() method

res.addCookie(ck);
NOTE:- This addCookie() method is available from 'HttpServletResponse'.

step-3 : Get cookies from the request object using getCookies() method
Cookie c[] = req.getCookie();

NOTE:-this getCookies() methods is available from ‘HttpServletRequest’.

step-4 : Invalidating cookie


->We can invalidate cookie by setting maxAge as zero
ck.setMaxAge(0);

ex:-
HttpSession:
->HttpSession is an interface from javax.servlet.http package and which is used to
transfer the information from one Servlet to another Servlet .

->Following are some important methods of HttpSession

public abstract void setAttribute(java.lang.String,java.lang.Object);

public abstract java.lang.Object getAttribute(java.lang.String);

public abstract void removeAttribute(java.lang.String);

public abstract void putValue(java.lang.String,java.lang.Object);

public abstract java.lang.Object getValue(java.lang.String);

public abstract void removeValue(java.lang.String);

public abstract void invalidate();

Note:

=>we use getSession() method from 'HttpServletRequest' to create the

implementation object of 'HttpSession' interface.

syntax-1:

HttpSession hs = req.getSession( );
=>In this syntax it checks the session object is available or not,

=>if avialble access the existing session object reference.

=>if Not-Available then create new session object.

=>No parameter in this because it will create fresh session object.

syntax-2:

HttpSession hs = req.getSession(false);
=>In this syntax it checks the session object is available or not,

=>if avialble access the existing session object reference


=>if Not-Available then don't create new session object

=>this method is having parameter flase. Means it will help to get session which is already available and if not
available then it will create new one.
Every session will have SessionID. And Session ID is a unique number, server assigns to a specific user,
during his visit(session). And defaultely, session ID is attached to a cookie and this cookie will be shared
from client to server (and server to client) during its requests/responses. And server will identify session
based on session id which is retrieved from cookie.

Filters in Servlet programming:


->Filter is a pre-processing componentand which is executed before Servlet
Program.

->Filters are used to get information from incoming requests.

->Filter are used to pre-process the request a/c to business requirement.

->Filter can also be used for encryption and decryption.

->Filters can be used to validate requests data.

=>The following are the components used in Constructing Filter Programs:


1.Filter

2.FilterChain

3.FilterConfig

1. Filter:

=>Filter is an interface from javax.servlet package and which is implemented to user


defined class in the process of constructing filter program.

->The following are the Life-Cycle methods of Filter:

o Init()
o doFilter
o destroy

2. FilterChain:

->This doFilter() method of FilterChain is used to extablish link b/w Filter


program to Servlet program.

->FilterChain is an interface from javax.servlet package and which is


instantiated automatically while executing doFilter() method from "Filter"
interface.
3. FilterConfig:
->FilterConfig is an interface from javax.servlet package and which is
instantiated automatically when Filter program loaded for execution.

->This FilterConfig object will hold filter name.

Note:
=>The Filter program is mapped using Annotation or web.xml

Case-1 : We use the following syntax in annotation

@WebFilter("/url-pattern")

Case-2 : we use the following structure of web.xml to map Filter program


<web-app>

<filter>

<filter-name> name </filter-name>

<filter-class> class </filter-class>

<init-param>

<param-name> name </param-name>

<param-value> value </param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name> name </filter-name>

<url-pattern> /url </url-pattern>

</filter-mapping>

</web-app>
Servlet Collaboration process?
->in simple process of exchanging information b/w Servlet programs is know as Servlet
Collaboration process.

->The servlet Collabroation process can be done in two ways.

o Using ‘RequestDispatcher’
o Using ‘sendRedirect() ‘ method.
(a) using 'RequestDispatcher':

->'RequestDispatcher' is used to establish communication b/w Servlet

programs available in same WebApplication.

->as we already discussed This 'RequestDispatcher' privide the following two


methods to perform

Communication process:

(i)forward() - forward communication process

(ii)include() - include communication process

(b) Using 'sendRedirect() method':

->using sendRediect() method is used to establish communication b/w Servlet Program


running in different web application.

->in this web application are executed in same webserver or different webserver.

->this is available in ‘HttpServletResponse’.

syntax:

res.sendRedirect("http://. ........ ");

ex
Note:- server make use of browser and redirect to that URL.
Note:-When we use RequestDispatcher the same Old request is
forwarded to next Servlet Program in communication process.
Note:-When we use sendRedirect() method then app1 will take help
of browser and generate new request to app2.
Some important Annotations in Servlet Programming:

->we have used lots of annotation in our servlet like


o @WebServlet
o @WebFilter
o @WebListener

(i) @WebServlet

->This @WebServlet annotation will hold url-pattern and provide information to


execution_control to map Servlet program for execution.

(ii) @WebFilter

->This @WebFilter annotation will hold url-pattern and provide information to


execution_control to map Filter program for execution.

(iii) @WebListener

->This @WebListener annotation will provide information to execution_control to map


Listener program for execution.

Servlet Life-cycle
->in real life also every one have there life cycle which means from starting stage to end
stage. Similarly Servlet life-Cycle defines different state of Servlet program from Starting
to Ending of Servlet Program.

following are the stages of Servlet Life-Cycle:

o Loading process
o Instantiation process
o Initialization process
o Request handling process
o Destroying process.
1. Loading Process:- process of identifying the servlet program based on URL-pattern
and loading in WebContainer is know as Loading Process.

2. InstantiationProcess:-Once Servlet program loaded into webContainer, it is


instantiated automatically .(creating object for servlet program).

->after instantiation process we can identify the following life-cycle methods.

GenericServlet:

(i)init()

(ii)service()

(iii)destroy()

HttpServlet:

(i)init()

(ii)doPost()/doGet()

(iii)destroy()

Filter:
(i)init()

(ii)doFilter()

(iii)destroy()

3. Initialization Process:- process making the programming component ready which can
be used by following methods like service(),doPost(),doGet(),doFilter().

->This initialization process is performed using init() method.

Note:

->init() method executes only once in the process of executing Life-Cycle

4. Request Handling process:

=>The process of executing service()/doPost()/doGet()/deFilter() method to

handle the request is known as Request Handling process.


Note:

->service() method is executed for all the multiple requests generated from Multiple
users.

5. Destroying process:

->After service() method execution,the destroy() method is executed to destroy the


instances of Servlet program.

JSP Programming:(Part-3)
->JSP stands for ‘Java Server Page’ and which is response from web-
application.

->JSP is tag based programming language and which is more easy when
compared to Servlet Programming.

->we need to save JSP file with .jsp extension.

->in more simple words you can say JSP program are combination of both
HTML code and JAVA code.

->JSP provides various tags to write java code part of JSP program.
1. Scripting tags
o Scriptlet tag
o Expression tag
o Declarative tag

2. Directive tags
o Page
o Include
o Taglib

3. Action tags
o Jsp:include
o Jsp:forward
o Jsp:param
o Jsp:useBean
o Jsp:setProperty
o Jsp:getProperty

1. Scripting tags
->it is used to write java code as part of JSP program.

->it is categorized into following tags Scriptlet tag , Expression


tag,Declarative tag.

(a) Scriptlet tag:

->Scriptlet tag is used to write normal Java Code part of JSP programs.

syntax:

<% ---JavaCode--- %>

(b) Expression tag:

->Expression tag is used to assign the value to variable or which is used to display the
data to the WebBrowser.
syntax:

<%= expression %>

(c) Declarative tag:


->Declarative tag is used to declare variables and methods in JSP programs.

syntax:

<%! variables;methods %>

2. Directive tags:
-> The tags which are used to specify the directions in translation process are known as
Directive Tags.

->this tag is categorized in page,include,taglib.

(a) page:

->'page' directive tag specifies the translator to add the related attribute to current JSP
page.
syntax:

<%@ page attribute="value" %>


exp:

<%@ page import="java.util.*"%>

List of attributes:

1.import

2.contentType

3.extends

4. info

5.buffer

6.language

7.isELIgnored

8. isThreadSafe
9. autoFlush

10.session

11.pageEncoding

12.errorPage

13.isErrorPage

(b) include:

->'include' directive tag specifies the file to be included to current JSP page.

syntax:

<%@ include file="file-name"%>

Exp:

<%@ include file="input.html" %>

(c) taglib:

->'taglib' directive tag specifies to add specified url to current JSP page and which is used
part of EL(Expression Lang) and JSTL (JSP Standard Tag Lib).

syntax:

<%@ taglib url="urloftaglib" prefix="prefixoftaglib"%>

Ex:-
The following are the implicit objects generated in JSP programming:

JSP name Servlet name

1. application - javax.servlet.ServletContext

2. config - javax.servlet.ServletConfig

3. request - javax.servlet.http.HttpServletRequest

4. response - javax.servlet.http.HttpServletResponse

5. out - javax.servlet.jsp.JspWriter

6. session - javax.servlet.http.HttpSession

7. exception - java.lang.Throwable

8. page - java.lang.Object

9. pageContext - javax.servlet.jsp.PageContext
3. Action tags:

->Action Tags are used to include some basic actions like inserting some other page
resources ,forwarding the request to another page, creating or locating the JavaBean
instances and,setting and retriving the bean properties in JSP pages.
Note:

->These action tags are used in Execution process at runtime.

=>The following are some Important action tags available in JSP:


1.<jsp:include>

2.<jsp:forward>

3.<jsp:param>

4.<jsp:useBean>

5.<jsp:setProperty>

6.<jsp:getProperty>

1. <jsp:include> :

->This action tag allows to include a static or dynamic resource such as HTML or JSP
specified by a URL to be included in the current JSP while processing request.

-If the resource is static then its content is included in the JSP page.

->If the resource is dynamic then its result is included in the JSP page.

attributes of include tag:

page : Takes a relative URL,which locates the resource to be included in the JSP page.

<jsp:include page="/Header.html"/>

<jsp:include page="<%=mypath%>"/>

2. <jsp:forward>:

-> This action tag forwards a JSP request to another resource and which can be either
static or dynamic.

->If the resource is dynamic then we can use a jsp:param tag to pass name and value of
the parameter to the resource.
Exp:

<jsp:forward page="/Header.html"/>

<jsp:forward page="<%=mypath%>"/>

3. <jsp:param>:

->This action tag is used to hold the parameter with value and which is to be forwarded
to the next resource.

4. <jsp:useBean>:

=>This tag is used to instantiate a JavaBean,or locate an existing bean instance and
assign it to a variable name(id).
syntax:

<jsp:useBean attributes>

<!-optional body content--->

</jsp:useBean>

Attributes of <jsp:useBean> tag:

(a)id

(b)scope

(c)class

(d) beanName

(e)type

(a) id:

->which represents the variable name assigned to id attribute of <jsp:useBean> tag and
which holds the reference of JavaBean instance.

(b) scope:

=>which specifies the scope in which the bean instance has to be created or located.
scope can be the following:

(i)page scope : within the JSP page,until the page sends response.

(ii)request scope : JSP page processing the same request until a JSP sends response.

(iii)session scope - Used with in the Session.

(iv) application scope - Used within entire web application.

(e) type :

->The "type" attribute takes a qualified className or interfaceName, which can be the
classname given in the class or beanName attribute or its super type.

5. <jsp:setProperty>:

->This action tag sets the value of a property in a bean, using the bean's setter methods.

Types of attributes:

(a)name

(b)property

(c)value

(d)param

(a) name:

->The name attribute takes the name of already existing bean as a reference variable to
invoke the setter method.

(b) property:

->which specifies the property name that has to be set,and specifies the setter method
that has to be invoked.

(c) value:

->The value attribute takes the value that has to be set to the specified bean property.

(d) param:

->which specify the name of the request parameter whose value to be assigned to bean
property.
6. <jsp:getProperty>:

->This action tag gets the value of a property in a bean by using the bean's getter
method and writes the value to the current JspWriter.

Types of attributes:

(a) name

(b)property

(a) name:

->The name attribute takes the reference variable name on which we want to invoke
the getter method.

(b) property:

->which gets the value of a bean property and invokes the getter method of the bean
property.

Demonstrating <jsp:useBean>,<jsp:setProperty> and<jsp:getProperty>


Web Architecture Models:(Web Application Architectures)

Two types of development models are used in Java for Web applications, and these
models are classified based on the different approaches used to develop Web
applications.

These models are:

1. Model-1 Architecture

2. Model-2 Architecture(MVC)
1. Model-1 Architecture:

The Model-1 architecture was the first development model used to develop Web
applications and this model uses JSP to design applications and, which is responsible for
all the activities and functionalities provided by the application.

Limitations of the Model-1 Architecture:

(i).Applications are inflexible and difficult to maintain. A single change in one page may
cause changes in other pages, leading to unpredictable results.

(ii).Involves the developer at both the page development and the business logic
implementation stages.

(iii).Increases the complexity of a program with the increase in the size of the JSP page.

2. Model-2 Architecture (MVC model)

->The draw backs in the Model-1 architecture led to the introduction of a new model
called Model-2. this Model-2 architecture is based on the MVC design model.
->MVC Stands for Model View Controller.

Model: Represents enterprise data .

View: Shows the contents of a Model.The View component accesses enterprise data
through the Model component and specifies how that data should be presented and this
View Component is designed by JSP.

Controller: Receives HTTP requests. The Controller component receives requests from a
client, determines the business logic to be performed, and delegates the responsibility
for producing the next phase of the user interface to an appropriate view component.

Advantages of Model-2 Architecture:

->Offers great flexibility to the presentation logic, which can be modified without
effecting the business logic.

Expression Language(EL) in JSP:


->This EL simplifies the accessibility of data stored in java Bean component and other
objects like request,session,application,etc..

Note: It is newly added feature in JSP technology.

syntax of EL:

$(expression)

The following are the implicit objects of EL:


pageScope : It maps the given attribute name with the value,set in the page scope

requestScope : It maps the given attribute name with the value set in the request
scope.

sessionScope : It maps the given attribute name with the value set in the session scope.

applicationScope : It maps the given attribute name with the value set in the application
scope.

param : It maps the request parameter to the single value

paramValues : It maps the request parameters to the array of values.


header : It maps the request header name to the single value.

headerValues : It maps the request header names to the array of values.

cookie :It maps the cookie name to the cookie value.

initParam : It maps the Initialization parameter .

pageContext : It provides access to many objects request,session,...

Note:
->we use "taglib" directive tag to declare JSTL Tags.

->To Execute JSTL Tags we use the following steps:

(i) Download the following Jar files to execute JSTL tags

javax.servlet.jsp.jstl-1.2.1.jar

javax.servlet.jsp.jstl-api-1.2.1.jar

(ii) These jars must be available within 'lib' folder of 'WEB-INF' in deployment directory

(1)Core Tags:

->These JSTL core tags provides variable support,URL management, flow control etc.
(Basic code writing)

syntax:

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

The following are the List of JSTL Core Tags:

c:out ->It displays the result of an expression, similar to

<%=...%> tag.

c:import->It Retrives relative or an absolute URL.

c:set-> It sets the value to variable.

c:remove->It is used for removing the variable .


c:catch-> It is used for Catching any Throwable exception that occurs in the body.

c:if-> It is an conditional tag

c:choose, c:when, c:otherwise->

It is the simple conditional tag that includes its body content

if the evaluated condition is true.

*imp

c:forEach-> It is the basic iteration tag.

c:redirect-> It redirects the browser to a new URL and supports the

context-relative URLs.
JSP LifeCycle:
->JSP LifeCycle demonstrates diff states of JSP program from Starting of the program to
the ending of the program.

->The following are the states of JSP program in LifeCycle:

(1) Translation process

(2)Compilation process

(3)Loading process

(4)Instantiation process

(5)Initialization process

(6)Request Handling process

(7)Destroying process

(1)Translation process:
->The process of separating JavaCode from JSP program is known as Translation process.

->After translation process SourceCode is generated.

(2) Compilation process:

=>The process of compiling the SourceCode and generating the ByteCode is known as
Compilation process.

(3) Loading process:

->The process of loading the JSP program for execution is known as Loading process.

(4) Instantiation process:

=>The process of creating object for JSP program is known as Instantiation process.

=>After Instantiation process we can find the following implicit


lifeCycle methods:

(i)_jspInit()

(ii)_jspService()
(iii) _jspDestroy()

(5) Initialization process:

=>The process of making the programming components ready for service

is known as Initialization process.

(6) Request Handling process:

=>The process of handling the request and giving the response is

known as Request Handling process.

(7) Destroying process:

=>The process of destroying the instances from the WebContainer is

known as Destroying process.

Listeners in Servlet Programming:


=>The Component which is executed background to the Servlet Objects when the
action(event) is performed on the objects, is known as Listener.

define Event-Deligation-Process?

=>when the event is performed on Source Object then the related Listener is executed
automatically and handles the event by executing related method.

=>In the process of adding listeners to Servlet program we consider the

1. Source Object

2. Event Class

2. Listener

3. Methods
Source Object : ServletContext object

Event Class : ServletContextEvent

Listener : ServletContextListener

Methods : contextInitialized(),contextDestroyed()

Source Object : ServletRequest Object

Event Class : ServletRequestEvent

Listener : ServletRequestListener

Methods : requestInitialized(),requestDestroyed()
Source Object : HttpSession Object

Event Class : HttpSessionEvent

Listener : HttpSessionListener

Methods : sessionCreated(),sessionDestroyed()

Eclipse configuration (in recent version)

If you are using recent version eclipse then you won’t get webcontent folder
you will get webapp so you need to put all your html,jsp ..etc in webapp
only.

And while adding servlet-api.jar please take care of classpath option.

You might also like