Anda di halaman 1dari 95

Java/J2EE Interview Questions And Answers

Nageswara Rao Pilla


pnageshmca@gmail.com
pnageshmca@rediffmail.com
pnageshmca@yahoomail.com

1.What are the principle concepts of OOPS?


There are four principle concepts upon which object oriented design and programming rest. They are:

Abstraction
Polymorphism
Inheritance
Encapsulation (i.e. easily remembered as A-PIE).

2.What is Abstraction?
Abstraction refers to the act of representing essential features without including the background details
or explanations.
3.What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing
outside access only as appropriate. It prevents other objects from directly altering or accessing the
properties or methods of the encapsulated object.
4.What is the difference between abstraction and encapsulation?

Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation
(information hiding) prevents clients from seeing its inside view, where the behavior of the
abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up
your abstraction to suit the developer needs.

5.What is Inheritance?

Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
A class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism

6.What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a
characteristic of being able to assign a different meaning or usage to something in different contexts specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
7.How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.

In some cases, multiple methods have the same name, but different formal argument lists
(overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal
argument list (overridden methods).

8.Explain the different forms of Polymorphism.


There are two types of polymorphism one is Compile time polymorphism and the other is run time
polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is
done
using
inheritance
and
interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms
in Java:

Method overloading
Method overriding through inheritance
Method overriding through the Java interface

9.What is runtime polymorphism or dynamic method dispatch?


In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time. In this process, an overridden
method is called through the reference variable of a superclass. The determination of the method to be
called is based on the object being referred to by the reference variable.
10.What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given procedure
call is not known until the time of the call at run-time. It is associated with polymorphism and
inheritance.
11.What is method overloading?
Method Overloading means to have two or more methods with same name in the same class with
different arguments. The benefit of method overloading is that it allows you to implement methods that
support the same semantic operation but differ by argument number or type.
Note:

Overloaded methods MUST change the argument list


Overloaded methods CAN change the return type
Overloaded methods CAN change the access modifier
Overloaded methods CAN declare new or broader checked exceptions
A method can be overloaded in the same class or in a subclass

12.What is method overriding?


Method overriding occurs when sub class declares a method that has the same type arguments as a
method declared by one of its superclass. The key benefit of overriding is the ability to define behavior
thats
specific
to
a
particular
subclass
type.
Note:

The overriding method cannot have a more restrictive access modifier than the method being
overridden (Ex: You cant override a method marked public and make it protected).
You cannot override a method marked final
You cannot override a method marked static

13.What are the differences between method overloading and method overriding?
Overloaded Method

Overridden Method

Must change

Must not change

Return type

Can change

Cant change except for covariant


returns

Exceptions

Can change

Can reduce or eliminate. Must not


throw new or broader checked
exceptions

Access

Can change

Must not make more restrictive (can be


less restrictive)

Invocation

Reference type determines which


overloaded version is selected.
Happens at compile time.

Object type determines which method


is selected. Happens at runtime.

Arguments

14.Can overloaded methods be override too?


Yes, derived classes still can override the overloaded methods. Polymorphism can still happen.
Compiler will not binding the method calls since it is overloaded, because it might be overridden now
or in the future.
15.Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.
16.How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method
directly through a superclass instance, or use the super prefix in the subclass itself. From the point of
the view of the subclass, the super prefix provides an explicit reference to the superclass'
implementation of the method.
// From subclass
super.overriddenMethod();

17.What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a
method hides one of the member variables in its superclass, the method can refer to the hidden variable
through the use of the super keyword. In the same way, if a method overrides one of the methods in its
superclass, the method can invoke the overridden method through the use of the super keyword.
Note:

You can only go back one level.


In the constructor, if you use super(), it must be the very first code, and you cannot access any
this.xxx variables or methods to compute its parameters.

18.How do you prevent a method from being overridden?


To prevent a specific method from being overridden in a subclass, use the final modifier on the method
declaration, which means "this is the final implementation of this method", the end of its inheritance
hierarchy.
public final void exampleMethod() {
// Method statements
}
19.What is an Interface?
An interface is a description of a set of methods that conforming implementing classes must have.
Note:

You cant mark an interface as final.


Interface variables must be static.
An Interface cannot extend anything but another interfaces.

20.Can we instantiate an interface?


You cant instantiate an interface directly, but you can instantiate a class that implements an interface.
21.Can we create an object for an interface?
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be
instantiated in their own right, so you must write a class that implements the interface and fulfill all the
methods defined in it.
22.Do interfaces have member variables?
Interfaces may have member variables, but these are implicitly public, static, and final- in other words,
interfaces can declare only constants, not instance variables that are available to all implementations
and may be used as key references for method arguments for example.
23.What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

24.What is a marker interface?


Marker interfaces are those which do not declare any required methods, but signify their compatibility
with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces.
These do not contain any methods, but classes must implement this interface in order to be serialized
and de-serialized.
25.What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method
that
is
declared,
but
contains
no
implementation.
Note:

If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for
the abstract methods.
You cant mark a class as both abstract and final.

26.Can we instantiate an abstract class?


An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
27.What are the differences between Interface and Abstract class?
Abstract Class

Interfaces

An abstract class can provide complete, default


code and/or just the details that have to be
overridden.

An interface cannot provide any code at all,just the


signature.

In case of abstract class, a class may extend only


A Class may implement several interfaces.
one abstract class.
An abstract class can have non-abstract methods. All methods of an Interface are abstract.
An abstract class can have instance variables.

An Interface cannot have instance variables.

An abstract class can have any visibility: public,


private, protected.

An Interface visibility must be public (or) none.

If we add a new method to an abstract class then


we have the option of providing default
implementation and therefore all the existing
code might work properly.

If we add a new method to an Interface then we


have to track down all the implementations of the
interface and define implementation for the new
method.

An abstract class can contain constructors .

An Interface cannot contain constructors .

Abstract classes are fast.

Interfaces are slow as it requires extra indirection


to find corresponding method in the actual class.

28.When should I use abstract classes and when should I use interfaces?
Use Interfaces when

You see that something in your design will change frequently.


If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class,
then you go for the interface, which makes it easy to just implement and make use of the
methods defined in the interface.

Use Abstract Class when

If various implementations are of the same kind and use common behavior or status then
abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task
with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a
good choice for nonleaf classes in class hierarchies.

29.When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.
30.Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.
31.What is Constructor?

A constructor is a special method whose task is to initialize the object of its class.
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided?


If a class defined by the code does not have any constructor, compiler will automatically provide one
no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier
(public/private/etc.) of the default constructor is the same as the class itself.
33.Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.
34.What are the differences between Contructors and Methods?
Constructors

Methods

Purpose

Create an instance of a class

Group Java statements

Modifiers

Cannot be abstract, final, native,


static, or synchronized

Can be abstract, final, native, static, or


synchronized

Return Type

No return type, not even void

void or a valid return type

Name

Same name as the class (first letter is Any name except the class. Method
capitalized by convention) -- usually a names begin with a lowercase letter
noun
by convention -- usually the name of
an action

this

Refers to another constructor in the


Refers to an instance of the owning
same class. If used, it must be the first class. Cannot be used by static
line of the constructor
methods.

super

Calls the constructor of the parent


class. If used, must be the first line of
the constructor

Calls an overridden method in the


parent class

Inheritance

Constructors are not inherited

Methods are inherited

35.How are this() and super() used with constructors?

Constructors use this to refer to another constructor in the same class with a different parameter
list.
Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must
use it in the first line; otherwise, the compiler will complain.

36.What are the differences between Class Methods and Instance Methods?
Class Methods

Instance Methods

Instance methods on the other hand require an


instance of the class to exist before they can be
Class methods are methods which are declared as
called, so an instance of a class needs to be
static. The method can be called without creating
created by using the new keyword.
an instance of the class
Instance methods operate on specific instances of
classes.
Class methods can only operate on class members Instance methods of the class can also not be
and not on instance members as class methods are called from within a class method unless they are
unaware of instance members.
being called on an instance of that class.
Class methods are methods which are declared as
static. The method can be called without creating Instance methods are not declared as static.
an instance of the class.
37.How are this() and super() used with constructors?

Constructors use this to refer to another constructor in the same class with a different parameter
list.

Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must
use it in the first line; otherwise, the compiler will complain.

38.What are Access Specifiers?


One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data
in a class and making this class available only through methods. Java allows you to control access to
classes, methods, and fields via so-called access specifiers..
39.What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:

Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to which the
methods and fields belong, within its subclasses, and within classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or
field will be accessible from inside the same package to which the class, method, or field
belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the
methods and fields belong. private methods and fields are not visible within subclasses and are
not inherited by subclasses.
Situation

public

protected

default

private

Accessible to class
from same package?

yes

yes

yes

no

Accessible to class
from different package?

yes

no, unless it is a subclass

no

no

40.What is final modifier?


The final modifier keyword makes that the programmer cannot change the value anymore. The actual
meaning depends on whether it is applied to a class, a variable, or a method.

final Classes- A final class cannot have subclasses.


final Variables- A final variable cannot be changed once it is initialized.
final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method?


There are two reasons for marking a method as final:

Disallowing subclasses to change the meaning of the method.


Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

42.What is static block?


Static block which exactly executed exactly once when the class is first loaded into JVM. Before going
to the main method the static block will execute.

43.What are static variables?


Variables that have only one copy per class are known as static variables. They are not attached to a
particular instance of a class but rather belong to a class as a whole. They are declared by using the
static keyword as a modifier.
static type varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a
default value. The default value depends on the data type of the variables.
44.What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class.
Non-static variables take on unique values with each object instance.
45.What are static methods?
Methods declared with the keyword static as modifier are called static methods or class methods. They
are so called because they affect a class as a whole, not a particular instance of the class. Static methods
are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:

A static method can only call other static methods.


A static method must only access static data.
A static method cannot reference to the current object using keywords super or this.

46.What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal
flow of the program's instructions.
47.What is error?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a
subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be
reported by the JVM itself.
48.Which is superclass of Exception?
"Throwable", the parent class of all exception related classes.
49.What are the advantages of using exception handling?
Exception handling provides the following advantages over "traditional" error management techniques:

Separating Error Handling Code from "Regular" Code.


Propagating Errors Up the Call Stack.
Grouping Error Types and Error Differentiation.

50.What are the types of Exceptions in Java


There are two types of exceptions in Java, unchecked exceptions and checked exceptions.

Checked exceptions: A checked exception is some subclass of Exception (or Exception itself),
excluding class RuntimeException and its subclasses. Each method must either handle all
checked exceptions by supplying a catch clause or list each unhandled checked exception as a
thrown exception.
Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked
exceptions. Class Error and its subclasses also are unchecked.

51.Why Errors are Not Checked?


A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from
compile-time checking because they can occur at many points in the program and recovery from them
is difficult or impossible. A program declaring such exceptions would be pointlessly.
52.Why Runtime Exceptions are Not Checked?
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time
checking because, in the judgment of the designers of the Java programming language, having to
declare such exceptions would not aid significantly in establishing the correctness of programs. Many
of the operations and constructs of the Java programming language can result in runtime exceptions.
The information available to a compiler, and the level of analysis the compiler performs, are usually
not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious
to the programmer. Requiring such exception classes to be declared would simply be an irritation to
programmers.
53.Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do
this, we use the try and catch keywords. The try is used to define a block of code in which exceptions
may occur. One or more catch clauses match a specific exception to a block of code that handles it.

54.What is the use of finally block?


The finally block encloses code that is always executed at some point after the try block, whether an
exception was thrown or not. This is right place to close files, release your network sockets,
connections, and perform any other cleanup your code requires.
Note: If the try block executes with no exceptions, the finally block is executed immediately after the
try block completes. It there was an exception thrown, the finally block executes immediately after the
proper catch block completes
55.What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return statement
encountered, and before the return executes.
56.Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause.
57.What is the difference throw and throws?
throws: Used in a method's signature if a method is capable of causing an exception that it does not
handle, so that callers of the method can guard themselves against that exception. If a method is
declared as throwing a particular class of exceptions, then any other method that calls it must either
have a try-catch clause to handle that exception or must be declared to throw that exception (or its
superclass) itself.
A method that does not handle an exception it throws has to announce this:
public void myfunc(int arg) throws MyException {

}
throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that
can catch that type of exception. The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
To throw an user-defined exception within a block, we use the throw command:
throw new MyException("I always wanted to throw an exception!");
58.How to create custom exceptions?
A. By extending the Exception class or one of its subclasses.
Example:
class MyException extends Exception {
public MyException() { super(); }
public MyException(String s) { super(s); }

}
59.What are the different ways to handle exceptions?
There are two ways to handle exceptions:

Wrapping the desired code in a try block followed by a catch block to catch the exceptions.
List the desired exceptions in the throws clause of the method and let the caller of the method
handle those exceptions.

1.What is the JDBC?


Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form
Java. JDBC has set of classes and interfaces which can use from Java application and talk to database
without learning RDBMS details and using Database Specific JDBC Drivers.
2.What are the new features added to JDBC 4.0?
The major features added in JDBC 4.0 include :

Auto-loading of JDBC driver class


Connection management enhancements
Support for RowId SQL type
DataSet implementation of SQL using Annotations
SQL exception handling enhancements
SQL XML support

3.Explain Basic Steps in writing a Java program using JDBC?


JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to
access database :

Load the RDBMS specific JDBC driver because this driver actually communicates with the
database (Incase of JDBC 4.0 this is automatically loaded).
Open the connection to database which is then used to send SQL statements and get results
back.
Create JDBC Statement object. This object contains SQL query.
Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a
result of SQL query.
Process the result set.
Close the connection.

4.Exaplain the JDBC Architecture?


The JDBC Architecture consists of two layers:

The JDBC API, which provides the application-to-JDBC Manager connection.


The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct
driver is used to access each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases. The location of the driver
manager with respect to the JDBC drivers and the Java application is shown in Figure 1.

Figure 1: JDBC Architecture


5.What are the main components of JDBC ?
The life cycle of a servlet consists of the following phases:

DriverManager: Manages a list of database drivers. Matches connection requests from the java
application with the proper database driver using communication subprotocol. The first driver
that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.
Driver: The database communications link, handling all communication with the database.
Normally, once the driver is loaded, the developer need not call it explicitly.
Connection : Interface with all methods for contacting a database.The connection object
represents communication context, i.e., all communication with database is through connection
object only.
Statement : Encapsulates an SQL statement which is passed to the database to be parsed,
compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.

6.How the JDBC application works?


A JDBC application can be logically divided into two layers:
1. Driver layer

2. Application layer

Driver layer consists of DriverManager class and the available JDBC drivers.
The application begins with requesting the DriverManager for the connection.
An appropriate driver is choosen and is used for establishing the connection. This connection is
given to the application which falls under the application layer.
The application uses this connection to create Statement kind of objects, through which SQL
commands are sent to backend and obtain the results.

Figure 2: JDBC Application


7.How do I load a database driver with JDBC 4.0 / Java 6?
Provided the JAR file containing the driver is properly configured, just place the JAR file in the
classpath. Java developers NO longer need to explicitly load JDBC drivers using code like
Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically
locating a suitable driver when the DriverManager.getConnection() method is called. This feature is
backward-compatible, so no changes are needed to the existing JDBC code.
8.What is JDBC Driver interface?
The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided
by the JDBC API. Each vendor driver must provide implementations of the
java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.
9.What does the connection object represents?
The connection object represents communication context, i.e., all communication with database is
through connection object only.
10.What is Statement ?
Statement acts like a vehicle through which SQL commands can be sent. Through the connection object
we
create
statement
kind
of
objects.
Through the connection object we create statement kind of objects.
Statement stmt = conn.createStatement();
This method returns object which implements statement interface.

11.What is PreparedStatement?
A prepared statement is an SQL statement that is precompiled by the database. Through
precompilation, prepared statements improve the performance of SQL commands that are executed
multiple times (given that the database supports prepared statements). Once compiled, prepared
statements can be customized prior to each execution by altering predefined SQL parameters.
PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ?
WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);
Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must
be specified before execution.

12.What is the difference between a Statement and a PreparedStatement?


Statement

PreparedStatement

A standard Statement is used to create a


Java representation of a literal SQL
statement and execute it on the database.

A PreparedStatement is a precompiled statement. This


means that when the PreparedStatement is executed, the
RDBMS can just run the PreparedStatement SQL
statement without having to compile it first.

Statement has to verify its metadata against


the database every time.

While a prepared statement has to verify its metadata


against the database only once.

If you want to execute the SQL statement


once go for STATEMENT

If you want to execute a single SQL statement multiple


number of times, then go for
PREPAREDSTATEMENT. PreparedStatement objects
can be reused with passing different values to the
queries

13.What are callable statements ?


Callable statements are used from JDBC application to invoke stored procedures and functions.
14.How to call a stored procedure from JDBC ?
PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall()
method of the Connection object created. A call to this method takes variable bind parameters as input
parameters as well as output variables and creates an object instance of the CallableStatement class.
The following line of code illustrates this:
CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");
Here conn is an instance of the Connection class.

15.What are types of JDBC drivers?


There are four types of drivers defined by JDBC as follows:

Type 1: JDBC/ODBCThese require an ODBC (Open Database Connectivity) driver for the
database to be installed. This type of driver works by translating the submitted queries into
equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver.
It provides no host redirection capability.
Type2: Native API (partly-Java driver)This type of driver uses a vendor-specific driver or
database API to interact with the database. An example of such an API is Oracle OCI (Oracle
Call Interface). It also provides no host redirection.
Type 3: Open Protocol-NetThis is not vendor specific and works by forwarding database
requests to a remote database source using a net server component. How the net server
component accesses the database is transparent to the client. The client driver communicates
with the net server using a database-independent protocol and the net server translates this
protocol into database calls. This type of driver can access any database.
Type 4: Proprietary Protocol-Net(pure Java driver)This has a same configuration as a type 3
driver but uses a wire protocol specific to a particular vendor and hence can access only that
vendor's database. Again this is all transparent to the client.

Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.


16.Which type of JDBC driver is the fastest one?
JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into
vendor specific protocol calls and it directly interacts with the database.
17.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
No. You can open only one Statement object per connection when you are using the JDBC-ODBC
Bridge.
18.Which is the right type of driver to use and when?

Type I driver is handy for prototyping


Type III driver adds security, caching, and connection control
Type III and Type IV drivers need no pre-installation

Note: Preferred by 9 out of 10 Java developers: Type IV.


19.What are the standard isolation levels defined by JDBC?
The values are defined in the class java.sql.Connection and are:

TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels.

20.What is resultset ?
The ResultSet represents set of rows retrieved due to query execution.
ResultSet rs = stmt.executeQuery(sqlQuery);
21.What are the types of resultsets?
The values are defined in the class java.sql.Connection and are:

TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can
be advanced only in the forward direction.
TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is
insensitive to changes committed by other transactions or other statements in the same
transaction.
TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is
affected by changes committed by other transactions or statements within the same transaction.

Note: A TYPE_FORWARD_ONLY resultset is always insensitive.


22.Whats the difference between TYPE_SCROLL_INSENSITIVE and
TYPE_SCROLL_SENSITIVE?
TYPE_SCROLL_INSENSITIVE

TYPE_SCROLL_SENSITIVE

A sensitive resultset does NOT represent a


An insensitive resultset is like the snapshot of the
snapshot of data, rather it contains points to those
data in the database when query was executed.
rows which satisfy the query condition.
After we get the resultset the changes made to data After we obtain the resultset if the data is
are not visible through the resultset, and hence
modified then such modifications are visible
they are known as insensitive.
through resultset.
Performance not effected with insensitive.

Since a trip is made for every get operation, the


performance drastically get affected.

22.What is rowset?
A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC)
result sets or tabular data sources like a file or spreadsheet. RowSets support component-based
development models like JavaBeans, with a standard set of properties and an event notification
mechanism.
24.What are the different types of RowSet ?
There are two types of RowSet are there. They are:

Connected - A connected RowSet object connects to the database once and remains connected
until the application terminates.
Disconnected - A disconnected RowSet object connects to the database, executes a query to
retrieve the data from the database and then closes the connection. A program may change the
data in a disconnected RowSet while it is disconnected. Modified data can be updated in the

database after a disconnected RowSet reestablishes the connection with the database.
25.What is the need of BatchUpdates?
The BatchUpdates feature allows us to group SQL statements together and send to database server in
one single trip.
26.What is a DataSource?
A DataSource object is the representation of a data source in the Java programming language. In basic
terms,

A DataSource is a facility for storing data.


DataSource can be referenced by JNDI.
Data Source may point to RDBMS, file System , any DBMS etc..

27.What are the advantages of DataSource?


The few advantages of data source are :

An application does not need to hardcode driver information, as it does with the DriverManager.
The DataSource implementations can easily change the properties of data sources. For example:
There is no need to modify the application code when making changes to the database details.
The DataSource facility allows developers to implement a DataSource class to take advantage
of features like connection pooling and distributed transactions.

28.What is connection pooling? what is the main advantage of using connection pooling?
A connection pool is a mechanism to reuse connections created. Connection pooling can increase
performance dramatically by reusing connections rather than creating a new physical connection each
time a connection is requested..

1.What is the Servlet?


A servlet is a Java programming language class that is used to extend the capabilities of servers that
host applications accessed by means of a request- response programming model.
2.What are the new features added to Servlet 2.5?
Following are the changes introduced in Servlet 2.5:

A new dependency on J2SE 5.0


Support for annotations
Loading the class
Several web.xml conveniences
A handful of removed restrictions
Some edge case clarifications

3.What are the uses of Servlet?


Typical uses for HTTP Servlets include:

Processing and/or storing data submitted by an HTML form.


Providing dynamic content, e.g. returning the results of a database query to the client.
A Servlet can handle multiple request concurrently and be used to develop high performance
system
Managing state information on top of the stateless HTTP, e.g. for an online shopping cart
system which manages shopping carts for many concurrent customers and maps every request
to the right customer.

4.What are the advantages of Servlet over CGI?


Servlets have several advantages over CGI:

A Servlet does not run in a separate process. This removes the overhead of creating a new
process for each request.
A Servlet stays in memory between requests. A CGI program (and probably also an extensive
runtime system or interpreter) needs to be loaded and started for each CGI request.
There is only a single instance which answers all requests concurrently. This saves memory and
allows a Servlet to easily manage persistent data.
Several web.xml conveniences
A handful of removed restrictions
Some edge case clarifications

5.What are the phases of the servlet life cycle?


The life cycle of a servlet consists of the following phases:

Servlet class loading : For each servlet defined in the deployment descriptor of the Web
application, the servlet container locates and loads a class of the type of the servlet. This can
happen when the servlet engine itself is started, or later when a client request is actually
delegated to the servlet.
Servlet instantiation : After loading, it instantiates one or more object instances of the servlet
class to service the client requests.

Initialization (call the init method) : After instantiation, the container initializes a servlet before
it is ready to handle client requests. The container initializes the servlet by invoking its init()
method, passing an object implementing the ServletConfig interface. In the init() method, the
servlet can read configuration parameters from the deployment descriptor or perform any other
one-time activities, so the init() method is invoked once and only once by the servlet container.

Request handling (call the service method) : After the servlet is initialized, the container may
keep it ready for handling client requests. When client requests arrive, they are delegated to the
servlet through the service() method, passing the request and response objects as parameters. In
the case of HTTP requests, the request and response objects are implementations of
HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service()
method invokes a different handler method for each type of HTTP request, doGet() method for
GET requests, doPost() method for POST requests, and so on.
Removal from service (call the destroy method) : A servlet container may decide to remove a
servlet from service for various reasons, such as to conserve memory resources. To do this, the
servlet container calls the destroy() method on the servlet. Once the destroy() method has been
called, the servlet may not service any more client requests. Now the servlet instance is eligible
for garbage collection

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
6.Why do we need a constructor in a servlet if we use the init method?
Even though there is an init method in a servlet which gets called to initialize it, a constructor is still
required to instantiate the servlet. Even though you as the developer would never need to explicitly call
the servlet's constructor, it is still being used by the container (the container still uses the constructor to

create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init
method, it is no use calling the init method if you haven't constructed an object to call it on yet.
7.How the servlet is loaded?
A servlet can be loaded when:

First request is made.


Server starts up (auto-load).
There is only a single instance which answers all requests concurrently. This saves memory and
allows a Servlet to easily manage persistent data.
Administrator manually loads.

8.How a Servlet is unloaded?


A servlet is unloaded when:

Server shuts down.


Administrator manually unloads.

9.What is Servlet interface?


The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface,
either directly or , more commonly by extending a class that implements it.

Note: Most Servlets, however, extend one of the standard implementations of that interface, namely
javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.
10.What is the GenericServlet class?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig
interface. In addition to the methods declared in these two interfaces, this class also provides simple

versions of the lifecycle methods init and destroy, and implements the log method declared in the
ServletContext
interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.
11.What's the difference between GenericServlet and HttpServlet?
GenericServlet

HttpServlet

The GenericServlet is an abstract class that is


extended by HttpServlet to provide protocolspecific methods.

An abstract class that simplifies writing HTTP


servlets. It extends the GenericServlet base class
and provides an framework for handling the
HTTP protocol.

The GenericServlet does not include protocolThe HttpServlet subclass passes generic service
specific methods for handling request parameters, method requests to the relevant doGet() or
cookies, sessions and setting response headers.
doPost() method.
GenericServlet is not specific to any protocol.

HttpServlet only supports HTTP and HTTPS


protocol.

12.Why is HttpServlet declared abstract?


The HttpServlet class is declared abstract because the default implementations of the main service
methods do nothing and must be overridden. This is a convenience implementation of the Servlet
interface, which means that developers do not need to implement all service methods. If your servlet is
required to handle doGet() requests for example, there is no need to write a doPost() method too.
13.Can servlet have a constructor ?
One can definitely have constructor in servlet.Even you can use the constrctor in servlet for
initialization purpose,but this type of approch is not so common. You can perform common operations
with the constructor as you normally do.The only thing is that you cannot call that constructor
explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible
for instantiating the servlet, so the constructor is also called by servlet container only.
14.What are the types of protocols supported by HttpServlet ?
It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So,
HttpServlet only supports HTTP and HTTPS protocol.
15.What is the difference between doGet() and doPost()?
# doGet()
1

In doGet() the parameters are appended to the


URL and sent along with header information.

doPost()
In doPost(), on the other hand will (typically)
send the information through a socket back to the
webserver and it won't show up in the URL bar.

2 The amount of information you can send back You can send much more information to the
using a GET is restricted as URLs can only be server this way - and it's not restricted to textual

1024 characters.

data either. It is possible to send files and even


binary data such as serialized Java objects!

doGet() is a request for information; it does


3 not (or should not) change anything on the
server. (doGet() should be idempotent)

doPost() provides information (such as placing an


order for merchandise) that the server is expected
to remember

4 Parameters are not encrypted

Parameters are encrypted

doPost() is generally used to update or post some


doGet() is faster if we set the response content
information to the server.doPost is slower
5 length since the same connection is used. Thus
compared to doGet since doPost does not write
increasing the performance
the content length
doGet() should be idempotent. i.e. doget
6 should be able to be repeated safely many
times
7

doGet() should be safe without any side


effects for which user is held responsible

8 It allows bookmarks.

This method does not need to be idempotent.


Operations requested through POST can have
side effects for which the user can be held
accountable.
This method does not need to be either safe
It disallows bookmarks.

16.When to use doGet() and when doPost()?


Always prefer to use GET (As because GET is faster than POST), except mentioned in the following
reason:

If data is sensitive
Data is greater than 1024 characters
If your application don't need bookmarks.

17.How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
18.Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it . The
default service function invokes the doXXX() method corresponding to the method of the HTTP
request.For example, if the HTTP request method is GET, doGet() method is called by default. A

servlet should override the doXXX() method for the HTTP methods that servlet supports. Because
HTTP service method check the request method and calls the appropriate handler method, it is not
necessary to override the service method itself. Only override the appropriate doXXX() method.
19.How the typical servlet code look like ?

20.What is a servlet context object?


A servlet context object contains the information about the Web application of which the servlet is a
part. It also provides access to the resources common to all the servlets in the application. Each Web
application in a container has a single servlet context associated with it.
21.What are the differences between the ServletConfig interface and the ServletContext interface?
ServletConfig

ServletContext

The ServletConfig interface is implemented by


the servlet container in order to pass

A ServletContext defines a set of methods that a


servlet uses to communicate with its servlet

configuration information to a servlet. The server


passes an object that implements the
container.
ServletConfig interface to the servlet's init()
method.
There is one ServletConfig parameter per servlet.

There is one ServletContext for the entire webapp


and all the servlets in a webapp share it.

The param-value pairs for ServletConfig object


are specified in the <init-param> within the
<servlet> tags in the web.xml file

The param-value pairs for ServletContext object


are specified in the <context-param> tags in the
web.xml file.

22.What's the difference between forward() and sendRedirect() methods?


forward()

sendRedirect()

A forward is performed internally by the servlet.

A redirect is a two step process, where the web


application instructs the browser to fetch a second
URL, which differs from the original.

The browser is completely unaware that it has


taken place, so its original URL remains intact.

The browser, in this case, is doing the work and


knows that it's making a new request.

Any browser reload of the resulting page will


simple repeat the original request, with the
original URL

A browser reloads of the second URL ,will not


repeat the original request, but will rather fetch
the second URL.

Both resources must be part of the same context


(Some containers make provisions for crosscontext communication but this tends not to be
very portable)

This method can be used to redirect users to


resources that are not part of the current context,
or even in the same domain.

Since both resources are part of same context, the


original request context is retained

Because this involves a new request, the previous


request scope objects, with all of its parameters
and attributes are no longer available after a
redirect.
(Variables will need to be passed by via the
session object).

Forward is marginally faster than redirect.

redirect is marginally slower than a forward, since


it requires two browser requests, not one.

23.What is the difference between the include() and forward() methods?


include()

forward()

The RequestDispatcher include() method inserts


the the contents of the specified resource directly
in the flow of the servlet response, as if it were

The RequestDispatcher forward() method is used


to show a different resource in place of the servlet
that was originally called.

part of the calling servlet.


If you include a servlet or JSP document, the
included resource must not attempt to change the
response status code or HTTP headers, any such
request will be ignored.

The forwarded resource may be another servlet,


JSP or static HTML document, but the response is
issued under the same URL that was originally
requested. In other words, it is not the same as a
redirection.

The include() method is often used to include


common "boilerplate" text or template markup
that may be included by many servlets.

The forward() method is often used where a


servlet is taking a controller role; processing some
input and deciding the outcome by returning a
particular response page.

24.What's the use of the servlet wrapper classes?


The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy
for developers to create custom implementations of the servlet request and response types. The classes
are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively
and their default behaviour is to pass all method calls directly to the underlying objects.
25.What is a deployment descriptor?
A deployment descriptor is an XML document with an .xml extension. It defines a component's
deployment settings. It declares transaction attributes and security authorization for an enterprise bean.
The information provided by a deployment descriptor is declarative and therefore it can be modified
without
changing
the
source
code
of
a
bean.
The JavaEE server reads the deployment descriptor at run time and acts upon the component
accordingly.
26.What is the difference between the getRequestDispatcher(String path) method of
javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
ServletRequest.getRequestDispatcher(String
path)
The getRequestDispatcher(String path) method of
javax.servlet.ServletRequest interface accepts
parameter the path to the resource to be included
or forwarded to, which can be relative to the
request of the calling servlet. If the path begins
with a / it is interpreted as relative to the
current context root.

ServletContext.getRequestDispatcher(String path)

The getRequestDispatcher(String path) method of


javax.servlet.ServletContext interface cannot
accept relative paths. All path must start with a /
and are interpreted as relative to current context
root.

27.What is the directory structure of a WAR file?

28.What is preinitialization of a servlet?


A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives
a request for that servlet first time. This is called lazy loading. The servlet specification defines the
element, which can be specified in the deployment descriptor to make the servlet container load and
initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in
is called preloading or preinitializing a servlet.
29.What is the <load-on-startup> element?
The <load-on-startup> element of a deployment descriptor is used to load a servlet file when the server
starts instead of waiting for the first request. It is also used to specify the order in which the files are to
be loaded. The <load-on-startup> element is written in the deployment descriptor as follows:
<servlet>

<servlet-name>ServletName</servlet-name>
<servlet-class>ClassName</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Note: The container loads the servlets in the order specified in the <load-on-startup> element.
30.What is session?

A session refers to all the requests that a single client might make to a server in the course of viewing
any pages associated with a given application. Sessions are specific to both the individual user and the
application. As a result, every user of an application has a separate session and has access to a separate
set of session variables.
31.What is Session Tracking?
Session tracking is a mechanism that servlets use to maintain state about a series of requests from the
same user (that is, requests originating from the same browser) across some period of time.
32.What is the need of Session Tracking in web application?
HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be
more realistic they have to retain information across multiple requests. Such information which is part
of the application is reffered as "state". To keep track of this state we need session tracking.
Typical example: Putting things one at a time into a shopping cart, then checking out--each page
request must somehow be associated with previous requests.
33.What are the types of Session Tracking ?
Sessions need to work with all web browsers and take into account the users security preferences.
Therefore there are a variety of ways to send and receive the identifier:

URL rewriting : URL rewriting is a method of session tracking in which some extra data
(session ID) is appended at the end of each URL. This extra data identifies the session. The
server can associate this session identifier with the data it has stored about that session. This
method is used with browsers that do not support cookies or where the user has disabled the
cookies.
Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every

dynamically generated form page for the client. When the client submits the form to the server
the hidden fields identify the client.
Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by
the browser, and later sent back to the server in subsequent requests. A cookie has a name, a
single value, and optional attributes. A cookie's value can uniquely identify a client.
Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer
communication can use SSL's support via HTTPS for generating a unique session key as part of
the encrypted conversation.

34.How do I use cookies to store session state on the client?


In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method
HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted
during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom
tag code.

To set a cookie on the client, use the addCookie() method in class HttpServletResponse.
Multiple cookies may be set for the same request, and a single cookie name may have multiple
values.
To get all of the cookies associated with a single HTTP request, use the getCookies() method of
class HttpServletRequest

35.What are some advantages of storing session state in cookies?

Cookies are usually persistent, so for low-security sites, user data that needs to be stored longterm (such as a user ID, historical information, etc.) can be maintained easily with no server
interaction.
For small- and medium-sized session data, the entire session data (instead of just the session ID)
can be kept in the cookie.

36.What are some disadvantages of storing session state in cookies?

Cookies are controlled by programming a low-level API, which is more difficult to implement
than some other approaches.
All data for a session are kept on the client. Corruption, expiration or purging of cookie files can
all result in incomplete, inconsistent, or missing information.
Cookies may not be available for many reasons: the user may have disabled them, the browser
version may not support them, the browser may be behind a firewall that filters cookies, and so
on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not
operate properly for all clients. Using cookies, and then switching to an alternate client-side
session state strategy in cases where cookies aren't available, complicates development and
maintenance.
Browser instances share cookies, so users cannot have multiple simultaneous sessions.
Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the
HTTP protocol. Notice that the while package javax.servlet.http supports session management
(via class HttpSession), package javax.servlet has no such support.

37.What is URL rewriting?

URL rewriting is a method of session tracking in which some extra data is appended at the end of each
URL. This extra data identifies the session. The server can associate this session identifier with the data
it has stored about that session.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time
a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if
the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs

Advantages
URL rewriting works just about everywhere, especially when cookies are turned off.
Multiple simultaneous sessions are possible for a single user. Session information is local to
each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't
foolproof, though, since users can start a new browser instance using a URL for an active
session, and confuse the server by interacting with the same session through two instances.
Entirely static pages cannot be used with URL rewriting, since every link must be dynamically
written with the session state. It is possible to combine static and dynamic content, using (for
example) templating or server-side includes. This limitation is also a barrier to integrating
legacy web pages with newer, servlet-based pages.
DisAdvantages
Every URL on a page which needs the session information must be rewritten each time a page is
served. Not only is this expensive computationally, but it can greatly increase communication
overhead.
URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in
awkward restrictions on the page.
URL rewriting does not work well with JSP technology.
If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are
lost.

38.How can an existing session be invalidated?


An existing session can be invalidated in the following two ways:

Setting timeout in the deployment descriptor: This can be done by specifying timeout between
the <session-timeout>tags as follows:
<session-config>
<session-timeout>10</session-timeout>
</session-config>
This will set the time for session timeout to be ten minutes.

Setting timeout programmatically: This will set the timeout for a specific session. The syntax
for setting the timeout programmatically is as follows:
public void setMaxInactiveInterval(int interval)
The setMaxInactiveInterval() method sets the maximum time in seconds before a session
becomes invalid.

Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e,
session never expires.
39.How can the session in Servlet can be destroyed?
An existing session can be destroyed in the following two ways:

Programatically : Using session.invalidate() method, which makes the container abonden the
session on which the method is called.
When the server itself is shutdown.

40.A client sends requests to two different web components. Both of the components access the
session. Will they end up using the same session object or different session ?
Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping between
client and a session.
41.What is servlet lazy loading?

A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it
receives a request for that servlet first time. This is called lazy loading.
The servlet specification defines the <load-on-startup> element, which can be specified in the
deployment descriptor to make the servlet container load and initialize the servlet as soon as it
starts up.
The process of loading a servlet before any request comes in is called preloading or
preinitializing a servlet.

42.What is Servlet Chaining?


Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output
of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns
the output to the Web browser.
43.How are filters?
Filters are Java components that are used to intercept an incoming request to a Web resource and a
response sent back from the resource. It is used to abstract any useful information contained in the
request or response. Some of the important functions performed by filters are as follows:

Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression

Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required
to recompile anything to change the input or output of the Web application.
44.What are the functions of an intercepting filter?

The functions of an intercepting filter are as follows:

It intercepts the request from a client before it reaches the servlet and modifies the request if
required.
It intercepts the response from the servlet back to the client and modifies the request if required.
There can be many filters forming a chain, in which case the output of one filter becomes an

input to the next filter. Hence, various modifications can be performed on a single request and
response.

45.What are the functions of the Servlet container?


The functions of the Servlet container are as follows:

Lifecycle management : It manages the life and death of a servlet, such as class loading,
instantiation, initialization, service, and making servlet instances eligible for garbage collection.
Communication support : It handles the communication between the servlet and the Web server.
Multithreading support : It automatically creates a new thread for every servlet request received.
When the Servlet service() method completes, the thread dies.
Declarative security : It manages the security inside the XML deployment descriptor file.
JSP support : The container is responsible for converting JSPs to servlets and for maintaining
them.

1.What are the advantages of JSP over Servlet?


JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that
they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page
can contain Java program fragments that instantiate and execute Java classes, but these occur inside an
HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality
can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides
a framework for Web application development.
2.What is the life-cycle of JSP?
When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class
and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:

Translation
Compilation
Loading the class
Instantiating the class
jspInit() invocation
_jspService() invocation
jspDestroy() invocation

3.What is the jspInit() method?


The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets.
This method is invoked by the container only once when a JSP page is initialized. It can be overridden
by a page author to initialize resources such as database and network connections, and to allow a JSP
page to read persistent configuration data.
4.What is the _jspService() method?
SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new
request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse
objects as its arguments. A page author cannot override this method, as its implementation is provided
by the container.
5.What is the jspDestroy() method?
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a
JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be
overridden by a page author to perform any cleanup operation such as closing a database connection.
6.What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the
jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources
like database connections, network connections, and so forth for the JSP page. It is good programming
practice to free any allocated resources within jspDestroy().

7.How can I override the jspInit() and jspDestroy() methods within a JSP page?
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page
and are typically declared as JSP declarations:
<%!
public void jspInit() {
...
}
%>
<%!
public void jspDestroy() {
...
}
%>
8.What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in
each page. These objects need not be declared or instantiated by the JSP author. They are automatically
instantiated by the container and are accessed using standard variables; hence, they are called implicit
objects.The implicit objects available in JSP are as follows:

request
response
pageContext
session
application
out
config
page
exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are
available only within the jspService method and not in any declaration.
9.What are JSP directives?

JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a
JSP page to the JSP container and control the processing of the entire page
They are used to set global values such as a class declaration, method implementation, output
content type, etc.
They do not produce any output to the client.
Directives are always enclosed within <%@ .. %> tag.
Ex: page directive, include directive, etc.

10.What are the different types of JSP tags?


The different types of JSP tags are as follows:

11.What is page directive?

A page directive is to inform the JSP engine about the headers or facilities that page should get
from the environment.
Typically, the page directive is found at the top of almost all of our JSP pages.
There can be any number of page directives within a JSP page (although the attribute value
pair must be unique).
The syntax of the include directive is: <%@ page attribute="value">
Example:<%@ include file="header.jsp" %>

12.What are the attributes of page directive?


There are thirteen attributes defined for a page directive of which the important attributes are as
follows:

import: It specifies the packages that are to be imported.


session: It specifies whether a session data is available to the JSP page.
contentType: It allows a user to set the content-type for a page.
isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a
servlet.

13.What is the include directive?


There are thirteen attributes defined for a page directive of which the important attributes are as
follows:

The include directive is used to statically insert the contents of a resource into the current JSP.
This enables a user to reuse the code without duplicating it, and includes the contents of the
specified file at the translation time.
The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
This directive has only one attribute called file that specifies the name of the file to be included.

14.What are the JSP standard actions?

The JSP standard actions affect the overall runtime behavior of a JSP page and also the response
sent back to the client.
They can be used to include a file at the request time, to find or instantiate a JavaBean, to
forward a request to a new page, to generate a browser-specific code, etc.
Ex: include, forward, useBean,etc. object

15.What are the standard actions available in JSP?


The standard actions available in JSP are as follows:

<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs
from an include directive in that it includes a resource at request processing time, whereas the
include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the
response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a
parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

16.What is the <jsp:useBean> standard action?


The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a JavaBean if it
does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to
specify the fully qualified classpath and type.
17.What are the scopes available in <jsp:useBean>?
The scopes available in <jsp:useBean> are as follows:

page scope:: It specifies that the object will be available for the entire JSP page but not outside
the page.
request scope: It specifies that the object will be associated with a particular request and exist as
long as the request exists.
application scope: It specifies that the object will be available throughout the entire Web

application but not outside the application.


session scope: It specifies that the object will be available throughout the session with a
particular client.

18.What is the <jsp:forward> standard action?

The <jsp:forward> standard action forwards a response from a servlet or a JSP page to another
page.
The execution of the current page is stopped and control is transferred to the forwarded page.
The syntax of the <jsp:forward> standard action is :
<jsp:forward page="/targetPage" />
Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.
If anything is written to the output stream that is not buffered before <jsp:forward>, an
IllegalStateException will be thrown.

Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should be


enabled. By default buffer is enabled.
19.What is the <jsp:include> standard action?
The <jsp:include> standard action enables the current JSP page to include a static or a dynamic
resource at runtime. In contrast to the include directive, the include action is used for resources that
change frequently. The resource to be included must be in the same context.The syntax of the
<jsp:include>
standard
action
is
as
follows:
<jsp:include
page="targetPage"
flush="true"/>
Here, targetPage is the page to be included in the current JSP.
20.What is the difference between include directive and include action?
Include directive

Include action

The include directive, includes the content of the


specified file during the translation phasewhen
the page is converted to a servlet.

The include action, includes the response


generated by executing the specified page (a JSP
page or a servlet) during the request processing
phasewhen the page is requested by a user.

The include directive is used to statically insert


the contents of a resource into the current JSP.

The include standard action enables the current


JSP page to include a static or a dynamic resource
at runtime.

Use the include action only for content that


Use the include directive if the file changes rarely. changes often, and if which page to include
Its the fastest mechanism.
cannot be decided until the main page is
requested.
21.Differentiate between pageContext.include and jsp:include?
The <jsp:include> standard action and the pageContext.include() method are both used to include
resources at runtime. However, the pageContext.include() method always flushes the output of the
current page before including the other components, whereas <jsp:include> flushes the output of the

current page only if the value of flush is explicitly set to true as follows:
<jsp:include page="/index.jsp" flush="true"/>
22.What is the jsp:setProperty action?
You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can
do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element,
as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName" property="myProperty" ... />
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an
existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as
below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName"
property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was
found.

23.What is the jsp:getProperty action?


The <jsp:getProperty> action is used to access the properties of a bean that was set using the
<jsp:getProperty> action. The container converts the property to a String as follows:

If it is an object, it uses the toString() method to convert it to a String.


If it is a primitive, it converts it directly to a String using the valueOf() method of the
corresponding Wrapper class.
The syntax of the <jsp:getProperty> method is: <jsp:getProperty name="Name"
property="Property" />

Here, name is the id of the bean from which the property was set. The property attribute is the property
to get. A user must create or locate a bean using the <jsp:useBean> action before using the
<jsp:getProperty> action.

24.What is the <jsp:param> standard action?


The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter names
and values to the target resource. The syntax of the <jsp:param> standard action is as follows:
<jsp:param name="paramName" value="paramValue"/>

25.What is the jsp:plugin action ?


This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the
browser run an applet using the Java plugin.
26.What are scripting elements?
JSP scripting elements let you insert Java code into the servlet that will be generated from the current
JSP page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class,
outside of any existing methods.
27.What is a scriptlet?
A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to
a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in
scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is
executed by the container at request processing time.
28.What are JSP declarations?
As the name implies, JSP declarations are used to declare class variables and methods in a JSP page.
They are initialized when the class is initialized. Anything defined in a declaration is available for the
whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not
included in the service() method when a JSP is translated to a servlet.
29.What is a JSP expression?
A JSP expression is used to write an output without using the out.print statement. It can be said as a
shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not
required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions
within the expression tags.
30.How is scripting disabled?
Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a
subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting
is as follows:
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>

1.What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples
interface from business logic and data.

Model : The model contains the core of the application's functionality. The model encapsulates
the state of the application. Sometimes the only functionality it contains is state. It knows
nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The
view can access the model getters, but it has no knowledge of the setters. In addition, it knows
nothing about the controller. The view should be notified when changes to the model occur.
Controller:The controller reacts to the user input. It creates and sets the model.

Model-View-Controller (MVC) Architecture


Introduction
A design pattern describes a proven solution to a recurring design problem, placing particular emphasis
on the context and forces surrounding the problem, and the consequences and impact of the solution.
There are many good reasons to use design patterns. Here are three:

They are proven. You tap the experience, knowledge and insights of developers who have used
these patterns successfully in their own work.
They are reusable. When a problem recurs, you don't have to invent a new solution; you follow
the pattern and adapt it as necessary.
They are expressive. Design patterns provide a common vocabulary of solutions, which you can
use to express larger solutions succinctly.

It is important remember, however, that design patterns do not guarantee success. You can only
determine whether a pattern is applicable by carefully reading its description, and only after you've
applied it in your own work can you determine whether it has helped any. One of these patters is
Model-View-Controller (MVC). Smalltalk defined it in the 70's. Since that time, the MVC design
idiom has become commonplace, especially in object-oriented systems.

MVC Architecture
The goal of the MVC design pattern is to separate the application object (model) from the way it is
represented to the user (view) from the way in which the user controls it (controller).
The Model object knows about all the data that need to be displayed. It also knows about all the
operations that can be applied to transform that object. However, it knows nothing whatever about the
GUI, the manner in which the data are to be displayed, nor the GUI actions that are used to manipulate
the data. The data are accessed and manipulated through methods that are independent of the GUI. The
model represents enterprise data and the business rules that govern access to and updates of this data.
Often the model serves as a software approximation to a real-world process, so simple real-world
modeling techniques apply when defining the model.

The View object refers to the model. It uses the query methods of the model to obtain data from the
model and then displays the information. A view renders the contents of a model. It accesses enterprise
data through the model and specifies how that data should be presented. It is the view's responsibility to
maintain consistency in its presentation when the model changes.

The Controller object knows about the physical means by which users manipulate data within the
model. A controller translates interactions with the view into actions to be performed by the model. In a
stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web
application, they appear as GET and POST HTTP requests. The actions performed by the model
include activating business processes or changing the state of the model. Based on the user interactions
and the outcome of the model actions, the controller responds by selecting an appropriate view.
In GUIs, views and controllers often work very closely together. For example, a controller is
responsible for updating a particular parameter in the model that is then displayed by a view. In some
cases a single object may function as both a controller and a view. Each controller-view pair is
associated with only one model, however a particular model can have many view-controller pairs.

Advantages
The MVC architecture has the following benefits:

Multiple views using the same model: The separation of model and view allows multiple
views to use the same enterprise model. Consequently, an enterprise application's model
components are easier to implement, test, and maintain, since all access to the model goes
through these components.
Easier support for new types of clients: To support a new type of client, you simply write a
view and controller for it and wire them into the existing enterprise model.
Clarity of design: By glancing at the model's public method list, it should be easy to understand
how to control the model's behavior. When designing the application, this trait makes the entire
program easier to implement and maintain.
Efficient modularity: of the design allows any of the components to be swapped in and out as
the user or programmer desires - even the model! Changes to one aspect of the program aren't
coupled to other aspects, eliminating many nasty debugging situations. Also, development of
the various components can progress in parallel, once the interface between the components is
clearly defined.
Ease of growth: Controllers and views can grow as the model grows; and older versions of the
views and controllers can still be used as long as a common interface is maintained.
Distributable: With a couple of proxies one can easily distribute any MVC application by only
altering the startup method of the application.

2.What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for
a specific requirement.

3.What is Struts framework?


Struts framework is an open-source framework for developing the web applications in Java EE, based
on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can
be used for the development of application of any size. Struts framework makes it much easier to
design scalable, reliable Web applications with Java.
4.What are the components of Struts?
Struts components can be categorize into Model, View and Controller:

Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front
controller to handle all the requests.

5.What are the core classes of the Struts Framework?


Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.

JavaBeans components for managing application state and behavior.


Event-driven development (via listeners as in traditional GUI development).
Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main
Controller component that handles client requests and determines which Action will process each
received request. It serves as an Action factory creating specific Action classes based on users
request.
7.What is role of ActionServlet?
ActionServlet performs the role of Controller:

Process user requests


Determine what the user is trying to achieve according to the request
Pull data from the model (if necessary) to be given to the appropriate view,
Select the proper view to respond to the user
Delegates most of this grunt work to Action classes
Is responsible for initialization and clean-up of resources

8.What is the ActionForm?


ActionForm is javabean which represents the form inputs containing the request parameters from the
View referencing the Action bean.
9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().
10.Describe validate() and reset() methods ?
validate() : Used to validate properties after they have been populated; Called before FormBean is
handed to Action. Returns a collection of ActionError as ActionErrors. Following is the

method signature for the validate() method.


public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

reset(): reset() method is called by Struts Framework with each request that uses the defined
ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the
new request values being set.
public void reset() {}

11.What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class is to
determine where the results of the Action will be sent once its processing is complete.
12.How is the Action Mapping specified ?
We can specify the action mapping in the configuration file called struts-config.xml. Struts
framework creates ActionMapping object from <ActionMapping> configuration element of
struts-config.xml file
<action-mappings>
<action path="/submit"
type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/error.jsp"/>
</action>
</action-mappings>

13.What is role of Action Class?


An Action Class performs a role of an adapter between the contents of an incoming HTTP request and
the corresponding business logic that should be executed to process this request.
14.In which method of Action class the business logic is executed ?
In the execute() method of Action class the business logic is executed.
public ActionForward execute(
ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)throws Exception ;

execute() method of Action class:

Perform the processing required to deal with this request

Update the server-side objects (Scope variables) that will be used to create the next page of the
user interface
Return an appropriate ActionForward object

15.What design patterns are used in Struts?


Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the
command design pattern and the action classes use the adapter design pattern. The process()
method of the RequestProcessor uses the template method design pattern. Struts also implement the
following J2EE design patterns.

Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token

6.Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be
configured as follows:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>

17.What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.
18.What are the important tags of struts-config.xml ?
The five important sections are:

19.What are the different kinds of actions in Struts?


The different kinds of actions in Struts are:

ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction

20.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have
a method for each logical action compared than a single execute method. The DispatchAction
dispatches to one of the logical actions represented by the methods. It picks a method to invoke based
on an incoming request parameter. The value of the incoming parameter is the name of the method that
the DispatchAction will invoke.

21.What is the directory structure of Struts application?


The directory structure of Struts application :

22.How to use DispatchAction?


To use the DispatchAction, follow these steps :

Create a class that extends DispatchAction (instead of Action)


In a new class, add a method for every function you need to perform on the service The
method has the same signature as the execute() method of an Action class.
Do not override execute() method Because DispatchAction class itself provides
execute() method.
Add an entry to struts-config.xml

23.What is the use of ForwardAction?


The ForwardAction class is useful when youre trying to integrate Struts into an existing
application that uses Servlets to perform business logic functions. You can use this class to take
advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets.
Use ForwardAction to forward a request to another resource in your application, such as a Servlet
that already does business logic processing or even another JSP page. By using this predefined action,
you dont have to write your own Action class. You just have to set up the struts-config file
properly to use ForwardAction.
24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses
Servlets. Use the IncludeAction class to include another resource in the response to the request being
processed.
25.What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included

by another action or jsp. Use ForwardAction to forward a request to another resource in your
application, such as a Servlet that already does business logic processing or even another JSP page.
26.What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the
resource bundle to get the key and then gets the method whose name is associated with the key into the
Resource Bundle.
27.What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front
end, but by the Locale independent key into the resource bundle. Since the key is always the same, the
LookupDispatchAction shields your application from the side effects of I18N.
28.What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets
called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method
name directly.
29.What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource
in a different module. SwitchAction is useful only if you have multiple modules in your Struts
application. The SwitchAction class can be used as is, without extending.
30.What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> elements <forward> takes
precendence.
31.What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of
properties (configured in configuration file), without requiring the developer to create a Java class for
each type of form bean.
32.What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward.
You need to make changes in two places:

In struts-config.xml: change your <form-bean> to be an


org.apache.struts.action.DynaActionForm instead of some subclass of
ActionForm

<form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >


<form-property name="userName" type="java.lang.String"/>
<form-property name="password" type="java.lang.String" />
</form-bean>

In your Action subclass that uses your form bean:


import org.apache.struts.action.DynaActionForm
downcast the ActionForm parameter in execute() to a DynaActionForm
access the form fields with get(field) rather than getField()

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........

33.How to display validation errors on jsp page?


<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request
attribute.
34.What are the various Struts tag libraries?
The various Struts tag libraries are:

HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags

35.What is the use of <logic:iterate>?


<logic:iterate> repeats the nested body content of this tag over a specified collection.
<table border=1>
<logic:iterate id="customer" name="customers">

<tr>
<td><bean:write name="customer" property="firstName"/></td>
<td><bean:write name="customer" property="lastName"/></td>
<td><bean:write name="customer" property="address"/></td>
</tr>
</logic:iterate>
</table>

36.What are differences between <bean:message> and <bean:write>


<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to
include parameters that can be substituted for defined placeholders in the retrieved string.
<bean:message key="prompt.customer.firstname"/>

<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>

37.How the exceptions are handled in struts?


Exceptions in Struts are handled in two ways:

Programmatic exception handling : Explicit try/catch blocks in any code that can throw
exception. It works well when custom value (i.e., of variable) needed when error occurs.

Declarative exception handling :You can either define <global-exceptions> handling


tags in your struts-config.xml or define the exception handling tags within
<action></action> tag. It works well when custom page needed when error occurs. This
approach applies only to exceptions thrown by Actions.

<global-exceptions>
<exception key="some.key"
type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>

or
<exception key="some.key"
type="package.SomeException"
path="/WEB-INF/somepage.jsp"/>

38.What is difference between ActionForm and DynaActionForm?

An ActionForm represents an HTML form that the user interacts with over one or more
pages. You will provide properties to hold the state of the form with getters and setters to access
them. Whereas, using DynaActionForm there is no need of providing properties to hold the
state. Instead these properties and their type are declared in the struts-config.xml
The DynaActionForm bloats up the Struts config file with the xml based definition. This
gets annoying as the Struts Config file grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no
compile time checking for the form fields. Detecting them at runtime is painful and makes you
go through redeployment.

ActionForm can be cleanly organized in packages as against the flat organization in the Struts
Config file.
ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e.
isolate and encapsulate the HTTP request parameters from direct use in Actions. With
DynaActionForm, the property access is no different than using request.getParameter( .. ).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection)
machinery that can be avoided.

39.How can we make message resources definitions file available to the Struts framework
environment?
We can make message resources definitions file (properties file) available to Struts framework
environment by adding this file to struts-config.xml.
<message-resources parameter="com.login.struts.ApplicationResources"/>

40.What is the life cycle of ActionForm?


The lifecycle of ActionForm invoked by the RequestProcessor is as follows:

Retrieve or Create Form Bean associated with Action


"Store" FormBean in appropriate scope (request or session)
Reset the properties of the FormBean
Populate the properties of the FormBean
Validate the properties of the FormBean
Pass FormBean to Action

1.What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.
2.What does ORM consists of ?
An ORM solution consists of the following four pieces:

API for performing basic CRUD operations


API to express queries referring to classes
Facilities to specify metadata
Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?


The ORM levels are:

Pure relational (stored procedure.)


Light objects mapping (JDBC)
Medium object mapping
Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you
to map plain old Java objects to relational database tables using (XML) configuration files. Its purpose
is to relieve the developer from a significant amount of relational data persistence-related programming
tasks.
5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from
this, ORM provides following benefits:

Improved productivity
High-level object-oriented API
Less Java code to write
No SQL to write
Improved performance
Sophisticated caching
Lazy loading
Eager loading
Improved maintainability
A lot less code to write
Improved portability
ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?


Hibernate simplifies:

Saving and retrieving your domain objects


Making database column and table name changes

Centralizing pre save and post retrieve logic


Complex joins for retrieving related items
Schema creation from object model

7.What is the need for Hibernate xml mapping file?


Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.
Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration?


The most common methods of Hibernate configuration are:

Programmatic configuration
XML configuration (hibernate.cfg.xml)

9.What are the Core interfaces are of Hibernate framework?


The five core interfaces are used in just about every Hibernate application. Using these interfaces, you
can store and retrieve persistent objects and control transactions.
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces

10.What are the important tags of hibernate.cfg.xml?


Following are the important tags of hibernate.cfg.xml:

11.What role does the Session interface play in Hibernate?


The Session interface is the primary interface used by Hibernate applications. It is a single-threaded,
short-lived object representing a conversation between the application and the persistent store. It allows
you
to
create
query
objects
to
retrieve
persistent
objects.
Session session = sessionFactory.openSession();
Session interface role:

Wraps a JDBC connection


Factory for Transaction
Holds a mandatory (first-level) cache of persistent objects, used when navigating the object
graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?


The application obtains Session instances from a SessionFactory. There is typically a single
SessionFactory for the whole applicationcreated during application initialization. The SessionFactory
caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also
holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
13.What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :

Load the Hibernate configuration file and create configuration object. It will automatically load

all hbm mapping files


Create session factory from configuration object
Get one session from this session factory
Create HQL Query
Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?


Hibernate offers a query language that embodies a very powerful and flexible mechanism to query,
store, update, and retrieve objects from a database. This language, the Hibernate query Language
(HQL), is an object-oriented extension to SQL.
15.How do you map Java Objects with Database tables?

First we need to write Java domain objects (beans with setter and getter).
Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

16.Whats the difference between load() and get()?


load() vs. get() :load()

get()

Only use the load() method if you are sure that the
object exists.

If you are not sure that the object exists, then


use one of the get() methods.

load() method will throw an exception if the


unique id is not found in the database.

get() method will return null if the unique


id is not found in the database.

load() just returns a proxy by default and database


wont be hit until the proxy is first invoked.

get() will hit the database immediately.

17.What is the difference between and merge and update ?


Use update() if you are sure that the session does not contain an already persistent instance with the
same identifier, and merge() if you want to merge your modifications at any time without
consideration of the state of the session.
18.How do you define sequence generated primary key in hibernate?
Using
Example:-

<generator>

tag.

<id column="USER_ID" name="id" type="java.lang.Long">


<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>

19.Define cascade and inverse option in one-many mapping?


cascade
enable
operations
to
cascade="all|none|save-update|delete|all-delete-orphan"

cascade

to

child

entities.

inverse - mark this collection as the "inverse" end of a bidirectional association.


inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a
parent who has a collection of children, should you ask the parent for its list of children, or ask the
children who the parents are?
20.What do you mean by Named SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
<return alias="emp" class="com.test.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :


List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

21.How do you invoke Stored Procedures?


<sql-query name="selectAllEmployees_SP" callable="true">
<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>
<return-property name="name" column="EMP_NAME"/>
<return-property name="address" column="EMP_ADDRESS"/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>

22.Explain Criteria API


Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very

convenient approach for functionality like "search" screens where there is a variable number of
conditions
to
be
placed
upon
the
result
set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which
provides different methods for querying/retrieving data from the database. It also converts checked
HibernateExceptions into unchecked DataAccessExceptions.
24.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :

HibernateTemplate, a Spring Template class simplifies interactions with Hibernate


Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.

25.How do you switch between relational databases without code changes?


Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql
queries based on the dialect defined.
26.If you want to see the Hibernate generated SQL statements on console, what should we do?
In
Hibernate
configuration
file
<property name="show_sql">true</property>

set

as

follows:

27.What are derived properties?


The properties that are not mapped to a column, but calculated at runtime by evaluation of an
expression are called derived properties. The expression can be defined using the formula attribute of
the element.
28.What is component mapping in Hibernate?

A component is an object saved as a value, not as a reference


A component can be saved directly without needing to declare interfaces or identifier properties
Required to define an empty constructor
Shared references not supported

Example:

29.What is the difference between sorted and ordered collection in hibernate?


sorted collection vs. order collection :sorted collection

order collection

A sorted collection is sorting a collection by


utilizing the sorting features provided by the Java
collections framework. The sorting occurs in the
memory of JVM which running Hibernate, after
the data being read from database using java
comparator.

Order collection is sorting a collection by


specifying the order-by clause for sorting this
collection when retrieval.

If your collection is not large, it will be more


efficient way to sort it.

If your collection is very large, it will be more


efficient way to sort it .

30.What is the advantage of Hibernate over jdbc?


Hibernate Vs. JDBC :JDBC
Hibernate
With JDBC, developer has to write code to map an object model's data representation to a relational
data model and its corresponding database schema.
Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate

itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to
be taken care of by the developer manually with lines of code.
Hibernate provides transparent persistence and developer does not need to write code explicitly to map
database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient
way to access database, i.e. to select effective query from a number of queries to perform same task.
Hibernate provides a powerful query language Hibernate Query Language (independent from type of
database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic
queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a
database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in
large amount. The code written to map table data to application objects and vice versa is actually to
map table fields to object properties. As table changed or database changed then its essential to change
object structure as well as to change code written to map table-to-object/object-to-table.
Hibernate provides this mapping itself. The actual mapping between tables and application objects is
done in XML files. If there is change in Database or in any table then the only need to change XML file
properties.
With JDBC, it is developers responsibility to handle JDBC result set and convert it to Java objects
through code to use this persistent data in application. So with JDBC, mapping between Java objects
and database tables is done manually.
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to
application in form of Java objects. It relieves programmer from manual handling of persistent data,
hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding.
Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are
moved to this cache as a result of query. It improves performance if client application reads same data
many times for same write. Automatic Transparent Persistence allows the developer to concentrate
more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the
developer.
Hibernate enables developer to define version type field to application, due to this defined field
Hibernate updates version field of database table every time relational tuple is updated in form of Java
class object to that table. So if two users retrieve same tuple and then modify it and one user save this
modified tuple to database, version is automatically updated for this tuple by Hibernate. When other
user tries to save updated tuple to database then it does not allow saving it because this user does not
have updated data.
31.What are the Collection types in Hibernate ?

Bag
Set
List
Array
Map

32.What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:

An implicit association join


An ordinary join in the FROM clause
A fetch join in the FROM clause.
A theta-style join in the WHERE clause.

33.Define cascade and inverse option in one-many mapping?


cascade
enable
operations
to
cascade="all|none|save-update|delete|all-delete-orphan"

cascade

to

child

entities.

inverse - mark this collection as the "inverse" end of a bidirectional association.


inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a
parent who has a collection of children, should you ask the parent for its list of children, or ask the
children who the parents are?
34.What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will
initially return CGLIB proxies which implement the named interface. The actual persistent object will
be loaded when a method of the proxy is invoked.
35.How can Hibernate be configured to access an instance variable directly and not through a setter
method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the
setter method and access the instance variable directly while initializing a newly loaded object.
36.How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not)
mutable. Immutable classes, may not be updated or deleted by the application.
37.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very
convenient approach for functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.

dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at


runtime and contain only those columns whose values have changed

dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at


runtime and contain only the columns whose values are not null.

38.What do you mean by fetching strategy ?


A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application
needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or
over-ridden by a particular HQL or Criteria query.
39.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update
the database when we modify the state of an object inside a transaction.
40.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign
key constraint violations but is still sufficiently predictable to the user. This feature is called
transactional write-behind.
41.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens
to an objectfor example, when an object is loaded, saved, or deleted. Hibernate applications don't
need to implement these callbacks, but they're useful for implementing certain kinds of generic
functionality.
42.What are the types of Hibernate instance states ?
Three types of instance states:

Transient -The instance is not associated with any persistence context


Persistent -The instance is associated with a persistence context
Detached -The instance was associated with a persistence context which has been closed
currently not associated

43.What are the differences between EJB 3.0 & Hibernate


Hibernate Vs EJB 3.0 :Hibernate
EJB 3.0
SessionCache or collection of loaded objects relating to a single unit of work

Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a


persistence unit
XDoclet Annotations used to support Attribute Oriented Programming
Java 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the database
Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc
Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API
Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces
Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two
unidirectional relationships
Entity Relationships are bidirectional or unidirectional
44.What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:

Table per class hierarchy


Table per subclass
Table per concrete class

1. What is JSF (or JavaServer Faces)?


A server side user interface component framework for Java technology-based web
applications.JavaServer Faces (JSF) is an industry standard and a framework for building componentbased user interfaces for web applications.
JSF contains an API for representing UI components and managing their state; handling events, serverside validation, and data conversion; defining page navigation; supporting internationalization and
accessibility; and providing extensibility for all these features.
2.What are the advantages of JSF?
The major benefits of JavaServer Faces technology are:

JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces
technology, user interfaces can be created easily with its built-in UI component library, which
handles most of the complexities of user interface management.
Offers a clean separation between behavior and presentation.
Provides a rich architecture for managing component state, processing component data,
validating user input, and handling events.
Robust event handling mechanism.
Events easily tied to server-side code.
Render kit support for different clients
Component-level control over statefulness
Highly 'pluggable' - components, view handler, etc
JSF also supports internationalization and accessibility
Offers multiple, standardized vendor implementations

3.What are differences between struts and JSF?


In a nutshell, Faces has the following advantages over Struts:

Eliminated the need for a Form Bean

Eliminated the need for a DTO Class

Allows the use of the same POJO on all Tiers because of the Backing Bean

The primary advantages of Struts as compared to JavaServer Faces technology are as follows:
Because Struts is a web application framework, it has a more sophisticated controller
architecture than does JavaServer Faces technology. It is more sophisticated partly because the
application developer can access the controller by creating an Action object that can integrate
with the controller, whereas JavaServer Faces technology does not allow access to the
controller. In addition, the Struts controller can do things like access control on each Action
based on user roles. This functionality is not provided by JavaServer Faces technology.

Struts includes a powerful layout management framework, called Tiles, which allows you to
create templates that you can reuse across multiple pages, thus enabling you to establish an
overall look-and-feel for an application.

The Struts validation framework includes a larger set of standard validators, which
automatically generate both server-side and client-side validation code based on a set of rules in

a configuration file. You can also create custom validators and easily include them in your
application by adding definitions of them in your configuration file.

The greatest advantage that JavaServer Faces technology has over Struts is its flexible,
extensible UI component model, which includes:
A standard component API for specifying the state and behavior of a wide range of components,
including simple components, such as input fields, and more complex components, such as
scrollable data tables. Developers can also create their own components based on these APIs,
and many third parties have already done so and have made their component libraries publicly
available.

A separate rendering model that defines how to render the components in various ways. For
example, a component used for selecting an item from a list can be rendered as a menu or a set
of radio buttons.

An event and listener model that defines how to handle events generated by activating a
component, such as what to do when a user clicks a button.

Conversion and validation models for converting and validating component data.

4. What are the available implementations of JavaServer Faces?


The main implementations of JavaServer Faces are:

Reference Implementation (RI) by Sun Microsystems.


Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
ADF Faces is Oracles implementation for the JSF standard.

6.What typical JSF application consists of?


A typical JSF application consists of the following parts:

JavaBeans components for managing application state and behavior.


Event-driven development (via listeners as in traditional GUI development).
Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

7.What Is a JavaServer Faces Application?


JavaServer Faces applications are just like any other Java web application. They run in a servlet
container, and they typically contain the following:

JavaBeans components containing application-specific functionality and data.


Event listeners.
Pages, such as JSP pages.
Server-side helper classes, such as database access beans.
In addition to these items, a JavaServer Faces application also has:
A custom tag library for rendering UI components on a page.
A custom tag library for representing event handlers, validators, and other actions.
UI components represented as stateful objects on the server.
Backing beans, which define properties and functions for UI components.
Validators, converters, event listeners, and event handlers.

An application configuration resource file for configuring application resources.

8.What is Managed Bean?


JavaBean objects managed by a JSF implementation are called managed beans. A managed bean
describes how a bean is created and managed. It has nothing to do with the bean's functionalities.
9.What is Backing Bean?
Backing beans are JavaBeans components associated with UI components used in a page. Backingbean management separates the definition of UI component objects from objects that perform
application-specific processing and hold data.
The backing bean defines properties and handling-logics associated with the UI components used on
the page. Each backing-bean property is bound to either a component instance or its value. A backing
bean also defines a set of methods that perform functions for the component, such as validating the
component's data, handling events that the component fires and performing processing associated with
navigation when the component activates.
10.What are the differences between a Backing Bean and Managed Bean?
Backing Beans are merely a convention, a subtype of JSF Managed Beans which have a very particular
purpose. There is nothing special in a Backing Bean that makes it different from any other managed
bean apart from its usage.
What makes a Backing Bean is the relationship it has with a JSF page; it acts as a place to put
component references and Event code.
Backing Beans

Managed Beans
A managed bean is a backing bean that has been registered with JSF (in
A backing bean is any bean
faces-config.xml) and it automatically created (and optionally initialized)
that is referenced by a form.
by JSF when it is needed.
The advantage of managed beans is that the JSF framework will
automatically create these beans, optionally initialize them with
parameters you specify in faces-config.xml,
Backing Beans should be
The managed beans that are created by JSF can be stored within the
defined only in the request
request, session, or application scopes
scope
Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a
particular page and hold all of the page specific event handling code. In a real-world scenario, several
pages may need to share the same backing bean behind the scenes. A backing bean not only contains
view data, but also behavior related to that data.
11.What is view object?

A view object is a model object used specifically in the presentation tier. It contains the data that must
display in the view layer and the logic to validate user input, handle events, and interact with the
business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and
view object are interchangeable terms.
12.What is domain object model?
Domain object model is about the business object and should belong in the business-logic tier. It
contains the business data and business logic associated with the specific business object.
13.What is the difference between the domain object model and a view object?
In a simple Web application, a domain object model can be used across all tiers, however, in a more
complex Web application, a separate view object model needs to be used. Domain object model is
about the business object and should belong in the business-logic tier. It contains the business data and
business logic associated with the specific business object. A view object contains presentation-specific
data and behavior. It contains data and logic specific to the presentation tier.
14.What do you mean by Bean Scope?
Bean Scope typically holds beans and other objects that need to be available in the different
components of a web application.
15. What are the different kinds of Bean Scopes in JSF?
JSF supports three Bean Scopes. viz.,

Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted
and ends when the response is sent back to the client.
Session Scope: The session scope persists from the time that a session is established until
session termination.
Application Scope: The application scope persists for the entire duration of the web
application. This scope is shared among all the requests and sessions.

16.What is the difference between JSP-EL and JSF-EL?


JSP-EL
In JSP-EL the value expressions are delimited
by ${}.
The ${} delimiter denotes the immediate
evaluation of the expressions, at the time that
the application server processes the page.

JSF-EL
In JSf-EL the value expressions are delimited by #{}.
The #{} delimiter denotes deferred evaluation. With
deferred evaluation ,the application server retains the
expression and evaluates it whenever a value is needed.

17.What are The main tags in JSF?


JSF application typically uses JSP pages to represent views. JSF provides useful special tags to enhance
these views. Each tag gives rise to an associated component. JSF (Sun Implementation) provides 43
tags in two standard JSF tag libraries:

JSF Core Tags Library.


JSF Html Tags Library.

18.How do you declare the managed beans in the faces-config.xml file?


The bean instance is configured in the faces-config.xml file:
<managed-bean>
<managed-bean-name>login</managed-bean-name>
<managed-bean-class>com.developersBookJsf.loginBean</managed-beanclass>

<managed-bean-scope>request</managed-bean-scope>
</managed-bean>

This means: Construct an object of the class com.developersBookJsf.loginBean, give it the


name login, and keep it alive for the duration of the request.
19.How to declare the Message Bundle in JSF?
We
can
declare
the
message
bundle
in
two
(Lets assume com.developersBookJsf.messages is the properties file)

ways:

1.The simplest way is to include the following elements in faces-config.xml file:


<application>
<resource-bundle>
<base-name>com.developersBookJsf.messages</base-name>
<var>message</var>
</resource-bundle>
</application>

2.Alternatively, you can add the f:loadBundle element to each JSF page that needs access to the
bundle:
<f:loadBundle baseName = com.developersBookJsf.messages var=message/>

20.How to declare the page navigation (navigation rules) in faces-config.xml file ?


Navigation rules tells JSF implementation which page to send back to the browser after a form has
been submitted. We can declare the page navigation as follows:
<naviagation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</naviagation-rule>

This declaration states that the login action navigates to /welcome.jsp, if it occurred inside
/index.jsp.

21.What if no navigation rule matches a given action?


If no navigation rule matches a given action, then the current page is redisplayed.
22. What are the JSF life-cycle phases?
The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):
1.Restore view
2.Apply request values; process events
3.Process validations; process events
4.Update model values; process events
5.Invoke application; process events
6.Render response
23.Explain briefly the life-cycle phases of JSF?
1. Restore View : A request comes through the FacesServlet controller. The controller examines
the request and extracts the view ID, which is determined by the name of the JSP page.
2. Apply request values: The purpose of the apply request values phase is for each component
to retrieve its current state. The components must first be retrieved or created from the
FacesContext object, followed by their values.
3. Process validations:In this phase, each component will have its values validated against the
application's validation rules.
4. Update model values:In this phase JSF updates the actual values of the server-side
model ,by updating the properties of your backing beans.
5. Invoke application: In this phase the JSF controller invokes the application to handle Form
submissions.
6. Render response: In this phase JSF displays the view with all of its components in their
current state.

Phase 1 : Restore view


In the RestoreView phase, JSF classes build the tree of UI components for the incoming request.

When a request for a JavaServer Faces page is made, such as when a link or a button is clicked,
the JavaServer Faces implementation begins the restore view phase.
This is one of the trickiest parts of JSF: The JSF framework controller uses the view ID
(typically JSP name) to look up the components for the current view. If the view isnt available,
the JSF controller creates a new one. If the view already exists, the JSF controller uses it. The
view contains all the GUI components and there is a great deal of state management by JSF to
track the status of the view typically using HTML hidden fields.
If the request for the page is an initial request, the JavaServer Faces implementation creates an
empty view during this phase. Lifecycle only executes the restore view and render response
phases because there is no user input or actions to process.
If the request for the page is a postback, a view corresponding to this page already exists.

During this phase, the JavaServer Faces implementation restores the view by using the state
information saved on the client or the server. Lifecycle continues to execute the remaining phases.

Fortunately this is the phase that requires the least intervention by application code.

Phase 2 : ApplyRequest values


During ApplyRequest values, the request parameters are read and their values are used to set the
values of the corresponding UI components. This process is called decoding.

If the conversion of the value fails, an error message associated with the component is generated
and queued on FacesContext. This message will be displayed during the render response
phase, along with any validation errors resulting from the process validations phase.
If some components on the page have their immediate event handling property is set to true,
then the validation, conversion, and events associated with these components takes place in this
phase instead of the Process Validations phase. For example, you could have a Cancel button
that ignores all values on a form.

Phase 3 : Process validations


The Apply Validations phase triggers calls to all registered validators.

The components validate the new values coming from the request against the application's
validation rules.
Any input can be scanned by any number of validators.
These Validators can be pre-defined or defined by the developer.
Any validation errors will abort the requesthandling process and skip to rendering the response
with validation and conversion error messages.

Phase 4 : Update Model Values


The Update Model phase brings a transfer of state from the UI component tree to any and all backing
beans, according to the value expressions defined for the components themselves.

It is in this phase that converters are invoked to parse string representations of various values to
their proper primitive or object types. If the data cannot be converted to the types specified by
the bean properties, the life cycle advances directly to the render response phase so that the page
is re-rendered with errors displayed.
Note: The difference between this phase and Apply Request Values - that phase moves values
from clientside HTML form controls to serverside UI components; while in this phase the
information moves from the UI components to the backing beans.

Phase 5 : Invoke Application


The Invoke Application phase handles any application-level events. Typically this takes the form of a
call to process the action event generated by the submit button that the user clicked.

Application level events handled


Application methods invoked
Navigation outcome calculated

Phase 6 : Render Response


Finally, Render Response brings several inverse behaviors together in one process:

Values are transferred back to the UI components from the bean. Including any modifications
that may have been made by the bean itself or by the controller.
The UI components save their state not just their values, but other attributes having to do with
the presentation itself. This can happen serverside, but by default state is written into the
HTML as hidden input fields and thus returns to the JSF implementation with the next request.
If the request is a postback and errors were encountered during the apply request values phase,
process validations phase, or update model values phase, the original page is rendered during
this phase. If the pages contain message or messages tags, any queued error messages are
displayed on the page.

24.What does it mean by render kit in JSF?


A render kit defines how component classes map to component tags that are appropriate for a particular
client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an
HTML client.

25. Is it possible to have more than one Faces Configuration file?


We can have any number of config files. Just need to register in web.xml.
Assume that we want to use faces-config(1,2,and 3),to register more than one faces configuration file in
JSF,just declare in the web.xml file
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/faces-config1.xml,
/WEB-INF/faces-config2.xml,
/WEB-INF/faces-config3.xml
</param-value>
</context-param>

1. What is IOC (or Dependency Injection)?


The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you
do not create your objects but describe how they should be created. You don't directly connect your
components and services together in code but describe which services are needed by which components
in a configuration file. A container (in the case of the Spring framework, the IOC container) is then
responsible
for
hooking
it
all
up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that
coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an
inversion of responsibility with regard to how an object obtains references to collaborating objects.
2.What are the different types of IOC (dependency injection) ?
There are three types of dependency injection:

Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as
constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex:
setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.

Note: Spring supports only Constructor and Setter Injection


3.What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:

Minimizes the amount of code in your application. With IOC containers you do not care about
how services are created and how you get references to the ones you need. You can also easily
add additional services by adding a new constructor or a setter method with little or no extra
configuration.

Make your application more testable by not requiring any singletons or JNDI lookup
mechanisms in your unit test cases. IOC containers make unit testing and switching
implementations very easy by manually allowing you to inject your own objects into the object
under test.

Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory
design pattern is more intrusive because components or services need to be requested explicitly
whereas in IOC the dependency is injected into requesting piece of code. Also some containers
promote the design to interfaces not to implementations design concept by encouraging
managed objects to implement a well-defined service interface of your own.

IOC containers support eager instantiation and lazy loading of services. Containers also provide
support for instantiation of managed objects, cyclical dependencies, life cycles management,
and dependency resolution between managed objects etc.

4. What is Spring ?
Spring is an open source framework created to address the complexity of enterprise application
development. One of the chief advantages of the Spring framework is its layered architecture, which

allows you to be selective about which of its components you use while also providing a cohesive
framework for J2EE application development.
5.What are the advantages of Spring framework?
The advantages of Spring are as follows:

Spring has layered architecture. Use what you need and leave you don't need now.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO
programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.

6.What are features of Spring ?

Lightweight:
spring is lightweight when it comes to size and transparency. The basic version of spring
framework is around 1MB. And the processing overhead is also very negligible.

Inversion of control (IOC):


Loose coupling is achieved in spring using the technique Inversion of Control. The objects give
their dependencies instead of creating or looking for dependent objects.

Aspect oriented (AOP):


Spring supports Aspect oriented programming and enables cohesive development by separating
application business logic from system services.

Container:
Spring contains and manages the life cycle and configuration of application objects.

MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This
framework is highly configurable via strategy interfaces, and accommodates multiple view
technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used
instead of Spring MVC Framework.

Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This
allowing the developer to add the pluggable transaction managers, and making it easy to
demarcate transactions without dealing with low-level issues. Spring's transaction support is not
tied to J2EE environments and it can be also used in container less environments.

JDBC Exception Handling:


The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which
simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring
provides best Integration services with Hibernate, JDO and iBATIS

7.How many modules are there in Spring? What are they?


(Roll over to view the Image )

Spring comprises of seven modules. They are..

The core container:


The core container provides the essential functionality of the Spring framework. A primary
component of the core container is the BeanFactory, an implementation of the Factory
pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an
application's configuration and dependency specification from the actual application code.

Spring context:
The Spring context is a configuration file that provides context information to the Spring
framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail,
internalization, validation, and scheduling functionality.

Spring AOP:
The Spring AOP module integrates aspect-oriented programming functionality directly into the
Spring framework, through its configuration management feature. As a result you can easily
AOP-enable any object managed by the Spring framework. The Spring AOP module provides
transaction management services for objects in any Spring-based application. With Spring AOP
you can incorporate declarative transaction management into your applications without relying
on EJB components.

Spring DAO:
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing
the exception handling and error messages thrown by different database vendors. The exception
hierarchy simplifies error handling and greatly reduces the amount of exception code you need
to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions
comply to its generic DAO exception hierarchy.

Spring ORM:
The Spring framework plugs into several ORM frameworks to provide its Object Relational

tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic
transaction and DAO exception hierarchies.

Spring Web module:


The Web context module builds on top of the application context module, providing contexts for
Web-based applications. As a result, the Spring framework supports integration with Jakarta
Struts. The Web module also eases the tasks of handling multi-part requests and binding request
parameters to domain objects.

Spring MVC framework:


The Model-View-Controller (MVC) framework is a full-featured MVC implementation for
building Web applications. The MVC framework is highly configurable via strategy interfaces
and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.

8.What are the types of Dependency Injection Spring supports?>

Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a noargument constructor or no-argument static factory method to instantiate your bean.
Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each
representing a collaborator.

9.What is Bean Factory ?


A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean
Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.

BeanFactory is able to create associations between collaborating objects as they are instantiated.
This removes the burden of configuration from bean itself and the beans client.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and
destruction methods.

10.What is Application Context?


A bean factory is fine to simple applications, but to take advantage of the full power of the Spring
framework, you may want to move up to Springs more advanced container, the application context. On
the surface, an application context is same as a bean factory. Both load bean definitions, wire beans
together, and dispense beans upon request. But it also provides:

A means for resolving text messages, including support for internationalization.


A generic way to load file resources.
Events to beans that are registered as listeners.

11.What is the difference between Bean Factory and Application Context ?


On the surface, an application context is same as a bean factory. But application context offers much
more..

Application contexts provide a means for resolving text messages, including support for i18n of

those messages.

Application contexts provide a generic way to load file resources, such as images.

Application contexts can publish events to beans that are registered as listeners.

Certain operations on the container or beans in the container, which have to be handled in a
programmatic fashion with a bean factory, can be handled declaratively in an application
context.

ResourceLoader support: Springs Resource interface us a flexible generic abstraction for


handling low-level resources. An application context itself is a ResourceLoader, Hence provides
an application with access to deployment-specific Resource instances.

MessageSource support: The application context implements MessageSource, an interface used


to obtain localized messages, with the actual implementation being pluggable

12.What are the common implementations of the Application Context ?


The three commonly used implementation of 'Application Context' are

ClassPathXmlApplicationContext : It Loads context definition from an XML file located in


the classpath, treating context definitions as classpath resources. The application context is
loaded from the application's classpath by using the code .
ApplicationContext context = new
ClassPathXmlApplicationContext("bean.xml");
FileSystemXmlApplicationContext : It loads context definition from an XML file in the
filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new
FileSystemXmlApplicationContext("bean.xml");
XmlWebApplicationContext : It loads context definition from an XML file contained within a
web application.

13.How is a typical spring implementation look like ?


For a typical Spring Application we need the following files:

An interface that defines the functions.

An Implementation that contains properties, its setter and getter methods, functions etc.,

Spring AOP (Aspect Oriented Programming)

A XML file called Spring configuration file.

Client program that uses the function.

14. What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:

The spring container finds the beans definition from the XML file and instantiates the bean.

Using the dependency injection, spring populates all of the properties as specified in the bean
definition

If the bean implements the BeanNameAware interface, the factory calls setBeanName()
passing the beans ID.

If the bean implements the BeanFactoryAware


setBeanFactory(), passing an instance of itself.

If there are any BeanPostProcessors associated with the


ProcessBeforeInitialization() methods will be called.

If an init-method is specified for the bean, it will be called.

Finally, if there are any BeanPostProcessors associated with


postProcessAfterInitialization() methods will be called.

interface,

the

factory

calls

bean,

their

post-

the

bean,

their

15.What do you mean by Bean wiring ?


The act of creating associations between application components (beans) within the Spring container is
reffered to as Bean wiring.
16.What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it
is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting
the contents of the BeanFactory. The autowiring functionality has five modes.

no

byName

byType

constructor

autodirect

17.What is DelegatingVariableResolver?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard
Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This
variable resolver is called as DelegatingVariableResolver
18.How to integrate Java Server Faces (JSF) with Spring?
JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By
declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to
instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We
can integrate JSF and Spring in two ways:

DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF
and Spring together.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<faces-config>
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
</faces-config>

The DelegatingVariableResolver will first delegate value lookups to the default resolver of the
underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext.
This allows one to easily inject dependencies into one's JSF-managed beans.

FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans


in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils
class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a
FacesContext parameter rather than a ServletContext parameter.
ApplicationContext ctx =
FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance())
;

19.What is Java Server Faces (JSF) - Spring integration mechanism?


Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard
JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following
algorithm is performed:

Does a bean with the specified name already exist in some scope (request, session, application)?
If so, return it

Is there a standard JavaServer Faces managed bean definition for this variable name? If so,
invoke it in the usual way, and return the bean that was created.

Is there configuration information for this variable name in the Spring WebApplicationContext
for this application? If so, use it to create and configure an instance, and return that instance to
the caller.

If there is no managed bean or Spring definition for this variable name, return null instead.

BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and
destruction methods.
As a result of this algorithm, you can transparently use either JavaServer Faces or Spring
facilities to create beans on demand.

20.What is Significance of JSF- Spring integration ?


Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to
create beans on demand, such as a bean that encapsulates the business logic to be performed when a
submit button is pressed.
21.How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:

Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set
their dependencies in a Spring context file.

Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a
getWebApplicationContext() method.

22.What are ORMs Spring supports ?


Spring supports the following ORMs :

Hibernate
iBatis
JPA (Java Persistence API)
TopLink
JDO (Java Data Objects)
OJB

23.What are the ways to access Hibernate using Spring ?


There are two approaches to Springs Hibernate integration:

Inversion of Control with a HibernateTemplate and Callback


Extending HibernateDaoSupport and Applying an AOP Interceptor

24.How to integrate Spring and Hibernate using HibernateDaoSupport?


Spring and Hibernate can integrate using Springs SessionFactory called LocalSessionFactory. The
integration process is of 3 steps.

Configure the Hibernate SessionFactory

Extend your DAO Implementation from HibernateDaoSupport


Wire in Transaction Support with AOP

25.What are Bean scopes in Spring Framework ?


The Spring Framework supports exactly five scopes (of which three are available only if you are using
a web-aware ApplicationContext). The scopes supported are listed below:
Scope
singleton

Description
Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and
every HTTP request will have its own instance of a bean created off the back of a single
bean definition. Only valid in the context of a web-aware Spring
ApplicationContext.

session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.

global
session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only
valid when used in a portlet context. Only valid in the context of a web-aware Spring
ApplicationContext.

26.What is AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to
modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility,
such as logging and transaction management. The core construct of AOP is the aspect, which
encapsulates behaviors affecting multiple classes into reusable modules.
27.How the AOP used in Spring?
AOP is used in the Spring Framework:To provide declarative enterprise services, especially as a
replacement for EJB declarative services. The most important such service is declarative transaction
management, which builds on the Spring Framework's transaction abstraction. To allow users to
implement custom aspects, complementing their use of OOP with AOP.
28.What do you mean by Aspect ?
A modularization of a concern that cuts across multiple objects. Transaction management is a good
example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using
regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation
(@AspectJ style).

29.What do you mean by JointPoint?


A point during the execution of a program, such as the execution of a method or the handling of an
exception. In Spring AOP, a join point always represents a method execution.
30.What do you mean by Advice?
Action taken by an aspect at a particular join point. Different types of advice include "around," "before"
and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor,
maintaining a chain of interceptors "around" the join point.
31.What are the types of Advice?
Types of advice:

Before advice: Advice that executes before a join point, but which does not have the ability to
prevent execution flow proceeding to the join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point completes normally: for
example, if a method returns without throwing an exception.

After throwing advice: Advice to be executed if a method exits by throwing an exception.

After (finally) advice: Advice to be executed regardless of the means by which a join point exits
(normal or exceptional return).

Around advice: Advice that surrounds a join point such as a method invocation. This is the most
powerful kind of advice. Around advice can perform custom behavior before and after the
method invocation. It is also responsible for choosing whether to proceed to the join point or to
shortcut the advised method execution by returning its own return value or throwing an
exception

32.What are the types of the transaction management Spring supports ?


Spring Framework supports:

Programmatic transaction management.


Declarative transaction management.

33.What are the benefits of the Spring Framework transaction management ?


The Spring Framework provides a consistent abstraction for transaction management that delivers the
following benefits:

Provides a consistent programming model across different transaction APIs such as JTA, JDBC,
Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of complex
transaction APIs such as JTA.
Integrates very well with Spring's various data access abstractions.

34. Why most users of the Spring Framework choose declarative transaction management ?

Most users of the Spring Framework choose declarative transaction management because it is the
option with the least impact on application code, and hence is most consistent with the ideals of a noninvasive lightweight container.
35.Explain the similarities and differences between EJB CMT and the Spring Framework's declarative
transaction management ?
The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to
individual
method
level.
It
is
possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are:

Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction
management works in any environment. It can work with JDBC, JDO, Hibernate or other
transactions under the covers, with configuration changes only.

The Spring Framework enables declarative transaction management to be applied to any class,
not merely special classes such as EJBs.

The Spring Framework offers declarative rollback rules: this is a feature with no EJB
equivalent. Both programmatic and declarative support for rollback rules is provided.

The Spring Framework gives you an opportunity to customize transactional behavior, using
AOP. With EJB CMT, you have no way to influence the container's transaction management
other than setRollbackOnly().

The Spring Framework does not support propagation of transaction contexts across remote
calls, as do high-end application servers.

37.When to use programmatic and declarative transaction management ?


Programmatic transaction management is usually a good idea only if you have a small number of
transactional
operations.
On the other hand, if your application has numerous transactional operations, declarative transaction
management is usually worthwhile. It keeps transaction management out of business logic, and is not
difficult to configure.
38.Explain about the Spring DAO support ?
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access
technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the
persistence technologies fairly easily and it also allows one to code without worrying about catching
exceptions that are specific to each technology.
39.What are the exceptions thrown by the Spring DAO classes ?
Spring
DAO
classes
throw
exceptions
which
are
subclasses
of
DataAccessException(org.springframework.dao.DataAccessException).Spring
provides a convenient translation from technology-specific exceptions like SQLException to its own
exception class hierarchy with the DataAccessException as the root exception. These exceptions
wrap the original exception.

40.What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate
between
SQLExceptions
and
Spring's
own
data-access-strategy-agnostic
org.springframework.dao.DataAccessException.
41.What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC.JdbcTemplate provides
many convenience methods for doing things such as converting database data into primitives or
objects, executing prepared and callable statements, and providing custom database error handling.
JdbcTemplate template = new JdbcTemplate(myDataSource);

42.What is PreparedStatementCreator ?
PreparedStatementCreator:

Is one of the most common used interfaces for writing data to database.
Has one method createPreparedStatement(Connection)
Responsible for creating a PreparedStatement.
Does not need to handle SQLExceptions.

43.What is SQLProvider ?
SQLProvider:

Has one method getSql()


Typically implemented by PreparedStatementCreator implementers.
Useful for debugging.

44.What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.

Has one method processRow(ResultSet)


Called for each row in ResultSet.
Typically stateful.

45.What are the differences between EJB and Spring ?


Spring and EJB feature comparison.
Feature
Transaction
management

EJB
Must use a JTA
transaction manager.
Supports transactions
that span remote method
calls.

Spring
Supports multiple transaction environments
through its
PlatformTransactionManager
interface, including JTA, Hibernate, JDO, and
JDBC.

Declarative
transaction
support

Persistence

Declarative
security

Distributed
computing

Can define transactions


declaratively through the
deployment descriptor.
Can define transaction
behavior per method or
per class by using the
wildcard character *.
Cannot declaratively
define rollback behavior
this must be done
programmatically.

Does not natively support distributed


transactionsit must be used with a JTA
transaction manager.

Can define transactions declaratively through


the Spring configuration file or through class
metadata.
Can define which methods to apply transaction
behavior explicitly or by using regular
expressions.
Can declaratively define rollback behavior per
method and per exception type.

Supports programmatic beanProvides a framework for integrating with several


managed persistence and
persistence technologies, including JDBC, Hibernate,
declarative container managed JDO, and iBATIS.
persistence.
Supports declarative
No security implementation out-of-the box.
security through users
Acegi , an open source security framework
and roles. The
built on top of Spring, provides declarative
management and
security through the Spring configuration file
implementation of users
or class metadata.
and roles is container
specific.
Declarative security is
configured in the
deployment descriptor.
Provides container-managed
remote method calls.

Provides proxying for remote calls via RMI, JAXRPC, and web services.

1.What is XML?
Extensible Markup Language (XML) is the universal language for data on the Web
XML is a technology which allows us to create our own markup language.
XML documents are universally accepted as a standard way of representing information in
platform and language independent manner.
XML is universal standard for information interchange.
XML documents can be created in any language and can be used in any language.
2.What is the difference between XML and HTML?
XML is no way clashes with HTML, since they are for two different purposes.
HTML

XML

HTML is for displaying purpose.

whereas XML is for data representation.

HTML is used to mark up text so it can be


displayed to users.

XML is used to mark up data so it can be processed


by computers.

HTML describes both structure (e.g. <p>, <h2>,


XML describes only content, or meaning
<em>) and appearance (e.g. <br>, <font>, <i>)
HTML uses a fixed, unchangeable set of tags

In XML, you make up your own tags

3.What are the benefits of XML?


There are many benefits of using XML on the Web :

Simplicity- Information coded in XML is easy to read and understand, plus it can be processed
easily by computers.
Openness- XML is a W3C standard, endorsed by software industry market leaders.
Extensibility - There is no fixed set of tags. New tags can be created as they are needed.
Self-description- In traditional databases, data records require schemas set up by the database
administrator. XML documents can be stored without such definitions, because they contain
meta data in the form of tags and attributes.
Contains machine-readable context information- Tags, attributes and element structure
provide context information that can be used to interpret the meaning of content, opening up
new possibilities for highly efficient search engines, intelligent data mining, agents, etc.
Separates content from presentation- XML tags describe meaning not presentation. The
motto of HTML is: "I know how it looks", whereas the motto of XML is: "I know what it
means, and you tell me how it should look." The look and feel of an XML document can be
controlled by XSL style sheets, allowing the look of a document to be changed without touching
the content of the document. Multiple views or presentations of the same content are easily
rendered.
Supports multilingual documents and Unicode-This is important for the internationalization
of applications.
Facilitates the comparison and aggregation of data - The tree structure of XML documents
allows documents to be compared and aggregated efficiently element by element.
Can embed multiple data types - XML documents can contain any possible data type - from
multimedia data (image, sound, video) to active components (Java applets, ActiveX).

Can embed existing data - Mapping existing data structures like file systems or relational
databases to XML is simple. XML supports multiple data formats and can cover all existing
data structures and .
Provides a 'one-server view' for distributed data - XML documents can consist of nested
elements that are distributed over multiple remote servers. XML is currently the most
sophisticated format for distributed data - the World Wide Web can be seen as one huge XML
database.

4.What is a well-formed XML document?


If a document is syntactically correct it can be called as well-formed XML documents. A well-formed
document conforms to XML's basic rules of syntax:

Every open tag must be closed.


The open tag must exactly match the closing tag: XML is case-sensitive.
All elements must be embedded within a single root element.
Child tags must be closed before parent tags.
A well-formed document has correct XML tag syntax, but the elements might be invalid for the
specified document type.

5.What is a valid XML document?


If a document is structurally correct then it can be called as valid XML documents. A valid document
conforms to the predefined rules of a specific type of document:

These rules can be written by the author of the XML document or by someone else.
The rules determine the type of data that each part of a document can contain.

Note:Valid XML document is implicitly well-formed, but well-formed may not be valid
6.What is the structure of XML document ?

Figure 1: XML Structure

7.What is a Processing Instruction in XML?


A ProcessingIntruction is the information which we would like to give to application. Through a
ProcessingInstruction an application would get idea about how to process the document. A
ProcessingInstruction can appear anywhere and any no. of times in a document.
8.How does the XML structure is defined?
XML document will have a structure which has to be defined before we can create the documents and
work with them. The structural rules can be defined using many available technologies, but the
following are popular way of doing so

Document Type Definition (DTD)


Schema

9.What is DTD?
A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines
rules for a specific type of document, including:

Names of elements, and how and where they can be used


The order of elements
Proper nesting and containment of elements
Element attributes

To apply a DTD to an XML document, you can:

Include the DTD's element definitions within the XML document itself.
Provide the DTD as a separate file, whose name you reference in the XML document.

10.What is XML Schema?


An XML Schema describes the structure of an XML instance document by defining what each element
must or may contain.XML Schema is expressed in the form of a separate XML file.

XML Schema provides much more control on element and attribute datatypes.
Some datatypes are predefined and new ones can be created.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="test">
<xsd:complexType>

Figure 2: XML Schema

11.What are differences between DTDs and Schema?


Schema

DTD

Schema document is an XML document i.e., the


structure of an XML document is specified by
another XML document.

DTDs follow SGML syntax.

Schema supports variety of dataTypes similar to


programming language.

In DTD everything is treated as text.

In Schema, It is possible to inherit and create


relationship among elements.

This is not possible in DTD without invalidating


existing documents.

In Schema, It is possible to group elements and


attributes so that they can be treated as single
logical unit.

Grouping of elements and attributes is not


possible in DTD.

In Schemas, it is possible to specify an upper limit It is not possible to specify an upper limit of an
for the number of occurrences of an element
element in DTDs
12.What is a Complex Element?
A complex element is an XML element that contains other elements and/or attributes.

There are four kinds of complex elements:

empty elements
elements that contain only other elements
elements that contain only text
elements that contain both other elements and text

13.What is a Simple Element?


A simple element is an XML element that can contain only text.

A simple element cannot have attributes


A simple element cannot contain other elements
A simple element cannot be empty
However, the text can be of many different types, and may have various restrictions applied to it

14.What are namespaces? Why are they important?


A simple element is an XML element that can contain only text.

Namespaces are a simple and straightforward way to distinguish names used in XML
documents, no matter where they come from.
XML namespaces are used for providing uniquely named elements and attributes in an XML
instance
They allow developers to qualify uniquely the element names and relationships and make these
names recognizable, to avoid name collisions on elements that have the same name but are
defined in different vocabularies.
They allow tags from multiple namespaces to be mixed, which is essential if data is coming
from multiple sources.

Example: a bookstore may define the <TITLE> tag to mean the title of a book, contained only within
the <BOOK> element. A directory of people, however, might define <TITLE> to indicate a person's
position, for instance: <TITLE>President</TITLE>. Namespaces help define this distinction clearly.
Note: a) Every namespace has a unique name which is a string. To maintain the uniqueness among
namespaces a IRL is most preferred approach, since URLs are unique.
b) Except for no-namespace Schemas, every XML Schema uses at least two namespaces:
1.the
target
namespace.
2. The XMLSchema namespace (http://w3.org/2001/XMLSchema)
15.What are the ways to use namespaces?
There are two ways to use namespaces:

Declare a default namespace


Associate a prefix with a namespace, then use the prefix in the XML to refer to the namespace

16.What is the relevance of ElementFormDefault attribute in the Schema?


ElementFormDefault indicates whether or not locally declared elements must be qualified by the target
namespace in an instance document. ElementFormDefault attribute in the Schema has the following

relevance:

Qualified: Each and every element of the Schema must be qualified with the namespace in the
instance document.
Unqualified: means only globally declared elements must be qualified with there namespace
and not the local elements.

17.What is XML parser?


An XML parser is a piece of software which can do following:

Check for well-formedness


Validate the document
Allows us to read, create or modify existing XML documents

Note: Parser is piece of software provided by vendors. An XML parser is built in Java runtime from
JDK 1.4 onwards
18.What is DOM?
The Document Object Model (DOM) is a platform and language-independent standard object model
for representing XML and related formats. DOM is standard API which is not specific to any
programming language. DOM represents an XML document as a tree model. The tree model makes the
XML document hierarchal by nature. Each and every construct of the XML document is represented as
a node in the tree.
19.What is SAX?
SAX-Simple API for XML processing. SAX provides a mechanism for reading data from an XML
document. It is a popular alternative to the Document Object Model (DOM).SAX provides an event
based processing approach unlike DOM which is tree based.
20.What are the interfaces of SAX?
The interfaces of SAX are:

DocumentHandler- is used for getting event notification relating to a document.


DTDHandler- is implemented to get the notifications related to declarations in DTD like
entities and notations
EntityResolver- is used for reading external entities.
ErrorHandler- is used for handling error related notifications.

21.What is the difference between SAX parser and DOM parser?


SAX

DOM

A SAX parser takes the occurrences of


A DOM parser creates a tree structure in memory
components of an input document as events (i.e.,
from an input document and then waits for requests
event based processing), and tells the client what
from client.
it reads as it reads through the input document.
No navigation possible (top to bottom only once) Whereas, we can navigate the DOM tree in any

direction, any no. of times.


We cannot modify the document content in SAX We can modify the document content in DOM
A SAX parser serves the client application
always only with pieces of the document at any
given time.

A DOM parser always serves the client application


with the entire document no matter how much is
actually needed by the client.

A SAX parser, however, is much more space


efficient in case of a big input document

A DOM parser is space inefficient when the


document is huge.

Use SAX parser when

Input document is too big for available


memory.
When only a part of the document is to be
read and we create the data structures of
our own.
If you use SAX, you are using much less
memory and performing much less
dynamic memory allocation.

Use DOM when

Your application has to access various parts


of the document and using your own
structure is just as complicated as the DOM
tree.
Your application has to change the tree very
frequently and data has to be stored for a
significant amount of time.

22.What is a CDATA section in XML?


CDATA Sections are used to escape blocks of text containing characters which would otherwise be
recognized as markup. All tags and entity references are ignored by an XML processor that treats them
just like any character data. CDATA blocks have been provided as a convenience measure when you
want to include large blocks of special characters as character data, but you do not want to have to use
entity references all the time.
23.What is XSL?
eXtensible Stylesheet Language(XSL) deals with most displaying the contents of XML
documents.XSL consists of three parts:

XSLT - a language for transforming XML documents


XPath - a language for navigating in XML documents
XSL-FO - a language for formatting XML documents

24.How is XSL different from Cascading Style Sheets? Why is a new Stylesheet language needed?
XSL is compatible with CSS and is designed to handle the new capabilities of XML that CSS can't
handle. XSL is derived from Document Style Semantics and Specification Language (DSSSL), a
complex Stylesheet language with roots in the SGML community. The syntax of XSL is quite different
from CSS, which could be used to display simple XML data but isn't general enough to handle all the
possibilities generated by XML. XSL adds the capability to handle these possibilities. For instance,
CSS cannot add new items or generated text (for instance, to assign a purchase order number) or add a
footer (such as an order confirmation). XSL allows for these capabilities.

25.What is XSLT?
eXtensible Stylesheet Language Transformation (XSLT) deals with transformation of one XML
document into XHTML documents or to other XML documents. XSLT uses XPath for traversing an
XML document and arriving at a particular node.

Figure 3: XSLT
26.What is the role of XSL transformer?
An XSL transformer will transform in the following way:

The source tree is obtained by parsing in a normal XML style


The transformation is now applied to the source with the help of information available in
Stylesheet.

27.What is the structure of XSLT?

Figure 4: XSLT Structure


28.What is XSL template?
Template specifies transformation rules. A Stylesheet document can be made up of at least one
template, which acts as an entry point. Every template uniquely identifies a particular node in the
source tree.
29.What is XPath?
XPath is an expression language used for addressing parts of an XML document. XPath is used to
navigate through elements and attributes in an XML document.
30.What is XSL-FO?
XSL-FO deals with formatting XML data. This can be used for generating output in a particular format
like XML to PDF, XML to DOC, etc.
31.How XSL-FO Works (or) How would you produce PDF output using XSLs?

Figure 5: XSL-FO