Ilovepdf Merged
Ilovepdf Merged
The throw statement is used to signal the occurance of the exception within a try block.
Often, exceptions are instantiated in the same statement in which they are thrown using the
syntax.
To handle the exception within the method where it is thrown, a catch statement that
handles MyException, must follow the try block. If the developer does not want to handle
the exception in the method itself, the method must pass the exception using the syntax:
8) What is serialization?
Quite simply, object serialization provides a program the ability to read or write a whole
object to and from a raw byte stream. It allows Java objects and primitives to be encoded
into a byte stream suitable for streaming to some type of network or to a file-system, or
more generally, to a transmission medium or storage facility. A seralizable object must
implement the Serilizable interface. We use ObjectOutputStream to write this object to a
stream and ObjectInputStream to read it from the stream.
97) What value does read() return when it has reached the
end of a file?
The read() method returns -1 when it has reached the end of a file.
98) Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.
194) What are three ways in which a thread can enter the
waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by
unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait()
method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
207) What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is
used to represent the classes and interfaces that are loaded by a Java program..
212) What methods are used to get and set the text label
displayed by a Button object?
getLabel() and setLabel()
215) What are the two basic ways in which classes that
can be run as threads may be defined?
A thread class may be declared as a subclass of Thread, or it may implement the Runnable
interface.
throw ThrowableInstance;
Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
/home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 1
System.out.println("Inside throwOne.");
9) What are Checked Exceptions and Unchecked
Exceptions?
The types of exceptions that need not be included in a methods throws list are called
Unchecked Exceptions.
• ArithmeticException
• ArrayIndexOutOfBoundsException
• ClassCastException
• IndexOutOfBoundsException
• IllegalStateException
• NullPointerException
• SecurityException
The types of exceptions that must be included in a methods throws list if that method can
generate one of these exceptions and does not handle it itself are called Checked
Exceptions.
• ClassNotFoundException
• CloneNotSupportedException
• IllegalAccessException
• InstantiationException
• InterruptedException
• NoSuchFieldException
• NoSuchMethodException
Throwable getCause( )
14) How can I retrieve only the first n rows, second n rows
of a database using a particular WHERE clause ? For
example, if a SELECT typically returns a 1000 rows, how do
first retrieve the 100 rows, then go back and retrieve the
next 100 rows and so on ?
Use the Statement.setFetchSize method to indicate the size of each database fetch. Note
that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no
standardized way of setting the fetch size exists. Please consult the Db driver manual.
{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}
19) How do I insert an image file (or other raw data) into
a database?
All raw data types (including binary documents or images) should be read and uploaded to
the database as an array of bytes, byte[]. Originating from a binary file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to
upload the data.
// Perform insert
int rowsAffected = stmnt.executeUpdate();
}
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
a new transaction is implicitly started.
14) How can I retrieve only the first n rows, second n rows
of a database using a particular WHERE clause ? For
example, if a SELECT typically returns a 1000 rows, how do
first retrieve the 100 rows, then go back and retrieve the
next 100 rows and so on ?
Use the Statement.setFetchSize method to indicate the size of each database fetch. Note
that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no
standardized way of setting the fetch size exists. Please consult the Db driver manual.
{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}
19) How do I insert an image file (or other raw data) into
a database?
All raw data types (including binary documents or images) should be read and uploaded to
the database as an array of bytes, byte[]. Originating from a binary file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to
upload the data.
// Perform insert
int rowsAffected = stmnt.executeUpdate();
}
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
a new transaction is implicitly started.
3) What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the
Jakarta Struts Framework this class plays the role of controller. All the requests to the
server goes through the controller. Controller is responsible for handling all the requests.
6) What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm
maintains the session state for web application and the ActionForm object is automatically
populated on the server side with data entered from a form on the client side.
<html:errors/$gt;
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.
To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of
the bean you want to retrieve.
In the bean tag the id attribute specifies the bean name and the class attribute specifies the
fully qualified class name.
21) 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>
22) What are the important beans lifecycle methods?
There are two important bean lifecycle methods. The first one is setup which is called when
the bean is loaded in to the container. The second method is the teardown method which is
called when the bean is unloaded from the container.
<beans>
<bean id="bar" class="com.act.Foo" init-method=”fooSetup” destroy=”fooTeardown”/
</beans>
<beans>
<bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>
</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.
int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this
also determines how many times setValues() will be called.
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.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibernate-map
<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.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionF
hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTra
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect
• Derived properties
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.
6) Calendar is an abstract class. The getInstance() method
tries to instantiate GregorianCalendar() i.e., parent
instantiating a derived class. This looks Non-OO? Ex:
Calendar a=Calendar.getInstance(); Can somebody explain
why is it so?
The Calender class is an abstact class, true, however,the point you missed is that the
getInstance() returns the " Calendar using the default timezone and locale. " , in your case,
the GregorianCalender a class that IS a Calender (a Suzuki IS a car, a 747 IS a plane..the
standard OO terminology. So what you get is a class that does some specialized work based
on the default locale. Other methods
return Calenders for specific timezones and locales. The closest parallel is possibly the
Factory Method design pattern.
package com.jgk.patterns.singleton;
public class JGKSingleton {
NOTE: The 2nd check for if (instance_ == null) is needed to avoid making another unnecessary
construct.
Don't let this byte you! ;-)
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.
The Object implementation of clone() performs a shallow copy of the object in question.
That is, it copies the values of the fields in the object, but not any actual objects that may
be pointed to. In other words, the new object will point to the same objects the old object
pointed to.
As an example of using the cloning:
This example is pretty trivial, but the real power comes when you don't know what you're
actually cloning.
For example, suppose you define an interface that represents a customer:
You might have several different implementations of this interface, possibly storing data in a
file, database, or using EJB Entity beans. If a shallow copy of the data is sufficient to
represent a copy of the object, Java's clone() method works great.
You might have a method that needs to make a copy of the data to store it in a Hashtable,
for example:
Note that this method knows nothing about what type of customer we're getting. This
pattern will work for any actual type of Customer, no matter how the data is stored. For
example:
manager.storeCustomer(c1);
manager.storeCustomer(c2);
manager.storeCustomer(c3);
class PieceOfCode {
public Object myMethod() {}
}
class EJBImpl ... {
PieceOfCode poc = new PieceOfCode();
public Object myMethod() {
return poc.myMethod();
}
}
This should not be a violation of EJB specs, since EJBs can use simple java classes for their
use. Think about Dependant Objects and so on.
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.
19. What happens if remove( ) is never invoked on a
session bean?
In case of a stateless session bean it may not matter if we call or not as in both cases
nothing is done. The number of beans in cache is managed by the container. In case of
Stateful session bean, the bean may be kept in cache till either the session times out, in
which case the bean is removed or when there is a requirement for memory in which case
the data is cached and the bean is sent to free pool.
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.
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.
You may want to check if you're already running in a transaction by calling tran.getStatus().
57. 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.
...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("javax.jts.UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...
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.
ï‚· An enterprise bean must not use the java.io package to attempt to access files
directories in the file system.
The file system APIs are not well-suited for business components to access data. B
components should use a resource manager API, such as JDBC API, to store data.
Alternative Solutions
To perform logging operations you must you a resource connection supported by the
EJB servers may support several resource connection options, which can be used to
below:
Containers will manage many beans simultaneously in the same fashion that a Java
WebServer manages many Servlets. To reduce memory consumption and processing,
containers pool resources and manage the lifecycles of all the beans very carefully. When a
bean is not being used a container will place it in a pool to be reused by another client, or
possibly evict it from memory and only bring it back when its needed. Because client
applications don't have direct access to the beans -- the container lies between the client
and bean -- the client application is completely unaware of the containers resource
management activities. A bean that is not in use, for example, might be evicted from
memory on the server, while its remote reference on the client remains intact. When the
client invokes a method on the remote reference, the container simply re-incarnates the
bean to service the request. The client application is unaware of the entire process.
An enterprise bean depends on the container for everything it needs. If an enterprise bean
needs to access a JDBC connection or another enterprise bean, it does so through the
container; if an enterprise bean needs to access the identity of its caller, obtain a reference
to itself, or access properties it does so through the container. The enterprise bean interacts
with its container through one of three mechanisms: callback methods, the EJBContext
interface, or JNDI.
• Callback Methods: Every bean implements a subtype of the EnterpriseBean
interface which defines several methods, called callback methods. Each callback
method alerts the bean of a different event in its lifecycle and the container will
invoke these methods to notify the bean when it's about to pool the bean, persist its
state to the database, end a transaction, remove the bean from memory, etc. The
callback methods give the bean a chance to do some housework immediately before
or after some event. Callback methods are discussed in more detail in other
sections.
• EJBContext: Every bean obtains an EJBContext object, which is a reference directly
to the container. The EJBContext interface provides methods for interacting with the
container so that that bean can request information about its environment like the
identity of its client, the status of a transaction, or to obtain remote references to
itself.
• JNDI: Java Naming and Directory Interface is a Java extension API for accessing
naming systems like LDAP, NetWare, file systems, etc. Every bean automatically has
access to a special naming system called the Environment Naming Context (ENC).
The ENC is managed by the container and accessed by beans using JNDI. The JNDI
ENC allows a bean to access resources like JDBC connections, other enterprise
beans, and properties specific to that bean.
The EJB specification defines a bean-container contract, which includes the mechanisms
(callbacks, EJBContext, JNDI ENC) described above as well as a strict set of rules that
describe how enterprise beans and their containers will behave at runtime, how security
access is checked, transactions are managed, persistence is applied, etc. The bean-
container contract is designed to make enterprise beans portable between EJB containers so
that enterprise beans can be developed once then run in any EJB container. Vendors like
BEA, IBM, and Gemstone sell application servers that include EJB containers. Ideally, any
enterprise bean that conforms to the specification should be able to run in any conformant
EJB container.
Portability is central to the value that EJB brings to the table. Portability ensures that a bean
developed for one container can be migrated to another if another brand offers more
performance, features, or savings. Portability also means that the bean developer's skills
can be leveraged across several EJB container brands, providing organizations and
developers with better opportunities.
In addition to portability, the simplicity of the EJB programming model makes EJB valuable.
Because the container takes care of managing complex tasks like security, transactions,
persistence, concurrency and resource management the bean developer is free to focus
attention on business rules and a very simple programming model. A simple programming
model means that beans can be developed faster without requiring a Ph.D. in distributed
objects, transactions and other enterprise systems. EJB brings transaction processing and
disributed objects development into the mainstream.
<enterprise-beans>
<entity>
<description>This entity bean models an audio compact disc.</description>
<ejb-name>MusicCDBean</ejb-name>
<home>musicstore.MusicCDHome</home>
<remote>musicstore.MusicCD</remote>
<ejb-class>musicstore.MusicCDBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>musicstore.MusicCDPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-field><field-name>upc</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>artist</field-name></cmp-field>
<cmp-field><field-name>type</field-name></cmp-field>
<cmp-field><field-name>price</field-name></cmp-field>
</entity>
</enterprise-beans>
In the above deployment descriptor, the container-managed fields are specified to be upc,
title, artist, type, and price.
While the deployment descriptor provides information about the container-managed fields
for use during deployment, the details of how these fields are mapped into the database (or
other persistent storage mechanism) are controlled by the container-specific deployment
process itself. To learn more about the container-specific deployment process, you will need
to consult your container vendor's documentation.
begin transaction
...
update table-a
...
if (condition-x)
commit transaction
else if (condition-y)
update table-b
commit transaction
else
rollback transaction
begin transaction
update table-c
commit transaction
...
I think what it means is there are some limitations in j2ee transaction support. In a
container managed situation, nested or multiple transactions are not allowed within a
method. if a biz method needs those features you need to go for bean managed
transactions.
99. How do I automatically generate primary keys?
A common way to do it is to use a stateless session bean to retrieve the ID that you wish to
use as the primary key. This stateless session bean can then execute an Oracle sequencer
or procedure etc. to retrieve the ID value used as the primary key.
<resource-ref>
<res-ref-name>jdbc/LocalDB2<res-ref-name>
<res-type>javax.sql.DataSource<res-type>
<res-auth>Container<res-auth>
<resource-ref>
The res-ref-name is the most interesting part. This is the JNDI name relative to the
java:comp/env namespace. Hence, to get this connection you'd do (in your bean):
which gives you a DataSource that you can call getConnection on.
The other half of this is container specific and done at deployment time by a 'Deployer' or
'Assembler' (to use the rolenames specified by the EJB spec.) This can work very differently
from one container to the next, but here are a couple of (abbreviated) examples.
With Weblogic 5.1, you must define a connection pool in weblogic.properties, then edit the
weblogic specific deployment descriptor (using the EJB Deployment tool) to associate the
resource-ref specified in ejb-jar.xml with that connection pool.
With Inprise Application Server 4.0, all of the parameters for the connection (JDBC driver,
connection URL, etc.) are specified in the inprise specific deployment descriptor (also
editable via their deployment tool).
Other servers will have other ways of associating the resource-ref with a pre-defined
connection pool.
/**
* Called by the container after the UserHome.create() is called
*/
public void ejbCreate(String userId, String password, long acctNum) {
this.userId = userId;
this.password = password;
this.acctNum = acctNum;
}
...
...
Now, assuming you have the User (remote interface class), UserHome (home interface
class), UserPK (primary key class) already done, you need to create the bean's deployment
descriptor. Inside the deployment descriptor, you must specify the database table, 'users',
which this bean will map to. Also, you must specify which fields from your bean map to
which fields in the 'users' database table. (This is how the container knows which fields to
persist between your bean and the database table.) Now assuming all code compiles and
you have an EJB server up and running and you have deployed your bean, all you need to
do is write a client (I would use a client to access a session bean, say 'CustomerSession',
which would talk to my entity bean) to create a new user and pass in the userId, password
and acctNum values, which will create the new user in the database.
Notice the fields in the UserBean will now be set, but the firstName and lastName fields will
still be set to null. These fields will still be empty in the database and will not change until
these fields are set in the bean, since it is persisted. Now, call the setUserData(UserData
data) method for setting the firstName and lastName, and these fields will now be set in the
database and no longer be null. The container will handle the persistence of any fields which
are set to null, just as it will handle any fields which are set to some meaningful value.
...
Properties p = new Properties();
..
p.put(Context.SECURITY_PRINCIPAL, "user");
p.put(Context.SECURITY_CREDENTIALS, "password");
...
3. Inside your bean, you can do "extra" security checks (if you used 'Role'-based
security): (Assuming you have a 'manager' role defined in your deployment
descriptor and a user assigned to this role)
You could also enforce security to your EJB server. Using Weblogic, you could add
the following to your weblogic.properties file:
...
weblogic.password.user=password
...
where "user" is the username you grant access for and "password" (after '=') is the
password for this username.
Probably not the answer you're looking for, especially if you allocate some other resource (a
Message Queue, for example) that you need to release. Although, if you're using a resource,
you really should be getting it when you need it (via JNDI) and returning it back to the pool
right away.
125. I have created a remote reference to an EJB in
FirstServlet. Can I put the reference in a servlet session
and use that in SecondServlet?
Yes.
The EJB client (in this case your servlet) acquires a remote reference to an EJB from the
Home Interface; that reference is serializable and can be passed from servlet to servlet.
If it is a session bean, then the EJB server will consider your web client's servlet session to
correspond to a single EJB session, which is usually (but not always) what you want.
127. How can I call one EJB from inside of another EJB?
Just do it!
EJBs can be clients of other EJBs. It just works. Really. Use JNDI to locate the Home
Interface of the other bean, then acquire an instance reference, and so forth.
129. Can I deploy two beans in a single jar file? If so, how?
Yes, multiple EJBs can be deployed in a single jar file. The deployment is somewhat
different between EJB 1.0 and EJB 1.1.
In EJB 1.1 and in the draft EJB 2.0 specification, instead of a manifest and serialized
deployment descriptors there is a single shared XML deployment descriptor named META-
INF/ejb-jar.xml. Within ejb-jar.xml there must be either a <session> or <entity> element
for each bean in the jar file. For example, the following XML fragment is for a jar file that
contains one entity and one session bean:
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MySessionBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</session>
<entity>
<ejb-name>MyEntityBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</entity>
</enterprise-beans>
</ejb-jar>
The EJB 2.0 draft specification for deployment descriptors differs from EJB 1.1 only in the
addition of XML elements for describing additional bean properties.
130. Why use EJB when we can do the same thing with
servlets?
Actually, servlets/JSPs and EJB are complementary, not competing technologies: Servlets
provide support for writing web based applications whereas EJBs provide support for writing
transactional objects. In larger web systems that require scalability, servlet and JSP or XML/
XSL technologies provide support for the front end (UI, client) code, where EJB provides
support for the back end (database connection pooling, declaritive transactions, declaritive
security, standardized parameterization...)
The most significant difference between a web application using only servlets and one using
servlets with EJBs is that the EJB model mandates a separation between display and
business logic. This is generally considered a Good Thing in non-trivial applications because
it allows for internal reuse, allows flexibility by providing a separation of concerns, gives a
logical separation for work, and allows the business logic to be tested separately from the
UI (among others).
Some of the hings that servlets and JSPs can do that EJBs cannot are:
• Respond to http/https protocol requests.
• (With JSP) provide an easy way to format HTML output.
• Easily associate a web user with session information
Some of the things that EJBs enable you to do that servlets/JSPs do not are:
• Declaritively manage transactions. In EJB, you merely specify whether a bean's
methods require, disallow, or can be used in the context of a transaction. The EJB
container will manage your transaction boundaries appropriately. In a purely servlet
architecture, you'll have to write code to manage the transaction, which is difficult if
a logical transaction must access multiple datasources.
• Declaritively manage security. The EJB model allows you to indicate a security role
that the user must be assigned to in order to invoke a method on a bean. In
Servlets/JSPs you must write code to do this. Note, however that the security model
in EJB is sufficient for only 90% to 95% of application code - there are always
security scenarios that require reference to values of an entity, etc.
<env-entry>
<env-entry-name>theParameter</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>
You can access the variable inside your EJB using the Environment Naming Context (in EJB
1.1)
<?xml version="1.0"?>
<jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
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
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/main.jsp<to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.jsp<to-view-id>
</navigation-case>
</navigation-rule>
from-outcome to be match with action attribute of the command button of the login.jsp as:
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>core.jsf.LoginBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<h:inputText value="#{user.name}"/>
<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.
<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.
, 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.
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,
Note: You have to call the jsf page directly and using the servlet mapping.
<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.fac
14) How to get current page URL from backing bean?
You can get a reference to the HTTP request object via FacesContext like this:
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getReque
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).
<context-param>
<param-name>connectionString</param-name>
<param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value>
</context-param>
FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");
<context-param>
<param-name>productId</param-name>
<param-value>2004Q4</param-value>
</context-param>
The following code snippet allows to terminate the session from the jsp page:
<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.act
</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);
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config-navigation.xml,/WEB-INF/faces-beans.xml</par
</context-param>
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.
24) How to mask actual URL to the JSF page?
You'll need to implement your own version of javax.faces.ViewHandler which does what you
need. Then, you register your own view handler in faces-config.xml.
Here's a simple abstract ViewHandler you can extend and then implement the 3 abstract
methods for. The abstract methods you override here are where you'll do your conversions
to/from URI to physical paths on the file system. This information is just passed right along
to the default ViewHandler for JSF to deal with in the usual way. For example, you could
override these methods to add and remove the file extension of an incoming view id (like in
your example), for extension-less view URIs.
import java.io.IOException;
import java.util.Locale;
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.cla
/**
* 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