You are on page 1of 48

Class.

forName(--) and newInstance()


------------------------------------
public static Class forName(String class_Name)throws ClassNotFoundException
-->To load class bytecode to the memory and to get metadata of the respective class
in the form of java.lang.Class object.

public Object newInstance() throws InstantiationException, IllegalAccessException


--> To crerate object for the loaded class by executing non-private and 0-arg
constructor.
EX:
---
class A
{
static
{
System.out.println("Class Loading");
}
A()
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args)throws Exception
{
Class c=Class.forName("A");
Object obj=c.newInstance();

}
}

Dynamic Input Approaches:


--------------------------
1.BufferedReader
2.Scanner
3.Console

1.BufferedReader
-----------------
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

EX:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Text Data :");
String data=br.readLine();
System.out.print("Enter the same text data again :");
int val=br.read();
System.out.println("First Entered :"+data);
System.out.println("Second Entered :"+val+"["+(char)val+"]");
}
}
Note: If we want to take primitive data as dynamic input through BufferedReader
then we have to use wrapper classes explicitly.
a)Read primitive data in the form of String by using readLine() method
b)Convert data from String type to the respective primtive data type.

EX:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("First Value :");
String data1=br.readLine();
System.out.print("Second Value :");
String data2=br.readLine();
int val1=Integer.parseInt(data1);
int val2=Integer.parseInt(data2);
System.out.println("Addition :"+(val1+val2));
}
}

Scanner:
---------
-->It was provided by JDK5.0 version
-->It was provided in java.util package
-->It can be used to take primitive data as dynamic input directly with out
using wrapper classes.
Steps:
------
a)Create Scanner class Object
------------------------------
Scanner s=new Scanner(System.in);

b)Read dynamic input through Scanner:


---------------------------------------
To read String data
public String nextLine()
public String next()

To read primtive data


public xxx nextXxx()
xxx--> byte, short,.....
EX:
---
import java.util.*;
class Test
{
public static void main(String[] args)throws Exception
{
Scanner s=new Scanner(System.in);
System.out.print("Employee Number :");
int eno=s.nextInt();
System.out.print("Employee Name :");
String ename=s.next();
System.out.print("Employee Salary :");
float esal=s.nextFloat();
System.out.print("Employee Address :");
String eaddr=s.next();
System.out.println();
System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number :"+eno);
System.out.println("Employee Name :"+ename);
System.out.println("Employee Salary :"+esal);
System.out.println("Employee Adderss :"+eaddr);
}
}

Q)What is the difference between next() and nextLine() method?


--------------------------------------------------------------
Ans:
---
next() ---> read single word from line of data.
nexrtLine()---> read a line of data contains multiple words.

EX:
---
import java.util.*;
class Test
{
public static void main(String[] args)throws Exception
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Text Data :");
String data1=s.nextLine();
System.out.print("Enter the same text again :");
String data2=s.next();
System.out.println("First Eneterd :"+data1);
System.out.println("Second Eneterd :"+data2);
}
}

Console:
---------
--> It was introduced in JAVA6 version.
--> It was provided in java.io package.
Drawbacks with BufferedReader and Scanner:
1)For each and every single dynamic input we have to consume two instructions.
a)System.out.println(); to display request message.
b)The actual instuction to read dynamic input.
br.readLine() or s.next() or s.nextXXX()

2)No Security for the data like passwords, PIN numbers,....

Steps:
------
a)Create Console class object:
------------------------------
public static Console console()
EX: Console c=System.console();

b)Read dynamic input through COnsole class:


--------------------------------------------
To display a message and to read String data

public String readLine(String message)


To display a message and to read password data in the form of char[].

public char[] readPassword(String message)

EX:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws Exception
{
Console c=System.console();
String uname=c.readLine("User Name :");
char[] pwd=c.readPassword("Password :");
String upwd=new String(pwd);
if(uname.equals("durga") && upwd.equals("durga"))
{
System.out.println("Login Success");
}
else
{
System.out.println("Login Failure");
}
}
}

Adv Java:
---------
1.JDBC
2.Servlets
3.JSPs
4.JSTL
5.EL

Databases:
-----------
Oracle
MySQL

Servers:
--------
Tomcat
Weblogic
JBOSS and Wildfly
Glassfish

IDEs
----
Editplus
Eclipse
MyEclipse
Netbeans

1.JDBC
-------
--> JDBC is a set by set by process to interact with database from Java
applications inorder to perform database operations from Java appl.
--> JDBC is a tech, it will proviode very good environment to connect with database
from java applications inorder to perform database operations from java
applications.
--> JDBC is an API[Collection of classes and interfaces], it will provide
environment to interact with database from java applications inorder to perform
database operations from java applications.
--> JDBC is an abstraction provided by SUN Micrystsems and implemented by all
database Vendors inorder to connect with database from java applications to perform
database operations from java appl.

public interface Driver


{
--abstract methods----
}

class OracleDriver implements Driver


{
----impl by Oracle----
}
class MySQLDriver implements Driver
{
--impl by MySQL---
}
class DB2Driver implements Driver
{
--impl by DB2----
}

Five Types

Type-1 Driver
Type-2 Driver
Type-3 Driver
Type-4 Driver
Type-5 Driver

Type-1 Driver
-------------
--> It also called as Bridge Driver or Jdbc-Odbc Driver.
--> It was provided by SUN Microsystems as reference implementation for Driver
interface iorder to provide enviironment for all the database vendors to
implement Driver interface.
--> SUN Microsystems has provided Type-1 drover in the form of
sun.jdbc.odbc.JdbcOdbcDriver in JAVA software along with java predefined
library.
--> This driver was provided by SUN Microsystems with the interdependncy on the
Microsoft product "ODBC Driver"[Open Database Connectivity].
--> ODBC is provided by Microsoft and implementd by using some native
implementations and it will provide very good environment to connect with any
type of Database from JDBC-ODBC Driver.
--> If we want to use Type-1 driver in JDBC applications then we must install
ODBC Driver [ODBC Native Library] in our System.
--> ODBC Driver is available bydefault in Microsoft products, but, it is not
available in Non Microsoft products bydefault, so that, Type-1 driver is
dependent on Microsoft propducts,Therefore, Type-1 driver is less portable
driver.
--> Type-1 driver is not suitable for Web Applications and Distributed appl.
--> Type-1 driver is suitable for Standalone Appl.
--> Type-1 driver is a reference impl, it is not for complex JDBC appl, it is
for simple JDBC appl requiurements.
--> Type-1 driver is slower driver, because, it must require two times
conversion inorder to interact with database from java appl.
1.From Java to ODBC by JDBC-ODBC Driver
2.From ODBC to DB repersentations by ODBC Driver
--> It will reduce JDBC application performance.

2.Type-2 Driver
----------------
--> It is also called as "Part java, part Native Driver" or simply "Native Driver".
--> Type-2 driver was prepared by using some java implementations and by using
Database Vendor provided native Library.
--> If we want to use Type-2 Driver in JDBC Applications then we have to install
the respective DB vendor provided native library in our
Machine.
--> When compared with Type-1 driver, Type-2 driver is more portable driver.
--> When compared with Type-1 driver, Type-2 driver is faster driver, Type-2 Driver
should not required two times conversions, it is sufficient to have one time
conversion to interact with database from java appl.
-->When compared with Type-1 driver, It will improve JDBC applications performance.
-->Type-2 Driver is not Economical Driver, it is costful.
-->Type-2 Driver is suggestible for Standalone applications only, not for web
applications and Distributed Applications.

Type-3 Driver:
---------------
--> Type-3 Driver is also called as "Middleware Database Access Server Driver" or
"Network Driver".
--> Type-1 and Type-2 Drivers are suggestible for only Standalone appl, but,Type-3
Driver is suggestible for Web applications and Distributed appl.
--> Type-1 driver is dependent on MS provided ODBC Driver, Type-2 Driver is
dependent on Database Vendor provided Native Library, but, Type-3 Driver is
dependent on Application Server which we have used for our applications.
--> Type-3 Driver is more portable driver when compared with Type-1 and Type-2
Drivers.
--> Type-3 Driver is faster Driver when compared with Type-1 and Type-2 Drivers,
because, Type-3 Driver is not required to perform two times conevrsions and it is
not required to load DB vendor provided native library, it is sufficient to start
application Server.
-->Type-3 driver will increase performance of the JDBC applications when compared
with Type-1 and Type-2 Drivers.
-->Type-3 Driver is able to provide very good environment to connect with multiple
databases from multiple clients[java appl] at a time.
-->It is not applicable for Standalone appl, because, it must require Server
environment.

Type-4 Driver
--------------
--> Type-4 Driver is also called as "Pure Java Driver" or "Thin Driver".
--> It was implemented completely on the basis of java implementations.
--> Type-4 Driver is more portable driver when compared with Type-1, Type-2 and
Type-3 Driver.
--> Type-4 Driver is suggestible for both Standalone applications and web
applications and Distributed Applications.
--> It is possible to use Type-4 driver with or with out application server.
--> Type-4 driver is frequently used driver in applications.
--> Type-4 driver is light weight driver and faster driver when compared with
Type-1,Type-2 and Type-3 Drivers.
--> Type-4 driver is most economical driver.

Steps To prepare First JDBC Application:


----------------------------------------
1.Load And Register Driver
2.Establish Connection between Java application and Database
3.Create either Statement or PreparedStatement or CallableStatement as per the
requirement.
4.Write And Execute SQL Queries
5.Close the Statement and Connection

1.Load And Register Driver


---------------------------

public static Class forName(String Driver_Class_Name)throws ClassNotFoundException


EX:
---
Class c=Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

package java.sql;
public interface Driver// SUn
{
-----
}

package sun.jdbc.odbc;
public class JdbcOdbcDriver implements Driver// Sun Microsystems
{
-------
static
{
-----
DriverManager.registerDriver(--);
}
}

package java.sql;
public class DriverManager
{
----
public static void registerDriver(Driver d)
{
---logic to register Driver----
}
}

package com.durgasoft.jdbc;
public class JdbcApp
{
public static void main(String[] args)throws Exception
{
Class c=Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
-----
}
}

In case of Type-1 driver , If we use JDBC3.0 version, JAVA6 and above versions then
"Load and Register Driver" step is optional.
In case of Type-4 Driver provided by Oracle , if we use JDBC4.0 version, JAVA6 and
above versions and Oracle11g/ Oracle11xe version "Load and Register Driver " step
is optional.

java.sql package

Driver [I]
DriverManager [C]
Connection [I]
Statement [I]
PreparedStatement [I]
CallableStatement [I]
ResultSet [I]
ResultSetMetaData [I]
DatabaseMetaData [I]
----
----

2.Establish Connection between Java application and database:


--------------------------------------------------------------
public static Connection getConnection(String driver_URL, String db_User_Name,
String db_Pwd)throws SQLException

Driver URL:
-----------
Type-1 Driver:
---------------
Driver_Class: sun.jdbc.odbc.JdbcOdbcDriver
Driver_URL: jdbc:odbc:nag

Type-4 Driver Provided by Oracle:


----------------------------------
Driver_Class : oracle.jdbc.OracleDriver
Driver_URL: jdbc:oracle:thin:@localhost:1521:xe

Type-4 Driver provided by MySQL:


---------------------------------
Driver_Class: com.mysql.jdbc.Driver
Driver_URL: jdbc:mysql://localhost:3306/db_Name

Main_Protocol_Name: Sub_Protocol_Name: DB_Name


Where Main_Protocol_Name is fixed in all the drivers that is "jdbc".

EX:
---
Connection con=DriverManager.getConnection("jdbc:odbc:nag", "system", "durga");

Q)In Jdbc, Connection is an interface, but, how getConnection() method will create
Connection object?
------------------------------------------------------------------------
Ans:
----

JDBC is an abstraction[Collection of interfaces] provided by SUN and implemented by


all database vendors.

package java.sql;
public interface Connection// SUN
{
----services in the form of abstract methods----
}

package com.oracle.jdbc;
public class OracleConnectionImpl implements Connection// Oracle
{
---implementation for services-----
}

package java.sql;
public class DriverManager// SUN
{
------
public static Connection getConnection(String url, String db_User_Name,
String db_Pwd)throws SQLException
{
---Logic to identify DB_Vendor Provided JDBC impl----
----Establish connection between java appl and DB by calling
Driver.connect()-----
Connection con=new OracleConnectionImpl();
return con;
}
-------
}

class JdbcApp
{
public static void main(String[] args)
{
---Load n register driver----
Connection con=DriverManager.getConnection(---,---,--);
}
}

3.Create either Statement or PreparedStatement or CallableStatement objects as per


the requirement:
--------------------------------------------------------------------

public Statement createStatement() in java.sql.Connection


EX: Statement st=con.createStatement();

Q)In Jdbc, Statement is an interface then how it is possible to create Statement


object in createStatement() method?
-----------------------------------------------------------------------

package java.sql;
public interface Statement// SUN
{
----
}

package com.oracle.jdbc;
public class OracleStatementImpl implements Statement// Oracle
{
---
}
package com.oracle.jdbc;
public class OracleConnectionImpl implements Connection// Oracle
{
----
public Statement createStatement()
{
--------
Statement st=new OracleStatementImpl();
return st;
}
}

class JdbcApp
{
public static void main(String[] args)
{
-------
Statement st=con.createStatement();
}
}

Q)What is the difference between Statement, PreparedStatement and


CallableStatement?
-------------------------------------------------------------------------
Ans:
----
Statement: To execute all the sql queries individually

PreparedStatement: To execute the same sql query in the next sequence, where to
improve JDBC application performance.

CallableStatement: To access stored procedures and functions from Java application


which are existed at database.

4.Write and Execute SQL Queries:


--------------------------------
1.executeQuery(---)
2.executeUpdate(--)
3.execute(--)

Q)Write JDBC application to create a table in DB by taking table name, column


names, column data types and sizes as dynamic input.

Type-4 Driver By Oracle


-------------------------
Driver_CLass: oracle.jdbc.driver.OracleDriver[Oracle8i]
Driver_Class: oracle.jdbc.OracleDriver[Right from Oracle9i]

Driver_URL : jdbc:oracle:thin:@localhost:1521:xe[Oracle 10/11xe]


Driver_URL : jdbc:oracle:thin:@localhost:1521:ORCL[Oracle10g/11g]

Oracle8i and 9i----> classes12.jar, classes14.jar


Oracle10g/10xe ----> ojdbc14.jar
Oracle11g/11xe ----> ojdbc6.jar[JAVA6 and above]
Oracle11g/11xe ----> ojdbc5.jar[JDK5.0]

C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar
DDL:create, alter, drop

DML:insert, update delete

int rowCount=st.executeUpdate(insert/update/delete)

int rowCount=st.executeUpdate(create/alter/drop);

Type of driver which we used.

If we use Type-1 driver provided by SUN Microsystems


OP: -1

If we use Type-4 driver provided by Oracle


OP: 0

ResultSet executeQuery(--) -----> select


int executeUpdate(--) ----> non select
boolean execute(--) -----------> both

boolean b1=st.execute("select * from emp1");


Sopln(b1); OP: true

Here internally ResultSet object is created but it will return true value.

public ResultSet getResultSet()


EX: ResultSet rs=st.getResultSet();

boolean b2=st.execute("update emp1 set esal=esal+500 where esal<10000");


Sopln(b2); OP: false

Here internally RowCount value is created but it will return false value.

public int getUpdateCount()


int rowCount=st.getUpdateCount();

st.executeQuery(--)
st.executeUpdate(--)
st.execute(--)

Q)In JDBC, we will use executeQuery(--) method to execute select sql query, but, if
we provide non-select sql query as parameter to executeQuery(--) method then what
will happen in JDBC applications?
-----------------------------------------------------------------------

ResultSet rs=st.executeQuery("update emp1 set esal=esal+500 where esal<10000");

Q)In JDBC, we will use executeUpdate(--) method to execute non-select sql query,
but, if we provide select sql query as parameter to executeUpdate(--) method then
what will happen in JDBC applications?
-----------------------------------------------------------------------
int rowCount=st.executeUpdate("select * from emp1");

java.sql.SQLException: No Rowcount was produced.

Read_Only and Forward_Only

public Statement createStatement(int Forwad_Only/Scroll_Sensitive/Scroll_


Insesitive, int Read_Only/Updatable)throws SQLException

To read data in forward direction .

1.public boolean next()throws SQLException


2.public xxx getXxx(int column_Index)
or
public xxx getXxx(int column_Name)

To read data in backward direction

1.public boolean previous()throws SQLException


--> It will check whether any previous record is existed or not from the current
cursor position, if it is not existed then it will return false, if it is existed
then it will return true value and it will move cursor to the previous record
position.

2.public xxx getXxx(int column_Index)


or
public xxx getXxx(int column_Name)

MySQL DB, Type-4 driver


-------------------------
Driver_Class Name: com.mysql.jdbc.Driver
Driver_URL: jdbc:mysql://localhost:3306/db_Name

If we want to use the above driver classs in Jdbc applications then we have to set
"classpath" environment variable to
"mysql-connector-java-5.0.8-bin.jar" or we have to add this jar file to our project
in eclipse ide as referenced library.

To prove Scroll sensitive ResultSet object we have to use the following steps.
1.Create Scroll Sensitive ResultSet.
2.Display Data from ResultSet object.
3.Pause application , goto database and perform modifications on table
explicitly.
4.Re-display data from ResultSet object by refreshing each and every record.
Conclusion: If the data before updatinos and after updations is different then the
ResultSet object is scroll sensitive ResultSet.

Type-1 Driver provided by SUN:


-------------------------------
Scroll Sensitive is supported.
Scroll insensitive is not supported.

Type-4 Driver provided by Oracle:


------------------------------------
Scroll Sensitive is not supported.
Scroll Insensitive is notsupported.

Type-4 driver provided by MySQL:


--------------------------------
Scroll Sensitive is supported.
Scroll Insensitive is not supported.

Updatable ResultSets:
----------------------
--> We can perform the database operations like insert, update, delete with out
using the respective SQL Queries.
--> We will use this mechanism when we have a requirement to work with unknown
databases.

Inserting Records in Database through Updatable ResultSet:


---------------------------------------------------------

Updating Records in database through Updatable ResultSet:


-----------------------------------------------------------

Deleting Records in Database through Updatable ResultSet


---------------------------------------------------------

GUI-JDBC Integration Application:


PreparedStatement:
------------------
Q)What is the difference between Statement and PreparedStatement?
-----------------------------------------------------------------
Ans:
----

How to insert dates in DB and How to retrive Dates from DB.

Batch Updations:
-----------------
public void addBatch(String sql_Query)

public int[] executeBatch()throws SQLException

Batch Updations with Statement

Batch updations With PreparedStatement

CallableStatement:
-------------------
Procedure will not have return statement to return value.
EX:
----
create or replace procedure Procedure_Name[(Param_List)]
AS
---Global declarations-----
BEGIN
----Database Logic----
END Procedure_Name;
/---> to save and compile procedure.

Functions are having return statements to return value.


EX:
---
create or replace function Function_Name[(Param_List)] return Data_Type
AS
---Global Declarations----
BEGIN
---Database Logic-----
return value;
END Function_Name;
/---> To save and compile function
There are three types of paraeters in procedures and functions.
1.IN type parameters: it will take values from procedure/function call and
providing that values to procedure body or function body.

2.OUT type parameters: It will take values from procedure/function body and it will
send to procedure/function call.

3.INOUT typeparameter: it is acting as both IN type and OUT type parameter.

We will create stored procedures and functions at database side.

CallableStatement.

CURSOR types.

SYS_REFCURSOR

Metadata:
---------
Data about the data is called Metadata.

1.DatabaseMetaData
2.ResultSetMetaData

1.DatabaseMetaData
--------------------
Database name,Database Product version, Driver versions, Supported SQL Keywords,
String Functions, NUmeric Functions, ......

public DatabaseMetaData getMetaData()

2.ResultSetMetaData
--------------------
data about ResultSet is called as ResultSet metadata, it includes no of columns,
column names, column data types, column sizes,.......

public ResultSetMetaData getMetaData()

Transaction Management:
------------------------
Front-End appl on Back-End system
Withdraw, deposit, transfer,.......Transactions.

In general, all transactions must follow the following properties called as "ACID"
properties

A-----> Automicity
C-----> COnsistency
I-----> Isolation
D-----> Durability

Automicity:
-----------
Either perform all operations or perform none of the operations in Transaction.
Perform All----> SUCCESS
Perform None---> FAILURE

1.Automicity:
---------------

Savepoint
----------

Isolation Levels:
------------------

1.Lost Update Problem


2.Dirty Read Problem
3.Non Repeatable Read Problem
4.Panthom Read Problem

java.sql.Connection

public static final int TRANSACTION_NONE=0;


public static final int TRANSACTION_READ_UNCOMMITTED=1;
public static final int TRANSACTION_READ_COMMITTED=2;
public static final int TRANSACTION_REPEATABLE_READ=4;
public static final int TRANSACTION_SERIALIZABLE=8;

con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
public int getTransactionIsolation()

BLOB CLOB
RowSets

Connection Pooling
-------------------

BLOB CLOB
------------
BLOB
----
It is a data type in databases, it able to manage large volumes of binary data and
it able to manage Images data,...

CLOB
----
It is a data type in databases, it able to manage large volumes of characters data
and it able to manage Documents like .doc files, PDFs, XML docs,.....

blob -------------> clob


InputStream ------> Reader
OutputStream------> Writer
FileInputStream---> FileReader
FileOutputStream--> FileWriter
setBinaryStream()-> setCharacterStream()
getBinaryStream()-> getCharacterStream()

RowSets:
---------

1.JdbcRowSet
2.CachedRowSet
---------------------------------------------
Servlets:
----------
1.Standalone Appl
1.CUI Appl
2.GUI Appl
2.Enterprise Appl
1.Web Appl
2.Distributed Appl
Q)What are the differences between Web applications and Distributed Applications?
-----------------------------------------------------------------------
Ans:
----
1.In case of web applications, the complete application logic is distributed over
server machine only.

In case of Distributed applications, the complete application logic is distributed


over both Local Machine and Remote Machine.

2.To prepare Web applications we will use a set of technologies called as "Web
tech"
EX: CGI
Servlets
JSPs
----
----
To prepare Distributed Applications, we will use a set of tech called as
"Distributed technologies".
EX: Socket Programming
RMI
CORBA
EJBs
Web Services
----
----
3.In case of Web applications, client is fixed that is Browser.

In case of Distributed Applications, client may be a core java program with main()
method, a GUI application with actionPerformed(--), a servlet program, a JSP
application, a struts appl, a JSF appl, A spring web module,.....

4.In case of web applications, Server saide application will provide services for
only one type of client that is browser.

In case of Distributed applications, server side appl may provide services for any
type of client.

5.The main purpose of web applications is to generate dynamic response from Server
machine.

The main purpose of Distributed applications is to establish communication between


local machine and Remote machine inorder to get Remote services from Remote
machine.

6.Web applications are executed by only web servers.

Distributed applications are executed by both web servers and application


servers.

7.Web application is the collection of web components like servlets, JSPs, which
are executed by the web containers like servlet container and JSP container,...
Distributed application is the collection of Distributed components like EJBs,
which are execurted by EJB Container.
-------------------------------------------------------------------------
In Enterprise Appl, there are two types of responses.

1.Static Response
2.Dynamic Response

To generate Dynamic Response we have to execute an application at server called as


"Web Application", to prepare web applications we have to use the following web
techs.
CGI
Servlets
JSPS
----
----

Q)What is the difference between CGI and Servlets?


---------------------------------------------------

Q)What are the differences between Servlets and JSPS?


------------------------------------------------------
Ans:
----
1.Servlets are very good at the time of getting requests from client.
JSPs are very good at the time of generating response to client.

2.In Web applications, we will use servlets mainly for processing the
requests[Executing Business Logic].
JSPs are maily for presentation part.

3.IN MVC based web applications, we have to use a servlet as controller and a set
of JSP pages as view part.

Struts MVC based Framework:


ActionServlet ---> Controller
set of JSPs------> View

JSF MVC based Framework:


FacesServlet -----> Controller
Set of JSP pages---> View

SPring Web Module MVC based Framework:


DispatcherServlet -----> Controller
Set of JSP pages ---> View

4.If we use only Servlets in web applications then we are unable to seperate
business logic and presentation logic.

If we use only JSPs in web applications, we are able to seperate presentation logic
and Business logic, for presentation logic we are able to use Html tags and for
Busines logic we are able to use JSP tags.

5.If we made any changes in Servlets then it is required to perform recompilation


and reloading into the server.

If we perform any modifications in JSP pages then it is not required to recompile


and reloading into the server explicitly, because, JSPs are auto loaded and auto-
compiled, refresh the browser is sufficient.

Client-Server Arch:
--------------------
It is 2-Tier Arch, it is minimum arch for enterprise appl , that is , web
applications.

1.Client
2.Protocol
3.Server

1.Client
----------
--> Client is a browser.
--> The role of the client in client-server arch is to send requests to server and
to get response from server.
--> To send request or to refer a particular serve4r side resource we have to use a
String at client address bar called as "URI".
1.URN
2.URL

Q)What is the difference between URI, URL and URN?


----------------------------------------------------
Ans:
-----
URI is a string specification provided at client address bar, it can be used to
refer a particular server side resource inorder to access from client.

URN is a string specification provided at client address bar, it can be used to


refer a particular resource existed at server machine through its logical name.
Note: In the case of servlets, logical name is the name specified along with
<servlet-name> tag in web.xml file.
Note: URN is not supported by almost all the servers.

URL is a string specification provided at client address bar, it can be used


torefer a particular resource existed at server machine through its locator or
Alias Name or URL_Pattern.
Note: Almost all the servers are supporting URL repersentation.
Note: locator or alias name or URL_Pattern is a name specified along with <url-
pattern> tag in web.xml .

Syntax:
-------

Protocol_Name://Server_IP_Addr:Server_Port_Num/appl_Name/res_Name[?Query_
String]
EX:
---
http://localhost:8080/loginapp/login?uname=abc&upwd=abc123

http----> Protocol_Name
localhost --> Server IP Address,If server software is available at the same client
machine then we can specify "localhost" as server IP address.
"127.0.0.1"
8080---> Server Port Number
8080 ---> Tomcat
7001 ---> Weblogic
--- ----
loginapp---> Web application name
login------> Locator for Login Servlet
?uname=abc&upwd=abc123 ----> Query String

Q)What is the difference between IP Address and Port Number?

Q)What is query String and what is the requirement of Query String?

http://localhost:8080/loginapp/login?uname=abc&upwd=abc123
------------------------------------------------------------------------
2.Protocol:
-------------
Hyd to Mumbai.
1.Bus: a Protocol.

2.Train: a protocol

3.Air: a protocol

TCP, IP, UDP, Http, ARP, RARP,.....

Q)In web applications we are going to use only Http protocol why?
------------------------------------------------------------------
Ans:
----
In web applications, we need a protociol, it must be ,
1.Connection less protocol: Not to have any phisical connection, to have
logical connection.
2.Stateless Protocol: Not to remembers previous requests data at the time
of processing present request.
3.Compatible with Hypertext data:In general , Data will be transfered from client
to server and from server to client in the form of Hyper text only

Http protocol

Q)How it is possible for Http protocol to manage stateless nature?


------------------------------------------------------------------

Protocol Services
-----------------
1.Http Methods
2.Status Codes

1.Http Methods
---------------
Http1.0
-------
GET
POST
HEAD

Http1.1
--------
OPTIONS
PUT
TRACE
DELETE

CONNECT
Q)What are the differences between GET and POST?
--------------------------------------------------
Ans:
----
1.GET request type is default request in web applications.
POST requyest type is not default requests type.

2.GET request is not having BODY part in rquest format.


POSt request is having Body part in request format.

3.GET Request is able to transfer less data from client to server due to the lack
of Body part in Request Format.

POST request is able to transfer more data from client to server due to the
availability of the body part.

Note: If we submit data along with GET request then that data will be transfered
through Header part of the request format, where header part is having memory
restrictions over the data , it allows only 2048 characters data only.No memory
restrictions over the data in POSt request.

4.In case of GET request no security is available for the Data like password data,
PIN Numbers,...

In case of POST request , Security is availabl for the data like Password data,PIN
Numbers, Secreate codes,....
Note:IN case of GEt request, If we provide data along with request then that data
will be displayed on client address bar as query string.In case of POST request, if
we provide data along with request then that data is not visible on client address
bar.

5.The main purpose of GET is to get data from Server , that is , for Downloading
data from Server.

The main purponse of POST request is POST data to Server , that is, for Uploading
Data to the Server.

6.Bookmarks are supported by GET request.


Bookmarks are not supported by POST request.

7.GET request is supporting ASCII characters data, not Binary data.


POST request is supporting all types of data.

8.GET requests data will be cached.


POST requests data will not be cached.
------------------------------------------------------------------------
3.HEAD:
--------
It is very same as GETrequest only, but it able to provide only HTTP Headers in
Response format only, it will not carry any response body.

4.OPTIONS:
----------
It can be used to get the HTTP method which are supported by present Server.

5.PUT :
-------
It is also be used to POST the data , but, it is used mainly for replacement of
tyhe resources at server.

6.DELETE:
----------
It can be used to specify a particular resource to delete from Server.

7.TRACE:
--------
To know the tracing part of the resource path we need to use TRACE request. It can
be used to check whether resources are working fine or not which are available at
server. It working on the basis of Echo server nature.

PUT, DELETE request types are not supported almost all the servers.

---------------------------------------------------------------------
Status Codes:
--------------
1XX ---> 100 to 199 ----> Informational Status Codes
2XX ---> 200 to 299 ----> Success Related Status codes.
3XX ---> 300 to 399 ----> Redirectinoal status codes.
4XX ---> 400 to 499 ----> Client Side Error.
5XX ---> 500 to 599 ----> Server Side Error.

Protocol:
----------
What is protocol
Which protocol is required in web appl.
What is the requirement to use Http Protocol.
How Http Protocol is able to manage its stateless nature.
Http Methods
Status Codes.
-------------------------------------------------------------------------
Server:
--------
Getting requests from client, Processing request and sending response to the
client.

Server softwares.
Tomcat
Weblogic
Websphere
JBOSS/Wildfly
Glassfish
----
----

2 types

1.Web Servers
2.Application Servers

Q)What is the difference between Web Server and Application Server?


--------------------------------------------------------------------
Ans:
----
Web Servers are able to execute only web applicatins and web servers are not
providing any Middleware services like JNDI, JTA, JAAS, JMS,.....
EX:Oracle WEB
Upto Tomcat1.4
Application Servers are able to execute any type of application like web
applications, distributed applications,.... and it able to provide middlewarew
services.
EX: Tomcat5.0
Weblogic
JBOSS
Glassfish
----
-----

If we install server software in server machine then that software is available


with 2 modules

1.Main Server
2.Container

Q)What is the difference between Main Server and Container?


------------------------------------------------------------
Ans:
----
Main Server: It will check whether request is valid or not, if it is valiud forward
request to Container and It will take response from Container and forward
thatresponse to protocol.

Container: It will take request from Mian Server, It will identify requested
resource, executes that requested resource and generates response to Main server.

Containers are in 2 Ways.


1.On the basis of the Technology or components which we used in applications there
are two types of containers.
1.Web Containers
--> executes only web components like servlets, JSPs,...
EX: Servlet Container , JSP Container
2.EJB Containers
---> Executes only EJB components.

2.on the basis of the containers physical existency there are three types of
containers.
1.Standalone Container:It is an integration of Main Server and
Container as single unit.
2.In-Process Container: It is a container existed inside the main
server.
3.Out-Of-Process Container:It is a container existed in out side of the
Main Server.
-------------------------------------------------------------------------

Steps To Prepare Web Applications:


-----------------------------------
0.Install Server Software
1.Prepare Web Application Directory Structer.
2.Prepare Deployement Descriptor[web.xml]
3.Prepare Web Resources Like Servlets and JSPs
4.Start Server and Deploy Web Application.
5.Access Web Applications

1.Prepare Web Application Directory Structer.


--------------------------------------------
http://localhost:1010/loginapp/loginform.html

http://localhost:1010/loginapp/login

2.Prepare Deployement Descriptor[web.xml]


-------------------------------------------
It is web.xml file, it will provide description about our web application which is
required by the container inorder to execute server side resource.

IN web applications, web.xml file is responsible for


1.Welcome Files Conf.
2.Display Names Conf.
3.Context Params Conf.
4.Servlets Conf.
5.Filters Conf.
6.Listeners Conf.
7.Intialized Params Conf
8.Error Pages Conf.
9.SessionTime-out Conf.
10.Tag Libraries Conf.
11.Security conf.
-----
------

If we want to provide servlets configuration in web.xml file we have to use the


tags.

<web-app>
<servlet>
<servlet-name>servlet_logical_name</servlet-name>
<servlet-class>Servlet class Fully Qualified Name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet_logical_name</servlet-name>
<url-pattern>pattern_Name1</url-pattern>
<url-pattern>pattern_Name2</url-pattern>
-----
</servlet-mapping>
</web-app>

EX:
---
<web-app>
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.durgasoft.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

Servlet2.5 version onwards we can declare more than one URL Pattern for Single
Servlet.

http://localhost:1010/loginapp/login
There are three approaches to define URL Patterns in web applications for Servlets.

1.Exact Match Method


2.Directory Match Method
3.Extension Match Method

1.Exact Match Method


---------------------
it must be started with '/' in web.xml file

<url-pattern>/abc/xyz</url-pattern>

Provide an url pattern at Client Address bar, it must be matched with the URL
pattern which we specified in web.xml file.

http://localhost:1010/app1/abc/xyz----> Valid
http://localhost:1010/app1/xyz/abc---> Invalid
http://localhost:1010/app1/abc-------> Invalid
http://localhost:1010/app1/xyz-------> Invalid

Note: When we want to access servlets individually there we have to use Exact match
method.

2.Directory Match Method:


--------------------------
It must be started with / and it must be ended with *

<url-pattern>/abc/*</url-pattern>

To access the corresponding resource we have to provide an url pattern at client


address bar, its prefix value must be matched with the prefix value of the URL
pattern defined in web.xml

http://localhost:1010/app1/abc ----> valid


http://localhost:1010/app1/abc/xyz----> Valid
http://localhost:1010/app1/abc/abc/xyz---> Valid
http://localhost:1010/app1/xyz/abc----> Invalid
http://localhost:1010/app1/abc/xyz/abc/xyz----> valid

Note: When we want to send gropups of requests to the server side resources there
we have to use directory match method to defined url pattern.
EX: Filters

3.Extension Match Method:


---------------------------
Define an url pattern, it must be started with * and ended with a particular
extension.

<url-pattern>*.do</url-pattern>

If we want to access the corresponding servlet then we have to provide an url


pattern at client address, it may start with any thing, but, it must have the same
extension which we defined in web.xml file.

http://lh:1010/app1/login.do-----> Valid
http://lh:1010/app1/reg.do-------> Valid
http://localhost:1010/add.do-----> Valid
http://localhost:1010/search.do----> Valid
http://localhost:1010/delete.xyz----> INvalid

It will be used in MVC based applications, where we need to send all the requests
to the Controller , where we have to perform actions on the basis of the url
patterns.

In web applications, is web.xml file mandatory?


------------------------------------------------
Ans:
----
depending on the server which we used.

1.Using Servlet/Filter/Listeners
---------------------------------
In all servers, web.xml file is mandatory upto Servlet2.5 version, web.xml file
optional from Servlets3.0 version, because, Servlet3.0 version will use Annotations
inplace of web.xml file.

2.With out Using Servlet/Filter/Listeners


-----------------------------------------
Depending on the server web.xml is mandatory.
If we use the servers like Weblogic,... then web.xml file is mandatory to deploy
applications into Servers.

If we use the servers like Tomcat then web.xml file is optional.

Is it possible to change name and location of web.xml file in web applications?


-----------------------------------------------------------------------
Ans:
----
No, it is not possible to change name and location of web.xml file , here name is
web.xml and location is under "WEB-INF" folder.

0.Install Server Software


1.Prepare Web Application Directory Structer.
2.Prepare Deployement Descriptor[web.xml]
3.Prepare Web Resources Like Servlets and JSPs
4.Start Server and Deploy Web Application.
5.Access Web Applications

3.Prepare Web Resources Like Servlets and JSPs


-----------------------------------------------
If we want to prepare Servlets we have to use predefined library provided by
Servlets API in the form of javax.servlet and javax.servlet.http packages.

In javax.servlet
Servlet
GenericServlet

In javax.servlet.http
HttpServlet

Q)What is Servlet and in how many ways we are able to prepare Servlets in web
applications?
-------------------------------------------------------------------------
Ans:
----
Serlvet is a server side program managed by the container , it can be executed to
generate dynamic response.

Servlet is an object managed by the container it must implement Servlet interface


either directly or indirectly.

As per the predefined library , there are three ways to porepare Servlets.

1.Implementning Servlet interface:


-----------------------------------
public class MySerclet implements Servlet{
----provide implementation for all Servlet interface methods---
}

2.Extending GenericServlet Abstract class:


----------------------------------------------
public class MyServlet extends GenericServlet{
---Implement service methods------
}

2.Extending HttpServlet Abstract class:


----------------------------------------------
public class MyServlet extends HttpServlet{
---Implement service methods------
}

4.Start Server and Deploy Web Application.


5.Access Web Applications

http://localhost:1010/app1/abc
------------------------------------------------------------------
Servlets Design:
-----------------
There are three ways to prepare Servlets
1.Implementing Servlet interface
2.Extending GenericServlet abstract class
3.Extending HttpServlet abstract class

1.Implementing Servlet interface


---------------------------------
public interface Servlet{
public void init(ServletConfig config)throws ServletException;

public void service(ServletRequest request, ServletResponse response) throws


ServletException , IOException;

public ServletConfig getServletConfig();

public String getServletInfo();

public void destroy();


}
public class MyServlet implements Servlet{
---implementation for all methods of Servlet interface----
}

init(), service(), destroy() ---> Lifecycle methods.


getServletInfo(), getServletConfig()--> Non lifecycle methods.
Steps to implement service() method:
--------------------------------------
1.Set content type to the Response Format
response.setContentType("text/html");
The default content type in Response Format is "text/html".
text/xml
application/pdf
image/jpg
img/jpg
2.Get PrintWriter object
ServletRequest
ServletResponse
To send response to the ServletResponse inorder to send response to
client we have to use PrintWriter.
public PrintWriter getWriter()
EX: PrintWriter out=response.getWriter();

3.Send dynamic response


out.println("<html>");
out.println("<body>");
out.println("<h1>Welcome</h1>");
out.println("</body></html>");
-------------------------------------------------------------------------

2.Extending GenericServlet
-----------------------------
In this approach, we have to declare an user defined class , it must be extended
from javax.servlet.GenericServlet .

public abstract class GenericServlet implements Servlet, ServletConfig ,


Serializable{
private transient ServletConfig config;
public void init(ServletConfig config)throws ServletException{
this.config=config;
init();
}
public void init(){
}
public abstract void service(ServletRequest req, ServletResponse resp)throws
ServletException, IOException;
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return null;
}
public void destroy(){
}
----
----
}

public class MyServlet extends GenericServlet{


---provide implementation for service() method----
}
3.Extending HttpServlet Abstract class:
----------------------------------------
Q)What are the differences between GenericServlet and HttpServlet?
------------------------------------------------------------------
Ans:
----
1.GenericServlet is protocol Independent.
HttpServlet is Http protocol dependent.

2.GenericServlet is able to process any type of protocol requests like TCP/IP,


UDP, FTP,....
HttpServlet is able to process only Http protocol requests, it unable to
process other protocol requests.
Note: In Web appliations environment, we will use 90% Http protocol.

3.GenericServlet is able to process all the types of requests in common way, it


will not process requests in specific manner even we send GET, POST, HEAD,......
, it will execute only service(--) method for all the types of requests like GET,
POST, HEAD,...
HttpServlet is able to process the requests in more specific manner.
GET -----------> doGet(--)
POST-----------> doPost(--)
HEAD-----------> doHead(--)
OPTIONS--------> doOptions(--)
PUT------------> doPut(--)
TRACE----------> doTrace(--)
DELETE---------> doDelete(--)

4.GenericServlet has not implemented any protocol conventions at Server side.


HttpServlet has provided "Http Protocol" conventions at server side.
Note: GenericServlet is rarely used feature in web applications.
HttpServlet is frequently used feature in applications.

5.GenericServlet is not compatible with protocol.


HttpServlet is very good compatioble with Http protocol.
------------------------------------------------------------------------

If we want to prepare HttpServlet then we have to declare an user defiend class, it


must be extended from javax.servlet.http.HttpServlet abstract class.

GET ------> doGet(--)

public abstract class HttpServlet extends GenericServlet{


pulbic void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException{
HttpServletRequest hreq=(HttpServletRequest)request;
HttpServletResponse hres=(HttpServletResponse)response;
service(hreq, hres);
}
protected void service(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
String req_Type=hreq.getMethod();
if(req_Type.equals("GET")){
doGet(hreq, hres);
}
if(req_Type.equals("POST")){
doPost(hreq, hres);
}
----
----
if(req_Type.equals("DELETE")){
doDelete(hreq, hres);
}
}
protocted void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
----
}
protocted void doPost(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
----
}
-----
-----
protocted void doDelete(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
----
}
}

public class MyServlet extends HttpServlet{


--- override doGet(--) or doPost(--) ....doDelete(--) on the basis of the requests
types-----
}

Q)In HttpServlet,in general, we have to override doXXX(--) method on the basis of


XXX request type, is it possible to override service(--) method in HttpServlet? and
if we override service() method then what will happen in web applications?
------------------------------------------------------------------------
Ans:
----
Yes, it is possible to override service(--) in HttpServlet, if we override
service(--) method then container will execute user defined service() method only,
container will not execute predefined service(--) method, with this, container is
unable to reach doXXX(--) method.

Note: If it is the requirement to override service(--) method then better to go for


GenericServlet, no need to use HttpServlet, If we want to get benifits from Http
Protocol services then we have to use HttpServlet.
-------------------------------------------------------------------------
Q)In general, in HttpServlet, if we send xxx request type then we have to override
doXXX() method in HttpServlet. IN HttpServlet, if we override doPost(--) method for
GET request then what will happen in web Applications?
-------------------------------------------------------------------------
Ans:
----
IN HttpServlet, if we override doPost() method for GET request then container will
execute predefined doGet(--) method provided by HttpServlet, where it was
implemented to rise 405 an excepotion like "Http Method GET is not supported by
this URL".

Q)In Servlets, is it possible to provide both constructor and init() method with in
a single Servlet class?
-----------------------------------------------------------------------
Ans:
----
In Servlets, we can write constructor and init() both with in a single Servlet
class. If we provide static block, constructor, init() method, service() or doXXX()
method and destroy method with in a single servlet then container will execute all
the programming element at the following respective servlet life cycle actions.

static block -------------> Servlet Loading


constructor --------------> Servlet Instantiation
init() method ------------> Servlet Initialization
service()/doXXX() --------> Request Processing
destroy() ----------------> Servlet Deinstiation

if we want to provide a constructor in Servlet class then that constructor must be


0-arg constructor and it must be public constructor. If the constructor is
parameterized constructor then we will get javax.servlet.ServletException with the
root cause java.lang.InstantiationException. If we provide non public constructor
then container will rise an exception like javax.servlet.ServletException with the
root cause java.lang.IllegalAccessException.

Lifecycle:
-----------

User Interface / Forms Design :


--------------------------------
Main purpose of the User interface in Web applications is,
1.It is an entry point to the users inorder to interact with web appl.
2.It will provide very good env to take data from users inorder to submit to
Server side application.
3.It will provide very good environment to perform Client side data validations
with java script functions.
4.It will provide very good environment to specify different types of Requests
like GET, POST, HEAD, OPTIONS,....
5.It will improve look and feel for the applications.
6.To prepare this layer we have to use presentation logic, it will be prepared by
using the technologies like Html, JSP, Velocity, Free marker ,....

There are two types of User interfaces.


1.Informational User Interface
2.Form-Based User Interface

1.Informational User Interface


----------------------------------
It is an user interface, it will provide some information as response like status
of the server side application execution like "Login Success", "Login Failure", or
displaying database tables data,.....

2.Form-Based User Interface


----------------------------
It is an user interface,it will include user forms inorder to collect data from
users.

IN web applications, we are able to generate forms in the following two ways.

1.Static Form Generation


2.Dynamic Form Generation

1.Static Form Generation


------------------------
We will prepare an html file , we will keep that html file under application folder
of the web application and we will access that html file from client, where Server
will send that Html file as response . In this context user form is generated with
out performing any action at server.

http://localhost:1010/loginapp/loginform.html

2.Dynamic Form Generation


--------------------------
We will prepare a Servlet with form generation logic at server machine, we will
access that servlet from client, where Server will execute that servlet and it will
generate an user form as response to client.

http://localhost:1010/reg_app/get_update_Form

When form is generated at client, when we submit request with data from user form
to Server , at server machine the user specified data will be stored in Request
object.

To get the value of a particular request parameter on the basis of key we have to
use the following method.

public String getParameter(String key)


EX: String uname=request.getParameter("uname");

If multiple values are associated with single key and if we want to get that
associated value in the form of an array we have to use the following method.

public String[] getParameterValues(String key)


EX: String[] uquals=request.getParameterValues("uquals");

To get only keys , not values then we have to use the following method.

public Enumeration getParameterNames()

public String getHeader(String name)


public String[] getHeaders(String name)
public Enumeration getHeaderNames()

public void setAttribute(String key, Object value)


public Object getAttribute(String key)
public void removeAttribute(String key)
public Enumeration getAttributeNames()

ServletContext:
----------------
Q)What are the differences between ServletConfig and ServletContext?
--------------------------------------------------------------------
Ans:
----
1.ServletConfig object is able to manage all the configuration details of a
particular servlet which includes logical name of the Servlet, initialization
parameters,..... which we specified in web.xml file.

ServletContext object is able to manage all the context details of a particular web
application which includes logical name of the web application, context
parameters,..... which we specified in web.xml file.

2.ServletConfig object is able to provide the complete view of a particular


servlet.

ServletContext object is able to provide the complete view of a particular web


application.

3.If we keep data in ServletConfig object then that data will be shared upto a
particular Servlet.

If we keep data in ServletContext object then that data will be shared through out
the web application.

4.ServletConfig object will provide less sharability.

ServletContext object will provide more sharability.

5.ServletConfig object scope is upto a particular Servlet.

ServletContext object scope is upto a particular web application.

6.ServletCOnfig object is created by container immediatly after Servlet


Instantiation and Just before executing init(-) method as part of Servlet
Initialization.

ServletContext object will be created exactly at the time of web application


deployement or at the time of Server startup.

7.ServletConfig object will be destroyed just before performing Servlet


Deinstantiation.

ServletContext object will be destroyed when we shutdown the server or when we


undeploy the web application.

8.The lifetime of the ServletConfig object is upto the Servlet object lifetime.

The lifetime of ServletContext object is upto a particvlar web application life


time.

9.ServletConfig object is able to allow only parameters data, that is, static data.

ServletContext object is able to allow both parameters data and attributes data,
that is , both static data and dynamic data.

10.ServletConfig object will be created after the server startup and after getting
first request from client except in <load-on-startup> configuration.

ServletContext object will be created exactly at the time of server startup


irrespective of getting request from client.
-------------------------------------------------------------------
To represent ServletContext --> javax.servlet.ServletContext.

1.By using getServletContext() method from GenericServlet

ServletContext context=getServletContext();

2.By using getServletCOntext() method from ServletRequest:

ServletContext context=request.getServletContext();

3.By Using getServletContext() method from ServletConfig:


ServletConfig config=getServletConfig();
ServletContext context=config.getServletContext();

To define logical name of the web application we have to use

<web-app>
---
<display-name>logical_name</display-name>
----
</web-app>

public String getServletContextName()


EX: String logical_Name=context.getServletContextName();