Professional Documents
Culture Documents
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.
• 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.
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="myNam" 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.
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 theservice() method. A scriptlet is written between the <% and %> tags and is
executed by the container at request processing time.
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.
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.
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 user’s request.
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.
16.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 directory structure of Struts application?
The directory structure of Struts application :
18.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.
21.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.
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
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.
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.
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> element’s<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.
<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.
• 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"/>
1) What is Spring?
Spring is a lightweight inversion of control and aspect-oriented container framework.
2) Explain 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.
• Framework: Spring provides most of the intra functionality leaving rest of the coding to
the developer.
3) What are the different modules in Spring framework?
• The Core container module
• Application context module
• AOP module (Aspect Oriented Programming)
• JDBC abstraction and DAO module
• O/R mapping integration module (Object/Relational)
• Web module
• MVC framework module
To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the
bean you want to retrieve.
MyBean myBean = (MyBean) factory.getBean("myBean");
In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully
qualified class name.
20) What are singleton beans and how can you create prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named
‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes
a prototype bean. By default it is set to true. So, all the beans in spring framework are by default
singleton beans.
<beans>
<bean id="bar" class="com.act.Foo" singleton=”false”/>
</beans>
When this interface is implemented, we should create and return a PreparedStatement from the
Connection argument, and the exception handling is automatically taken care off. When this
interface is implemented, another interface SqlProvider is also implemented which has a method
called getSql() which is used to provide sql strings to JdbcTemplate.
47) Explain about BatchPreparedStatementSetter?
If the user what to update more than one row at a shot then he can go for
BatchPreparedStatementSetter. This interface provides two methods
setValues(PreparedStatement ps, int i) throws SQLException;
int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also
determines how many times setValues() will be called.
48) Explain about RowCallbackHandler and why it is used?
In order to navigate through the records we generally go for ResultSet. But spring provides an
interface that handles this entire burden and leaves the user to decide what to do with each row.
The interface provided by spring isRowCallbackHandler. There is a method processRow() which
needs to be implemented so that it is applicable for each and everyrow.
void processRow(java.sql.ResultSet rs);
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.
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.
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
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.
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: Spring’s 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 ?
<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.
• Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a
getWebApplicationContext()method.
Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
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 SpringApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a
web-aware SpringApplicationContext.
global Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when
session used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
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.
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.
• 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 non-invasive
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.
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 theDataAccessException as the root exception. These exceptions wrap the original
exception.
Declarative • Can define transactions • Can define transactions declaratively through the
transaction declaratively through the Spring configuration file or through class
deployment descriptor. metadata.
support
• Can define transaction • Can define which methods to apply transaction
behavior per method or behavior explicitly or by using regular
per class by using the expressions.
wildcard character *. • Can declaratively define rollback behavior per
• Cannot declaratively method and per exception type.
define rollback behavior—
this must be done
programmatically.
Persistence Supports programmatic bean- Provides a framework for integrating with several
managed persistence and persistence technologies, including JDBC, Hibernate,
declarative container managed JDO, and iBATIS.
persistence.
Declarative • Supports declarative • No security implementation out-of-the box.
security security through users and • Acegi, an open source security framework built on
roles. The management top of Spring, provides declarative security
and implementation of through the Spring configuration file or class
users and roles is metadata.
container specific.
• Declarative security is
configured in the
deployment descriptor.
Distributed Provides container-managed Provides proxying for remote calls via RMI, JAX-
computing remote method calls. RPC, and web services.
J2EE Interview Questions
1) What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform
consists of a set of services, application programming interfaces (APIs), and protocols that provide
the functionality for developing multi tiered, and web-based applications.
1) What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service. This
lets the users to develop persistent classes following object-oriented principles such as
association, inheritance, polymorphism, composition, and collections.
2) What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of
objects in a Java application in to the tables of a relational database using the metadata that
describes the mapping between the objects and the database. It works by transforming the data
from one representation to another.
The Session and Transaction are the interfaces provided by hibernate. There are many other
interfaces besides this.
11) What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided in an
xml document. This document is called as xml mapping document. The document defines, among
other things, how properties of the user defined persistence classes’ map to the columns of the
relative tables in database.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibernate-
mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>
Everything should be included under tag. This is the main tag for an xml mapping document.
16) What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
8. ProxyFactory interface - used to create proxies
9. ConnectionProvider interface – used for JDBC connection management
10. TransactionFactory interface – Used for transaction management
11. Transaction interface – Used for transaction management
12. TransactionManagementLookup interface – Used in transaction management.
13. Cahce interface – provides caching techniques and strategies
14. CacheProvider interface – same as Cache interface
15. ClassPersister interface – provides ORM strategies
16. IdentifierGenerator interface – used for primary key generation
17. Dialect abstract class – provides SQL support
17) What are different environments to configure hibernate?
There are mainly two types of environments in which the configuration of hibernate application
differs.
18) What is the file extension you use for hibernate mapping file?
The name of the file should be like this : filenam.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this
extension.
First, we need to create an instance of Configuration and use that instance to refer to the location
of the configuration file. After configuring this instance is used to create the SessionFactory by
calling the method buildSessionFactory().
26) What are the different types of property and class mappings?
• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
Or
<property name="description" type="string">
<column name="DESCRIPTION"/>
</property>
• Derived properties
<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from
BID b where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>
• Object identity –Objects are identical if they reside in the same memory location in the
JVM. This can be checked by using the = = operator.
• Object equality –Objects are equal if they have the same value, as defined by the equals(
) method. Classes that don’t explicitly override this method inherit the implementation
defined by java.lang.Object, which compares object identity.
• Database identity –Objects stored in a relational database are identical if they represent
the same row or, equivalently, share the same table and primary key value.
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.
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
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
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.What’s the difference between load() and get()?
load() vs. get() :-
load() get()
Only use the load()method if you are sure that the If you are not sure that the object exists, then
object exists. use one of the get()methods.
load()method will throw an exception if the unique get()method will return null if the unique
id is not found in the database. id is not found in the database.
load()just returns a proxy by default and database
get()will hit the database immediately.
won’t be hit until the proxy is first invoked.
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.
26.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
Example:
JDBC Hibernate
With JDBC, developer has to write code to map Hibernate is flexible and powerful ORM solution
an object model's data representation to a to map Java classes to database tables. Hibernate
relational data model and its corresponding itself takes care of this mapping using XML files
database schema. so developer does not need to write code for this.
With JDBC, the automatic mapping of Java Hibernate provides transparent persistence and
objects with database tables and vice versa developer does not need to write code explicitly
conversion is to be taken care of by the developer to map database tables tuples to application
manually with lines of code. objects during interaction with RDBMS.
Hibernate provides a powerful query language
Hibernate Query Language (independent from
JDBC supports only native Structured Query
type of database) that is expressed in a familiar
Language (SQL). Developer has to find out the
SQL like syntax and includes full support for
efficient way to access database, i.e. to select
polymorphic queries. Hibernate also supports
effective query from a number of queries to
native SQL statements. It also selects an effective
perform same task.
way to perform a database manipulation task for
an application.
Application using JDBC to handle persistent data
(database tables) having database specific code in
Hibernate provides this mapping itself. The
large amount. The code written to map table data
actual mapping between tables and application
to application objects and vice versa is actually to
objects is done in XML files. If there is change in
map table fields to object properties. As table
Database or in any table then the only need to
changed or database changed then it’s essential to
change XML file properties.
change object structure as well as to change code
written to map table-to-object/object-to-table.
Hibernate reduces lines of code by maintaining
With JDBC, it is developer’s responsibility to
object-table mapping itself and returns result to
handle JDBC result set and convert it to Java
application in form of Java objects. It relieves
objects through code to use this persistent data in
programmer from manual handling of persistent
application. So with JDBC, mapping between
data, hence reducing the development time and
Java objects and database tables is done manually.
maintenance cost.
With JDBC, caching is maintained by hand- Hibernate, with Transparent Persistence, cache is
coding. 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.
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
In JDBC there is no check that always every user Java class object to that table. So if two users
has updated data. This check has to be added by retrieve same tuple and then modify it and one
the developer. 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.
36.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.
Callback interfaces allow the application to receive a notification when something interesting happens to an
object—for 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.
1. What is EJB?
EJB stands for Enterprise JavaBeans and is widely-adopted server side component architecture for
J2EE. It enables rapid development of ission-critical application that are versatile, reusable and
portable across middleware while protecting IT investment and preventing vendor lock-in.
12. The EJB container implements the EJBHome and EJBObject classes. For
every request from a unique client, does the container create a separate
instance of the generated EJBHome and EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. While referring the EJB Object classes the
container creates a separate instance for each client request. The instance pool maintenance is up
to the implementation of the container. If the container provides one, it is available otherwise it is
not mandatory for the provider to implement it. Having said that, yes most of the container
providers implement the pooling functionality to increase the performance of the application
server. The way it is implemented is, again, up to the implementer.
13. Can the primary key in the entity bean be a Java primitive type such as
int?
The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For
example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class,
not a primitive).
14. Can you control when passivation occurs?
The developer, according to the specification, cannot directly control when passivation occurs.
Although for Stateful Session Beans, the container cannot passivate an instance that is inside a
transaction. So using transactions can be a strategy to control passivation. The ejbPassivate()
method is called during passivation, so the developer has control over what to do during this
exercise and can implement the require optimized logic. Some EJB containers, such as BEA
Weblogic, provide the ability to tune the container to minimize passivation calls. Taken from the
Weblogic 6.0 DTD -The passivation-strategy can be either default or transaction. With the default
setting the container will attempt to keep a working set of beans in the cache. With the
transaction setting, the container will passivate the bean after every transaction (or method call
for a non-transactional invocation).
15. What is the advantage of using Entity bean for database operations, over
directly using JDBC API to do database operations? When would I use
one over the other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC
API. There are two types of Entity Beans Container Managed and Bean Managed. In Container
Managed Entity Bean - Whenever the instance of the bean is created the container automatically
retrieves the data from the DB/Persistence storage and assigns to the object variables in bean for
user to manipulate or use them. For this the developer needs to map the fields in the database to
the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed
Entity Bean - The developer has to specifically make connection, retrieve values, assign them to
the objects in the ejbLoad() which will be called by the container when it instantiates a bean
object. Similarly in the ejbStore() the container saves the object values back the persistence
storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container.
Apart from this, when you use Entity beans you don’t need to worry about database transaction
handling, database connection pooling etc. which are taken care by the ejb container.
18. What are the special design cares that must be taken when you work
with local interfaces?
It is important to understand that the calling semantics of local interfaces are different from those
of remote interfaces. For example, remote interfaces pass parameters using call-by-value
semantics, while local interfaces use call-by-reference. This means that in order to use local
interfaces safely, application developers need to carefully consider potential deployment scenarios
up front, then decide which interfaces can be local and which remote, and finally, develop the
application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in
some situations, the long-term costs of these choices, especially when changing requirements and
component reuse are taken into account, need to be factored into the design decision.
20. What is the difference between Message Driven Beans and Stateless
Session beans?
In several ways, the dynamic creation and allocation of message-driven bean instances mimics
the behavior of stateless session EJB instances, which exist only for the duration of a particular
method call. However, message-driven beans are different from stateless session EJBs (and other
types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages
asynchronously, rather than processing a serialized sequence of method calls. Message-driven
beans have no home or remote interface, and therefore cannot be directly accessed by internal or
external clients. Clients interact with message-driven beans only indirectly, by sending a message
to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by
creating bean instances and passing JMS messages to those instances as necessary. The
Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or
removed as a result of client requests or other API calls.
21. How can I call one EJB from inside of another EJB?
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.
27. What is the difference between session and entity beans? When should I
use one or the other?
An entity bean represents persistent global data from the database; a session bean represents
transient user-specific data that will die when the user disconnects (ends his session). Generally,
the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans
(e.g. Account.deposit, Account.withdraw)
28. Is there any default cache management system with Entity beans?
In other words whether a cache of the data in database will be maintained in EJB? - Caching data
from a database inside the Application Server are what Entity EJBs are used for. The ejbLoad()
and ejbStore() methods are used to synchronize the Entity Bean state with the persistent
storage(database). Transactions also play an important role in this scenario. If data is removed
from the database, via an external application - your Entity Bean can still be alive the EJB
container. When the transaction commits, ejbStore() is called and the row will not be found, and
the transaction rolled back.
31. How can I call one EJB from inside of another EJB?
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.
37. For Entity Beans, What happens to an instance field not mapped to any
persistent storage, when the bean is passivated?
The specification infers that the container never serializes an instance of an Entity bean (unlike
Stateful session beans). Thus passivation simply involves moving the bean from the ready to the
pooled bin. So what happens to the contents of an instance variable is controlled by the
programmer. Remember that when an entity bean is passivated the instance gets logically
disassociated from its remote object. Be careful here, as the functionality of passivation/activation
for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans
the ejbPassivate method notifies the entity bean that it is being disassociated with a particular
entity prior to reuse or for dereference.
38. What is a Message Driven Bean, what functions does a message driven
bean have and how do they work in collaboration with JMS?
Message driven beans are the latest addition to the family of component bean types defined by
the EJB specification. The original bean types include session beans, which contain business logic
and maintain a state associated with client sessions, and entity beans, which map objects to
persistent data. Message driven beans will provide asynchrony to EJB based applications by acting
as JMS message consumers. A message bean is associated with a JMS topic or queue and receives
JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message
beans do not have home or remote interfaces. Instead, message driven beans are instantiated by
the container as required. Like stateless session beans, message beans maintain no client-specific
state, allowing the container to optimally manage a pool of message-bean instances. Clients send
JMS messages to message beans in exactly the same manner as they would send messages to
any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of
the new specification. To receive JMS messages, message driven beans implement the
javax.jms.MessageListener interface, which defines a single onMessage() method. When a
message arrives, the container ensures that a message bean corresponding to the message
topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the
client’s message as the single argument. The message bean’s implementation of this method
contains the business logic required to process the message. Note that session beans and entity
beans are not allowed to function as message beans.
39. Does RMI-IIOP support code downloading for Java objects sent by value
across an IIOP connection in the same way as RMI does across a JRMP
connection?
Yes. The JDK 1.2 supports the dynamic class loading. The EJB container implements the EJBHome
and EJBObject classes. For every request from a unique client,
40. Does the container create a separate instance of the generated EJBHome
and EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. While referring the EJB Object classes the
container creates a separate instance for each client request. The instance pool maintenance is up
to the implementation of the container. If the container provides one, it is available otherwise it is
not mandatory for the provider to implement it. Having said that, yes most of the container
providers implement the pooling functionality to increase the performance of the application
server. The way it is implemented is again up to the implementer.
41. What is the advantage of putting an Entity Bean instance from the Ready
State to Pooled State?
The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has
been created, but has not been yet synchronized or assigned to an EJBObject. This mean that the
instances do represent entity beans, but they can be used only for serving Home methods (create
or findBy), since those methods do not relay on the specific values of the bean. All these instances
are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also
added: It can be looked at it this way: If no client is using an entity bean of a particular type there
is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the
container will, after some time, move the entity bean from the Ready State to the Pooled state to
save memory. Then, to save additional memory, the container may begin moving entity beans
from the Pooled State to the Does Not Exist State, because even though the bean’s cache has
been cleared, the bean still takes up some memory just being in the Pooled State.
42. What is the need of Remote and Home interface. Why can’t it be in one?
The main reason is because there is a clear division of roles and responsibilities between the two
interfaces. The home interface is your way to communicate with the container, that is that is
responsible of creating, locating even removing one or more beans. The remote interface is your
link to the bean that will allow you to remotely access to all its methods and members. As you can
see there are two distinct elements (the container and the beans) and you need two different
interfaces for accessing to both of them.
43. Can I develop an Entity Bean without implementing the create() method
in the home interface?
As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity
Bean. In cases where create() method is not provided, the only way to access the bean is by
knowing its primary key, and by acquiring a handle to it by using its corresponding finder method.
In those cases, you can create an instance of a bean based on the data present in the table. All
one needs to know is the primary key of that table. I.e. a set a columns that uniquely identify a
single row in that table. Once this is known, one can use the 'getPrimaryKey()' to get a remote
reference to that bean, which can further be used to invoke business methods.
What is the difference between Context, InitialContext and Session Context? How they are used?
javax.naming.Context is an interface that provides methods for binding a name to an object. It's
much like the RMI Naming.bind() method.
javax.naming.InitialContext is a Context and provides implementation for methods available in the
Context interface.
Where as SessionContext is an EJBContext objects that is provided by the EJB container to a
SessionBean in order for the SessionBean to access the information and/or services or the
container.
There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean
for the purpose of the EntityBean accessing the container details. In general, the EJBContext
(SessionContext and EntityContext), AppletContext and ServletContext help the corresponding
Java objects in knowing about its 'context' [environment in which they run], and to access
particular information and/or service. Whereas, the javax.naming.Context is for the purpose of
'NAMING' [by the way of referring to] an object.
44. Why an onMessage call in Message-driven bean is always a separate
transaction?
EJB 2.0 specification: "An onMessage call is always a separate transaction, because there is never
a transaction in progress when the method is called." When a message arrives, it is passed to the
Message Driven Bean through the onMessage() method, that is where the business logic goes.
Since there is no guarantee when the method is called and when the message will be processed,
is the container that is responsible of managing the environment, including transactions.
45. Why are ejbActivate() and ejbPassivate() included for stateless session
bean even though they are never required as it is a no conversational
bean?
To have a consistent interface, so that there is no different interface that you need to implement
for Stateful Session Bean and Stateless Session Bean. Both Stateless and Stateful Session Bean
implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to
remove ejbActivate and ejbPassivate from the interface.
46. Static variables in EJB should not be relied upon as they may break in
clusters. Why?
Static variables are only ok if they are final. If they are not final, they will break the cluster. What
that means is that if you cluster your application server (spread it across several machines) each
part of the cluster will run in its own JVM.
Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes
value of the static variable to be increased to 101. On the subsequent call to the same EJB from
the same client, a cluster 2 may be invoked to handle the request. A value of the static variable in
cluster 2 is still 100 because it was not increased yet and therefore your application ceases to be
consistent. Therefore, static non-final variables are strongly discouraged in EJBs.
52. When defining the Primary Key for the Enterprise Bean, the Deployer
using the Container Provider's tools will typically add additional
container-managed fields to the concrete subclass of the entity bean
class.
In this case, the Container must generate the Primary Key value when the entity bean instance is
created (and before ejbPostCreate is invoked on the instance.)
55. If my session bean with single method insert record into 2 entity beans,
how can know that the process is done in same transaction (the
attributes for these beans are Required)?
If your session bean is using bean-managed transactions, you can ensure that the calls are
handled in the same transaction by :
javax.transaction.UserTransaction tran= null;
try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}
You may want to check if you're already running in a transaction by calling tran.getStatus().
56. When should I adopt BMP and when I should use CMP?
You can use CMP and BMP beans in the same application... obviously, a bean can be BMP or CMP,
not both at the same time (they are mutually exclusive).
There is a common approach that is normally used and considered a good one. You should start
developing CMP beans, unless you require some kind of special bean, like multi-tables, that
cannot be completely realized with a single bean. Then, when you realize that you need
something more or that you would prefer handling the persistence (performance issue are the
most common reason), you can change the bean from a CMP to a BMP.
With J2EE implementations, you obtain the UserTransaction object with a code segment similar to
the following:
...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("java:comp/UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...
If the environment provides the UserTransaction object via a system property, you would use a
code segment similar to the following:
...
String transName = System.getProperty("jta.UserTransaction");
Context c = new InitialContext();
UserTransaction ut = (UserTransaction) c.lookup(transName);
ut.begin();
// perform multiple operations...
ut.commit()
...
JNDI remote look-up names and property names vary, of course, across servers/environment.
1) What is JSF?
JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this it
means complex components are pre-coded and can be used with ease. It is event-driven
programming model. By that it means that JSF has all necessary code for event handling and
component organization. Application programmers can concentrate on application logic rather
sending effort on these issues. It has component model that enables third-party components to
be added like AJAX.
Once this is done, one can access the JSF components using the prefix attached. If working with
an IDE (a.k.a Integrated Development Environment) one can easily add JSF but when working
without them one also has to update/make the faces-config.xml and have to populate the file
with classes i.e. Managed Beans between
<faces-config> </faces-config> tags
from-outcome to be match with action attribute of the command button of the login.jsp as:
<h:commandbutton value="Login" action="login"/>
<web-app version="e;2.4"e;
xmlns="e;http://java.sun.com/xml/ns/j2ee"e;
xmlns:xsi="e;http://www.w3.org/2001/XMLSchema-instance"e;
xsi:schemaLocation="e;http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"e;>
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>
The unique thing about this file is ?servlet mapping?. JSF pages are processed by a servlet known
to be part of JSF implementation code. In the example above, it has extension of .faces. It would
be wrong to point your browser to http://localhost:8080/MyJSF/login.jsp, but it has to be
http://localhost:8080/MyJSF/login.faces. If you want that your pages to be with .jsf, it can be
done with small modification :-),
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
<servlet-mapping>
As can be seen in Figure 1, JSF interacts with Client Devices which ties together with
presentation, navigation and event handling and business logic of web tier model. Hence JSF is
limited to presentation logic / tier. For Database tier i.e. Database and Web services one has to
rely on other services.
9) How does JSF depict the MVC (a.k.a Model View Controller) model?
The data that is manipulated in form or the other is done by model. The data presented to user in
one form or the other is done by view. JSF is connects the view and the model. View can be
depicted as shown by:
<h:inputText value="#{user.name}"/>
JSF acts as controller by way of action processing done by the user or triggering of an event. For
ex.
<h:commandbutton value="Login" action="login"/>
, this button event will triggered by the user on Button press, which will invoke the login Bean as
stated in the faces-config.xml file. Hence, it could be summarized as below: User Button Click ->
form submission to server -> invocation of Bean class -> result thrown by Bean class caught be
navigation rule -> navigation rule based on action directs to specific page.
12) How to pass a parameter to the JSF application using the URL string?
if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the
passing parameter id with the following lines of java code:
FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get("id");
From the page, you can access the same parameter using the predefined variable with name
param. For example,
<h:outputText value="#{param['id']}" />
Note: You have to call the jsf page directly and using the servlet mapping.
and then use the normal request methods to obtain path information. Alternatively,
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).
The following code snippet allows to terminate the session from the jsp page:
<% session.invalidate(); %> <c:redirect url="loginPage.jsf" />
<html>
<head>
<title>Input Name Page</title>
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
}
</script>
</head>
<body bgcolor="white">
<f:view>
<div id="main">
<h1><h:outputText value="#{Message.inputname_header}"/></h1>
<h:messages style="color: red"/>
<h:form id="helloForm">
<h:outputText value="#{Message.prompt}"/>
<h:inputText id="userName" value="#{GetNameBean.userName}"
required="true">
<f:validateLength minimum="2" maximum="20"/>
</h:inputText>
<h:commandButton onclick="gowait()" id="submit"
action="#{GetNameBean.action}" value="Say Hello" />
</h:form>
</div>
<div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0">
<table width="100%" height ="300px">
<tr>
<td align="center" valign="middle">
<h2>Please, wait...</h2>
</td>
</tr>
</table>
</div>
</f:view>
</body>
</html>
If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form
is just submitted. So, assign the id for your image and then add reload code that will be called
after some short delay. For the example above, it might be:
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
window.setTimeout('showProgress()', 500);
}
function showProgress(){
var wg = document.getElementById("waitgif");
wg.src=wg.src;
}
</script>
....
....
....
// use your own method that reads file to the byte array
byte[] pdf = getTheContentOfTheFile(filename);
FacesContext faces = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)
faces.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\"");
try {
ServletOutputStream out;
out = response.getOutputStream();
out.write(pdf);
} catch (IOException e) {
e.printStackTrace();
}
faces.responseComplete();
}
21) How to show Confirmation Dialog when user Click the Command Link?
h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your
own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use
onmousedown event that occurs before onclick. <script language="javascript"> function
ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete == true)
{ link.onclick(); } } </script> . . . . <h:commandLink action="delete" onmousedown="return
ConfirmDelete(this);"> <h:outputText value="delete it"/> </h:commandLink>
Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF
implementation will process it twice.
Hi there, I guess the Note: column should have been meant or intended for "faces-config.xml"
file as thats the default configuration file for JSF (which is similar to struts-config.xml for
Struts!!). faces-context.xml file sounds like the user defined config file similar to the
aforementioned two xml files.
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A facade view handler which maps URIs into actual physical views that the
* underlying implementation can deal with regularly.
* Therefore, all internal references to view ids, for example in faces-config,
* will use the path to the physical files. Everything publicized, however, will
* see a "converted" / facade url.
*/
public abstract class SimpleConverterViewHandler extends ViewHandler {
private static final Log LOG =
LogFactory.getLog(SimpleConverterViewHandler.class);
/**
* Distinguishes a URI from a physical file view.
* Tests if a view id is in the expected format -- the format corresponding
* to the physical file views, as opposed to the URIs.
* This test is necessary because JSF takes the view ID from the
* faces-config navigation, and calls renderView() on it, etc.
*/
public abstract boolean isViewFormat(FacesContext context, String viewId);
/**
* Convert a private file path (view id) into a public URI.
*/
public abstract String convertViewToURI(FacesContext context, String viewId);
/**
* Convert a public URI into a private file path (view id)
* note: uri always starts with "/";
*/
public abstract String convertURIToView(FacesContext context, String uri);
base.renderView(context, viewToRender);
}
<b>This is a text</b>
This is a text
26) h:inputSecret field becomes empty when page is reloaded. How to fix
this?
Set redisplay=true, it is false by default.
• Pattern Name and Classification : A short, meaningful name for the pattern, usually
only one or two words. Names provide a vocabulary for patterns, and they have implied
semantics – choose names carefully. Following the GoF book, we can also group patterns
into higher level classifications such as creational, structural, and behavioral patterns.
• Problem : A general description of the problem context and the goals and constraints that
occur repeatedly in that context. A concrete motivational scenario can be used to help
describe the problem. The problem description should provide guidance to assist others in
recognizing situations where the pattern can be applied.
• Solution : The classes and/or objects that participate in the design pattern, their
structure (e.g., in terms of a UML class diagram), their responsibilities, and their
collaborations. The solution provides an abstract description that can be applied in many
different situations. Sample Code in an object-oriented language can be used to illustrate
a concrete realization of the pattern.
• Consequences : A discussion of the results and tradeoffs of applying the pattern.
Variations and language-dependent alternatives should also be addressed.
• Known Uses : Examples of the pattern in real systems. Look for applications of the
pattern in language libraries and frameworks, published system descriptions, text books,
etc. Not every good solution represents a pattern. A general rule of thumb is that a
candidate pattern (also called a “proto-pattern”) should be discovered in a minimum of
three existing systems before it can rightfully be called a pattern.
The following quote by Robert Martin highlights the importance of providing pattern descriptions:
“The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in
which those patterns are documented. ... Prior to the GoF book, the only good way to learn
patterns was to discover them in design documentation, or (more probably) code.”
The programmer would access the single instance of this class by writing something similar to
Singleton.getInstance().someMethod()
or similar to
Singleton s = Singleton.getInstance();
s.method1();
...
s.method2();
...
For a more complete discussion of the Singleton pattern, see the chapter “Singleton” in the book
Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of Four” (Addison-
Wesley, 1995), or the chapter “Singleton” in the book Patterns in Java, Volume 1 by Mark Grand
(John Wiley & Sons, 1998). For information about variations on the Singleton Pattern, see the
chapter entitled “To Kill a Singleton” in the book Pattern Hatching: Design Patterns Applied by
John Vlissides or the article “Implementing the Singleton Pattern in Java” by Rod Waldhoff.
return Calenders for specific timezones and locales. The closest parallel is possibly the Factory
Method design pattern.
8) How can I make sure at most one instance of my class is ever created?
This is an instance where the Singleton design pattern would be used. You need to make the
constructor private (so nobody can create an instance) and provide a static method to get the
sole instance, where the first time the instance is retrieved it is created:
public class Mine {
private static Mine singleton;
private Mine() {
}
public static synchronized Mine getInstance() {
if (singleton == null) {
singleton = new Mine();
}
return singleton;
}
// other stuff...
}
• Factory Method: Define a interface for creating classes, let a subclass (or a helper class)
decide which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the
EJBObject implementations. They are actually created by a generated container class. See
InitialContextFactory interface that returns an InitialContext based on a properties
hashtable.
• Singleton: Ensure a class has only one instance, and provide a global point of access to
it.
There are many such classes. One example is javax.naming.NamingManager
• Adapter: Convert the interface of a class into another interface clients expect.
In the EJB implementation model, we implement an EJB in a class that extends
SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces.
EJB container generates a class that adapts the EJBObject interface by forwarding the calls
to the enterprise bean class and provides declarative transaction, persistence support.
12) What are the differences between analysis patterns and design
patterns?
Analysis pattern are for domain architecture, and design pattern are for implementation
mechanism for some aspect of the domain architecture. In brief, analysis pattern are more high
level and more (end-user) functional oriented.
NOTE: The 2nd check for if (instance_ == null) is needed to avoid making another unnecessary
construct.
Don't let this byte you! ;-)
16) What is the Reactor pattern?
The new book "Pattern-oriented Software Architecture Volume 2" ISBN 0471606952 has a
chapter on the Reactor pattern. It falls under the general category of "Event Handling Patterns".
To quote the leading bit of the chapter,
"The Reactor architectural pattern allows event-driven applications to demultiplex and dispatch
service requests that are delivered to an application from one or more clients"
It is used in a synchronous manner, so that if the callback you delegate the event to takes a while
to complete you will run into problems with scalability.
18) How and where did the concept of design patterns get started?
Work on patterns has been influenced by the works of Christopher Alexander who published on
topics related to urban planning and building architecture in the late 1970s. The history of
patterns for software design began in the late 1980s and reached an important milestone with
the publishing of the first book fully dedicated to this subject by the "Gang of Four", Erich
Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns - Elements of Reusable
Object-Oriented Software). In conjunction, the emergence of object-oriented software
development fostered the work on other topics related to design patterns such as application
frameworks, analysis patterns, language idioms, and so on.
Note that Cloneable is an empty interface! It merely acts as a tag to state that you really want
instance of the class to be cloned. If you don't implement Cloneable, the super.clone()
implementation will throw a CloneNotSupportedException.