Java Interview Questions
Java Interview Questions
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).
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
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
Return type
Can change
Exceptions
Can change
Access
Can change
Invocation
Arguments
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:
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.
Interfaces
28.When should I use abstract classes and when should I use interfaces?
Use Interfaces 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.
Methods
Purpose
Modifiers
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
super
Inheritance
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
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.
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
no
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:
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.
}
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.
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.
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.
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.
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.
PreparedStatement
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.
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
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.
TYPE_SCROLL_SENSITIVE
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,
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..
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
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:
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 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.
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.
8 It allows bookmarks.
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 ?
ServletContext
sendRedirect()
forward()
ServletContext.getRequestDispatcher(String path)
<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.
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
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.
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.
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.
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.
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?
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.
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.
Translation
Compilation
Loading the class
Instantiating the class
jspInit() invocation
_jspService() invocation
jspDestroy() invocation
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.
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" %>
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.
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
<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.
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
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.
Include action
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.
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.
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.
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.
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.
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:
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>
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
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:
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.
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:
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"));
}
...........
HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags
<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>
<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"/>
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.
<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"/>
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"/>
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:
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
Programmatic configuration
XML configuration (hibernate.cfg.xml)
Load the Hibernate configuration file and create configuration object. It will automatically load
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>
get()
Only use the load() method if you are sure that the
object exists.
<generator>
tag.
cascade
to
child
entities.
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 :
set
as
follows:
Example:
order collection
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
cascade
to
child
entities.
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
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.
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.
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.
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
ways:
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/>
This declaration states that the login action navigates to /welcome.jsp, if it occurred inside
/index.jsp.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
An Implementation that contains properties, its setter and getter methods, functions etc.,
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.
interface,
the
factory
calls
bean,
their
post-
the
bean,
their
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.
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.
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.
Hibernate
iBatis
JPA (Java Persistence API)
TopLink
JDO (Java Data Objects)
OJB
Description
Scopes a single bean definition to a single object instance per Spring IoC container.
prototype
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).
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 (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
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.
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:
44.What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.
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
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
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.
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 ?
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:
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.
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>
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.
empty elements
elements that contain only other elements
elements that contain only text
elements that contain both other elements and 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:
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.
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:
DOM
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:
Figure 5: XSL-FO