Java - ms32m - mx128m For Resizing The JVM Heap Space
Java - ms32m - mx128m For Resizing The JVM Heap Space
1. What is EJB
Session Facade is a design pattern to access the Entity bean through local
interface than accessing directly. It increases the performance over the network.
In this case we call session bean which on turn call entity bean.
EJB technology is the core of J2EE. It enables developers to write reusable and
portable server-side business logic for the J2EE platform.
EJB is a specification for J2EE server, not a product; Java beans may be a
graphical component in IDE.
Entity Bean is a Java class which implements an Enterprise Bean interface and
provides the implementation of the business methods. There are two types:
Container Managed Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two
types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t
maintain any conversational state with clients between method invocations.
Stateful bean maintains state between invocations.
Retrieve Home Object reference from Naming Service via JNDI. Return Home
Object reference to the client. Create me a new EJB Object through Home Object
interface. Create EJB Object from the Ejb Object. Return EJB Object reference to
the client. Invoke business method using EJB Object reference. Delegate request
to Bean (Enterprise Bean).
11. Is it possible to share an HttpSession between a JSP and EJB? What happens
when I change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects
in session are serializable.This has to be consider as passed-by-value, that means
that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t
be reflected back to the HttpSession of the Servlet Container.The pass-by-
reference can be used between EJBs Remote Interfaces, as they are remote
references. While it is possible to pass an HttpSession as a parameter to an EJB
object, it is considered to be bad practice in terms of object-oriented design. This
is because you are creating an unnecessary coupling between back-end objects
(EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction
for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries
with it a bunch of http semantics), create a class that acts as a value object (or
structure) that holds all the data you need to pass back and forth between front-
end/back-end. Consider the case where your EJB needs to support a non HTTP-
based client. This higher level of abstraction will be flexible enough to support it.
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 refering 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).
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 Mananged. In Container Managed Entity Bean - Whenever the instance
of the bean is created the container automatically retrieves the data from the
DB/Persistance 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, retrive values, assign them to the objects in the ejbLoad()
which will be called by the container when it instatiates a bean object. Similarly in
the ejbStore() the container saves the object values back the the persistance
storage. ejbLoad and ejbStore are callback methods and can be only invoked by
the container. Apart from this, when you use Entity beans you dont 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 care that must be taken when you work with local
interfaces?
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.
20. What is the difference between Message Driven Beans and Stateless Session
beans?
22. 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.
Technically yes, spec. compliant NO! - The enterprise bean must not attempt to
query a class to obtain information about the declared members that are not
otherwise accessible to the enterprise bean because of the security rules of the
Java language
Although technically it is legal, static initializer blocks are used to execute some
piece of code before executing any constructor or method while instantiating a
class. Static initializer blocks are also typically used to initialize static fields -
which may be illegal in EJB if they are read/write - In EJB this can be achieved by
including the code in either the ejbCreate(), setSessionContext() or
setEntityContext() methods.
Stopping the execution of a method inside a Session Bean is not possible without
writing code inside the Session Bean. This is because you are not allowed to
access Threads inside an EJB.
There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec
says that the deployer must specify a value for the transaction attribute for those
methods having container managed transaction. In WebLogic, the default
transaction attribute for EJB is SUPPORTS.
28. 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)
29. 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 AAApplication Server are what
Entity EJB’s 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.
An Entity Bean represents persistent data that is stored outside of the EJB
Container/Server. The ejbFindByPrimaryKey is a method used to locate and load
an Entity Bean into the container, similar to a SELECT statement in SQL. By
making this method mandatory, the client programmer can be assured that if
they have the primary key of the Entity Bean, then they can retrieve the bean
without having to create a new bean each time - which would mean creating
duplications of persistent data and break the integrity of EJB.
With the EJBHome version of the remove, you are able to delete an entity bean
without first instantiating it (you can provide a PrimaryKey object as a parameter
to the remove method). The home version only works for entity beans. On the
other hand, the Remote interface version works on an entity bean that you have
already instantiated. In addition, the remote version also works on session beans
(stateless and stateful) to inform the container of your loss of interest in this
bean.
32. 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.
Persistence in EJB is taken care of in two ways, depending on how you implement
your beans: container managed persistence (CMP) or bean managed persistence
(BMP) For CMP, the EJB container which your beans run under takes care of the
persistence of the fields you have declared to be persisted with the database -
this declaration is in the deployment descriptor. So, anytime you modify a field in
a CMP bean, as soon as the method you have executed is finished, the new data
is persisted to the database by the container. For BMP, the EJB bean developer is
responsible for defining the persistence routines in the proper places in the bean,
for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be
developed by the bean developer to make calls to the database. The container is
responsible, in BMP, to call the appropriate method on the bean. So, if the bean is
being looked up, when the create() method is called on the Home interface, then
the container is responsible for calling the ejbCreate() method in the bean, which
should have functionality inside for going to the database and looking up the
data.
Yes you can overload methods Should synchronization primitives be used on bean
methods? - No. The EJB specification specifically states that the enterprise bean is
not allowed to use thread primitives. The container is responsible for managing
concurrent access to beans at runtime.
No. You cannot change the transaction isolation level in the middle of transaction.
38. 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 it’s 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.
39. 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.
40. 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 support the dynamic class loading. The EJB container
implements the EJBHome and EJBObject classes. For every request from a unique
client,
41. 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 refering the
EJB Object classes the container creates a separate instance for each client
request. The instance pool maintainence 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.
42. 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.
By Admin on Nov 4, 2007 in Java System Design & Analysis Patterns Interview
Qu | 0 Comments
Share This
Is Struts threadsafe?
Yes
Struts provide many tag libraries to ease the development of web applications.
These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes,
checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities
and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application
What is ActionMapping?
banking
org.apache.struts.action.ActionServlet
config /WEB-INF/struts-config.xml,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
1
< / servlet >
Share This
Portlets are packaged as WAR files with a web application deployment descriptor
(web.xml). This defines each portlet as a servlet within the web application,
including unique identifiers for each portlet, the portlet class, and initialization
parameters.
1. open WSAD
2. go to project
3. click properties
4. select javaBuildPath
5. add any jar file like jaxp select add external jars.
If you use JDBC type (I) driver you dont need to add any driver in websphere.
you simply created DSN and use it locally, same we use java class, if you use
Type(2) and Type(4) so first go to admin console then go to connection, then add
driver there fill other info like conn. size, uname pass, max conn. and connect it
to you applications.
JSP Action:
* JSP actions are XML tags that direct the server to use existing components or
control the behavior of the JSP engine.
* Consist of typical (XML-base) prefix of ‘jsp’ followed by a colon, followed by the
action name followed by one or more attribute parameters. For example: There
are six JSP Actions: , , , , ,
How can you enable session tracking for JSP pages if the browser has disabled
cookies: We can enable session tracking using URL rewriting. URL rewriting
includes the sessionID within the link itself as a name/value pair. However, for
this to be effective, you need to append the session Id for each and every link
that is part of your servlet response. adding sessionId to a link is greatly
simplified by means of a couple of methods: response.ecnodeURL() associates a
session ID with a giver UIRl, and if you are using redirection,
response.encodeRedirectURL() can be used by giving the redirected URL as input.
Both encodeURL() and encodeRedirectURL() first determine whether cookies are
supported by the browser; is so, the input URL is returned unchanged since the
session ID wil lbe persisted as cookie.
How do I prevent the output of my JSP or servlet pages from being caches by the
browser?
Set the appropriate HTTP header attributes to prevent the dynamic content
output by the JSP page from being cached by the browser. Execute the following
scriptlet at the beginning of JSP pages to prevent them from being caches at the
browser.
Share This
What is UML?
They are 9: Use case diagram, class diagram, object diagram, sequence diagram,
statechart diagram, collaboration diagram, activity diagram, component diagram,
deployment diagram.
SDLC: Software development life cycle. SDLC of a system includes processes that
are Use case driven, architecture centric and iterative and incremental. Life cycle
is divided into phases. Phase is a time span between two milestones. The
milestones are Inception, Elaboration, construction, and transition. Process
workflows that evolve through these phase are Business Modelling, Requirement
gathering, Analysis and Design, Implementation, Testing, Deployment.
Supporting workflows are configuration and change management, Project
management.
Use Case: specifies the behavior of a system or a part of a system. Involves the
interaction of actors and system.
Aggregation: One class owns but shares a reference to objects of another class.
Child refrerence exists even if parent oject rereference is set to null. Symbol:
empty diamond arrow.
Composition: one class contains objects of another class. child reference does not
exists independently. Symbol: filled diamond arrow.
Share This
doGet() mthod is limited with 2k of data to be sent, and doPost() mehtod doesn’t
have this limitation. A request string for doGet() looks like the following:
http://www.google.com/svt1?p1=v1&p2=v2&…&pN=vN. doPost() method call
doesntneed a long texttail after a servlet name in a request. All parameters are
stored in a request itself, not in a request string, and its impossible to guess the
data transmitted to a servlet only looking at the request string.
ServletConfig: the object created after a servlet is instantiated and its default
constructor is read. It is created to pass initialization infomation to the servlet.
Share This
Inheritance:
Implicit Casting:
Polymorphism: one name many forms. enables one entity to be used as general
category for different types of actions.
Encapsulation: process of binding or wrapping the data and the codes that
operates on the data into single entity. This keeps data safe from outside
interface and misuse. objects allow procedures to be encapsulated with their data
to reduce potential interference. one way to think about encapsulation is as a
protective wrapper that prevents code and data from being arbitrarily accessed
by other code defined outside the wrapper.
What is OOPs?
Object oriented programming organizes a program around its data, ie., objets
and a set of welll defined intervaces to that data.
Transient modifier applies to variables only and it is not stored as part or its
objects persistent state. Transient variables are not serialized. Volatile modifier
applies to variables only and it tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of the program.
Inner class: classes defined in other classes, including those defined in methods
are called inner classes. An inner class can have nay accessibility including
private. Anonymous class: class defined inside a mthod without name and is
instantiated and declared in the same place and cannot have explicit
constructors.
Abstract class: class designed with implementation gaps for subclasses to fill in
and is deliberately incomplete. Interface: similar to a class which may contain
method’s signature only but no body and it is a formal set of methods and
contsant declarations that must be defined by the class that implements it.
interfaces are usefull for: declaring methods that one or more classes are
expected to implement, capturing similarities between unrelated classes without
forcing a class relationship.
2. What is ActionServlet?
3. How you will make available any Message Resources Definitions file to the
Struts Framework Environment?
Message Resources Definitions file are simple .properties files and these files
contains the messages that can be used in the struts project. Message Resources
Definitions files can be added to the struts-config.xml file through tag.
Example:
generates the client side java script for the form “logonForm” as defined in the
validation.xml file. The when added in the jsp file generates the client site
validation script.
Yes
No
Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println(”inside”);
};
public static void main(String a1[])
{
System.out.println(”in interfia”);
}
}
}
No
5. What is Externalizable?
Only public and abstract modifiers are allowed for methods in interfaces.
Variables declared within a method are “local” variables. Variables declared within
the class i.e not within any methods are “member” variables (global variables).
Variables declared within the class i.e not within any methods and are defined as
“static” are class variables
8. What are the different identifier states of a Thread?
Because C++ has proven by example that operator overloading makes code
almost impossible to maintain. In fact there very nearly wasn’t even method
overloading in Java, but it was thought that this was too useful for some very
basic methods like print(). Note that some of the classes like DataOutputStream
have unoverloaded methods like writeInt() and writeByte().
Static variables and methods are instantiated only once per class. In other words
they are class variables, not instance variables. If you change the value of a
static variable in a particular object, the value of that variable changes for all
instances of that class. Static methods can be referenced with the name of the
class rather than the name of a particular object of the class (though that works
too). That’s how library methods like System.out.println() work. out is a static
field in the java.lang.System class.
12. How do I convert a numeric IP address like 192.18.97.39 into a hostname like
java.sun.com?
Threads block on i/o (that is enters the waiting state) so that other threads may
execute while the I/O operation is performed.
18. Which characters may be used as the second character of an identifier,but not
as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but
they may be used after the first character of an identifier.
19. What modifiers may be used with an inner class that is a member of an outer
class?
20. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character
set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents
characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit
patterns.
Wrapped classes are classes that allow primitive types to be accessed as objects.
22. What restrictions are placed on the location of a package statement within a
source code file?
A package statement must appear as the first line in a source code file (excluding
blank lines and comments).
23. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time
slicing, a task executes for a predefined slice of time and then reenters the pool
of ready tasks. The scheduler then determines which task should execute next,
based on priority and other factors.
25. What are order of precedence and associativity, and how are they used?
Share This
Session Facade is a design pattern to access the Entity bean through local
interface than accessing directly. It increases the performance over the network.
In this case we call session bean which on turn call entity bean.
EJB technology is the core of J2EE. It enables developers to write reusable and
portable server-side business logic for the J2EE platform.
EJB is a specification for J2EE server, not a product; Java beans may be a
graphical component in IDE.
Entity Bean is a Java class which implements an Enterprise Bean interface and
provides the implementation of the business methods. There are two types:
Container Managed Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two
types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t
maintain any conversational state with clients between method invocations.
Stateful bean maintains state between invocations.
Retrieve Home Object reference from Naming Service via JNDI. Return Home
Object reference to the client. Create me a new EJB Object through Home Object
interface. Create EJB Object from the Ejb Object. Return EJB Object reference to
the client. Invoke business method using EJB Object reference. Delegate request
to Bean (Enterprise Bean).
11. Is it possible to share an HttpSession between a JSP and EJB? What happens
when I change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects
in session are serializable.This has to be consider as passed-by-value, that means
that it?s read-only in the EJB. If anything is altered from inside the EJB, it won?t
be reflected back to the HttpSession of the Servlet Container.The pass-by-
reference can be used between EJBs Remote Interfaces, as they are remote
references. While it is possible to pass an HttpSession as a parameter to an EJB
object, it is considered to be bad practice in terms of object-oriented design. This
is because you are creating an unnecessary coupling between back-end objects
(EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction
for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries
with it a bunch of http semantics), create a class that acts as a value object (or
structure) that holds all the data you need to pass back and forth between front-
end/back-end. Consider the case where your EJB needs to support a non HTTP-
based client. This higher level of abstraction will be flexible enough to support it.
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 refering 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).
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 Mananged. In Container Managed Entity Bean - Whenever the instance
of the bean is created the container automatically retrieves the data from the
DB/Persistance 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, retrive values, assign them to the objects in the ejbLoad()
which will be called by the container when it instatiates a bean object. Similarly in
the ejbStore() the container saves the object values back the the persistance
storage. ejbLoad and ejbStore are callback methods and can be only invoked by
the container. Apart from this, when you use Entity beans you dont need to worry
about database transaction handling, database connection pooling etc. which are
taken care by the ejb container.
EEJB was originally designed around remote invocation using the Java Remote
Method Invocation (RMI) mechanism, and later extended to support to standard
CORBA transport for these calls using RMI/IIOP. This design allowed for
maximum flexibility in developing applications without consideration for the
deployment scenario, and was a strong feature in support of a goal of component
reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their
EJB calls are between beans in a single container. With this feedback in mind, the
EJB 2.0 expert group has created a local interface mechanism. The local interface
may be defined for a bean during development, to allow streamlined calls to the
bean if a caller is in the same container. This does not involve the overhead
involved with RMI like marshalling etc. This facility will thus improve the
performance of applications in which co-location is planned. Local interfaces also
provide the foundation for container-managed relationships among entity beans
with container-managed persistence.
18. What are the special design care that must be taken when you work with local
interfaces?
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.
20. What is the difference between Message Driven Beans and Stateless Session
beans?
22. 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.
Technically yes, spec. compliant NO! - The enterprise bean must not attempt to
query a class to obtain information about the declared members that are not
otherwise accessible to the enterprise bean because of the security rules of the
Java language.
25. Is it legal to have static initializer blocks in EJB?
Although technically it is legal, static initializer blocks are used to execute some
piece of code before executing any constructor or method while instantiating a
class. Static initializer blocks are also typically used to initialize static fields -
which may be illegal in EJB if they are read/write - In EJB this can be achieved by
including the code in either the ejbCreate(), setSessionContext() or
setEntityContext() methods.
Stopping the execution of a method inside a Session Bean is not possible without
writing code inside the Session Bean. This is because you are not allowed to
access Threads inside an EJB.
There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec
says that the deployer must specify a value for the transaction attribute for those
methods having container managed transaction. In WebLogic, the default
transaction attribute for EJB is SUPPORTS.
28. 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)
29. Is there any default cache management system with Entity beans ?
An Entity Bean represents persistent data that is stored outside of the EJB
Container/Server. The ejbFindByPrimaryKey is a method used to locate and load
an Entity Bean into the container, similar to a SELECT statement in SQL. By
making this method mandatory, the client programmer can be assured that if
they have the primary key of the Entity Bean, then they can retrieve the bean
without having to create a new bean each time - which would mean creating
duplications of persistent data and break the integrity of EJB.
31. Why do we have a remove method in both EJBHome and EJBObject?
With the EJBHome version of the remove, you are able to delete an entity bean
without first instantiating it (you can provide a PrimaryKey object as a parameter
to the remove method). The home version only works for entity beans. On the
other hand, the Remote interface version works on an entity bean that you have
already instantiated. In addition, the remote version also works on session beans
(stateless and stateful) to inform the container of your loss of interest in this
bean.
32. 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.
Yes you can overload methods should synchronization primitives be used on bean
methods? - No. The EJB specification specifically states that the enterprise bean is
not allowed to use thread primitives. The container is responsible for managing
concurrent access to beans at runtime.
37. Are we allowed to change the transaction isolation property in middle of a
transaction?
No. You cannot change the transaction isolation level in the middle of transaction.
38. 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.
39. 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.
40. 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,
41. 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.
42. 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 caching 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.
Ans. If we dont want the constructor to be visible to the extend classes then we
can declare a constructor to be private and also if we want a class to made as a
singleton class then we have to declare it has private
Ans: If you want to redirect your page which is residing on a different application
then you’ll be using response.sendRedirect(), here the request will be forwarded
to another application i,e your request will be redirected to another resoure on
different application/server
response.sendRedirect(”http://www.somesite.com”);
If you want to forward your request to another page on the same application then
you’ll be using the requestdispatcher.
RequestDispatcher rd = ct.getRequestDispatcher(”/servlet/AccountServlet”);
rd.forward(req, res);
3. Design Patterns?
4.What happens when any request comes from a client (Whole scenario)?
Ans: using the equals() Method we can compare the two objects
These are two quite different pieces of software.There are few Web servers in
common use: Apache takes the lion’s share, while Microsoft Internet Information
Server (IIS) and iPlanet Web Server are among the others. Application servers
jumped into the limelight only about two years ago and there is a proliferation of
products from companies such as BEA, iPlanet, Oracle, SilverStream, HP
(Bluestone), and IBM.
In general, an application server prepares material for the Web server — for
example, gathering data from databases, applying business rules, processing
security clearances, or storing the state of a user’s session. In some respects the
term application server is misleading since the functionality isn’t limited to
applications. Its role is more as an aggregator and manager for data and
processes used by anything running on a Web server.
Popularity: 2% [?]
Share This
Private constructor is used if you do not want other classes to instantiate the
object. The instantiation is done by a public static method within the same class.
1. Used in the singleton pattern. (Refer Q45 in Java section).
2. Used in the factory method pattern (Refer Q46 in Java section).
3. Used in utility classes e.g. StringUtils etc.
Why there are some interfaces with no defined methods (i.e. marker
interfaces) in Java?
The interfaces with no defined methods act like markers. They just tell the
compiler that the objects of the classes implementing the interfaces with no
defined methods need to be treated differently. Example Serializable, Cloneable
etc
try {
if (choice)
{
while (true) ;
} else
{
System.exit(1);
}
} finally
{code.to.cleanup();
}
Popularity: 2% [?]
Share This
Let’s say I need to spawn multiple threads to do the work, and continue to the
next step only after all of them complete. I will need to tell the main thread to
wait. The key point is to use Thread.join() method. For example,
package foo;
import java.util.Vector;
Popularity: 2% [?]
1. What are the implicit objects? - Implicit objects are objects that are
created by the web container and contain information related to a
particular request, page, or application. They are: request, response,
pageContext, session, application, out, config, page, exception.
2. Is JSP technology extensible? - Yes. JSP technology is extensible
through the development of custom actions, or tags, which are
encapsulated in tag libraries.
3. How can I implement a thread-safe JSP page? What are the
advantages and Disadvantages of using it? - You can make your JSPs
thread-safe by having them implement the SingleThreadModel interface.
This is done by adding the directive <%@ page isThreadSafe="false" %>
within your JSP page. With this, instead of a single instance of the servlet
generated for your JSP page loaded in memory, you will have N instances
of the servlet loaded and initialized, with the service method of each
instance effectively synchronized. You can typically control the number of
instances (N) that are instantiated for all servlets implementing
SingleThreadModel through the admin screen for your JSP engine. More
importantly, avoid using the tag for variables. If you do use this tag, then
you should set isThreadSafe to true, as mentioned above. Otherwise, all
requests to that page will access those variables, causing a nasty race
condition. SingleThreadModel is not recommended for normal use. There
are many pitfalls, including the example above of not being able to use <
%! %>. You should try really hard to make them thread-safe the old
fashioned way: by making them thread-safe
4. How does JSP handle run-time exceptions? - You can use the
errorPage attribute of the page directive to have uncaught run-time
exceptions automatically forwarded to an error processing page. For
example: <%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is
encountered during request processing. Within error.jsp, if you indicate
that it is an error-processing page, via the directive: <%@ page
isErrorPage="true" %> Throwable object describing the exception may be
accessed within the error page via the exception implicit object. Note: You
must always use a relative URL as the value for the errorPage attribute.
5. How do I prevent the output of my JSP or Servlet pages from being
cached by the browser? - You will need to set the appropriate HTTP
header attributes to prevent the dynamic content output by the JSP page
from being cached by the browser. Just execute the following scriptlet at
the beginning of your JSP pages to prevent them from being cached at the
browser. You need both the statements to take care of some of the older
browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy
server
%>
6. How do I use comments within a JSP page? - You can use “JSP-style”
comments to selectively block out code while debugging or simply to
comment your scriptlets. JSP comments are not visible at the client. For
example:
7. <%-- the scriptlet is now commented out
8. <%
9. out.println("Hello World");
10. %>
11. --%>
You can also use HTML-style comments anywhere within your JSP page.
These comments are visible at the client. For example:
Of course, you can also use comments supported by your JSP scripting
language within your scriptlets. For example, assuming Java is the
scripting language, you can have:
<%
//some comment
/**
yet another comment
**/
%>
12. Response has already been commited error. What does it mean? -
This error show only when you try to redirect a page after you already
have written something in your page. This happens because HTTP
specification force the header to be set up before the lay out of the page
can be shown (to make sure of how it should be displayed, content-
type=”text/html” or “text/xml” or “plain-text” or “image/jpg”, etc.) When
you try to send a redirect status (Number is line_status_402), your HTTP
server cannot send it right now if it hasn’t finished to set up the header. If
not starter to set up the header, there are no problems, but if it ’s already
begin to set up the header, then your HTTP server expects these headers
to be finished setting up and it cannot be the case if the stream of the
page is not over… In this last case it’s like you have a file started with
<HTML Tag><Some Headers><Body>some output (like testing your
variables.) Before you indicate that the file is over (and before the size of
the page can be setted up in the header), you try to send a redirect
status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
13. How do I use a scriptlet to initialize a newly instantiated bean? - A
jsp:useBean action may optionally have a body. If the body is specified, its
contents will be automatically invoked when the specified bean is
instantiated. Typically, the body will contain scriptlets or jsp:setProperty
tags to initialize the newly instantiated bean, although you are not
restricted to using those alone.
The following example shows the “today” property of the Foo bean
initialized to the current date when it is instantiated. Note that here, we
make use of a JSP expression within the jsp:setProperty action.
14. <jsp:useBean id="foo" class="com.Bar.Foo" >
15. <jsp:setProperty name="foo" property="today"
16. value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date()) %>"/ >
17. <%-- scriptlets calling bean setter methods go here --%>
18. </jsp:useBean >
19. How can I enable session tracking for JSP pages if the browser has
disabled cookies? - We know that session tracking uses cookies by
default to associate a session identifier with a unique user. If the browser
does not support cookies, or if cookies are disabled, you can still enable
session tracking using URL rewriting. URL rewriting essentially includes the
session ID within the link itself as a name/value pair. However, for this to
be effective, you need to append the session ID for each and every link
that is part of your servlet response. Adding the session ID to a link is
greatly simplified by means of of a couple of methods:
response.encodeURL() associates a session ID with a given URL, and if
you are using redirection, response.encodeRedirectURL() can be used by
giving the redirected URL as input. Both encodeURL() and
encodeRedirectedURL() first determine whether cookies are supported by
the browser; if so, the input URL is returned unchanged since the session
ID will be persisted as a cookie. Consider the following example, in which
two JSP files, say hello1.jsp and hello2.jsp, interact with each other.
Basically, we create a new session within hello1.jsp and place an object
within this session. The user can then traverse to hello2.jsp by clicking on
the link present within the page.Within hello2.jsp, we simply extract the
object that was earlier placed in the session and display its contents.
Notice that we invoke the encodeURL() within hello1.jsp on the link used
to invoke hello2.jsp; if cookies are disabled, the session ID is
automatically appended to the URL, allowing hello2.jsp to still retrieve the
session object. Try this example first with cookies enabled. Then disable
cookie support, restart the brower, and try again. Each time you should
see the maintenance of the session across pages. Do note that to get this
example to work with cookies disabled at the browser, your JSP engine
has to support URL rewriting.
20. hello1.jsp
21. <%@ page session="true" %>
22. <%
23. Integer num = new Integer(100);
24. session.putValue("num",num);
25. String url =response.encodeURL("hello2.jsp");
26. %>
27. <a href='<%=url%>'>hello2.jsp</a>
28. hello2.jsp
29. <%@ page session="true" %>
30. <%
31. Integer i= (Integer )session.getValue("num");
32. out.println("Num value in session is "+i.intValue());
33. How can I declare methods within my JSP page? - You can declare
methods for use within your JSP page as declarations. The methods can
then be invoked within any other methods you declare, or within JSP
scriptlets and expressions. Do note that you do not have direct access to
any of the JSP implicit objects like request, response, session and so forth
from within JSP methods. However, you should be able to pass any of the
implicit JSP variables as parameters to the methods you declare. For
example:
34. <%!
35. public String whereFrom(HttpServletRequest req) {
36. HttpSession ses = req.getSession();
37. ...
38. return req.getRemoteHost();
39. }
40. %>
41. <%
42. out.print("Hi there, I see that you are coming in from ");
43. %>
44. <%= whereFrom(request) %>
45. Another Example
46. file1.jsp:
47. <%@page contentType="text/html"%>
48. <%!
49. public void test(JspWriter writer) throws IOException{
50. writer.println("Hello!");
51. }
52. %>
53. file2.jsp
54. <%@include file="file1.jsp"%>
55. <html>
56. <body>
57. <%test(out);% >
58. </body>
59. </html>
60. Is there a way I can set the inactivity lease period on a per-session basis?
- Typically, a default inactivity lease period for all sessions is set within
your JSP engine admin screen or associated properties file. However, if
your JSP engine supports the Servlet 2.1 API, you can manage the
inactivity lease period on a per-session basis. This is done by invoking the
HttpSession.setMaxInactiveInterval() method, right after the session has
been created. For example:
61. <%
62. session.setMaxInactiveInterval(300);
63. %>
would reset the inactivity period for this session to 5 minutes. The
inactivity interval is set in seconds.
64. How can I set a cookie and delete a cookie from within a JSP page?
- A cookie, mycookie, can be deleted using the following scriptlet:
65. <%
66. //creating a cookie
67. Cookie mycookie = new Cookie("aName","aValue");
68. response.addCookie(mycookie);
69. //delete a cookie
70. Cookie killMyCookie = new Cookie("mycookie", null);
71. killMyCookie.setMaxAge(0);
72. killMyCookie.setPath("/");
73. response.addCookie(killMyCookie);
74. %>
75. How does a servlet communicate with a JSP page? - The following
code snippet shows how a servlet instantiates a bean and initializes it with
FORM data posted by a browser. The bean is then placed into the request,
and the call is then forwarded to the JSP page, Bean1.jsp, by means of a
request dispatcher for downstream processing.
76. public void doPost (HttpServletRequest request, HttpServletResponse
response) {
77. try {
78. govi.FormBean f = new govi.FormBean();
79. String id = request.getParameter("id");
80. f.setName(request.getParameter("name"));
81. f.setAddr(request.getParameter("addr"));
82. f.setAge(request.getParameter("age"));
83. //use the id to compute
84. //additional bean properties like info
85. //maybe perform a db query, etc.
86. // . . .
87. f.setPersonalizationInfo(info);
88. request.setAttribute("fBean",f);
89. getServletConfig().getServletContext().getRequestDispatcher
90. ("/jsp/Bean1.jsp").forward(request, response);
91. } catch (Exception ex) {
92. . . .
93. }
94. }
The JSP page Bean1.jsp can then process fBean, after first extracting it
from the default request scope via the useBean action.
96. How can I prevent the word "null" from appearing in my HTML
input text fields when I populate them with a resultset that has
null values? - You could make a simple wrapper function, like
97. <%!
98. String blanknull(String s) {
99. return (s == null) ? "" : s;
100. }
101. %>
102. then use it inside your JSP form, like
103. <input type="text" name="shoesize" value="<
%=blanknull(shoesize)% >" >
104. How can I get to print the stacktrace for an exception
occuring within my JSP page? - By printing out the exception’s stack
trace, you can usually diagonse a problem better when debugging JSP
pages. By looking at a stack trace, a programmer should be able to
discern which method threw the exception and which method called that
method. However, you cannot print the stacktrace using the JSP out
implicit variable, which is of type JspWriter. You will have to use a
PrintWriter object instead. The following snippet demonstrates how you
can print a stacktrace from within a JSP error page:
105. <%@ page isErrorPage="true" %>
106. <%
107. out.println(" ");
108. PrintWriter pw = response.getWriter();
109. exception.printStackTrace(pw);
110. out.println(" ");
111. %>
112. How do you pass an InitParameter to a JSP? - The JspPage
interface defines the jspInit() and jspDestroy() method which the page
writer can use in their pages and are invoked in much the same manner as
the init() and destory() methods of a servlet. The example page below
enumerates through all the parameters and prints them to the console.
113. <%@ page import="java.util.*" %>
114. <%!
115. ServletConfig cfg =null;
116. public void jspInit(){
117. ServletConfig cfg=getServletConfig();
118. for (Enumeration e=cfg.getInitParameterNames();
e.hasMoreElements();) {
119. String name=(String)e.nextElement();
120. String value = cfg.getInitParameter(name);
121. System.out.println(name+"="+value);
122. }
123. }
124. %>
125. How can my JSP page communicate with an EJB Session
Bean? - The following is a code snippet that demonstrates how a JSP page
can interact with an EJB session bean:
126. <%@ page import="javax.naming.*,
javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
127. <%!
128. //declare a "global" reference to an instance of the home
interface of the session bean
129. AccountHome accHome=null;
130. public void jspInit() {
131. //obtain an instance of the home interface
132. InitialContext cntxt = new InitialContext( );
133. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
134. accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
135. }
136. %>
137. <%
138. //instantiate the session bean
139. Account acct = accHome.create();
140. //invoke the remote methods
141. acct.doWhatever(...);
142. // etc etc...
143. %>
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/>
Question: What is the difference between <jsp:include page = ... > and
<%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The
differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another
jsp. It is executed ( the included page is executed and the generated html
content is included in the content of calling jsp) each time the client page is
accessed by the client. This approach is useful to for modularizing the web
application. If the included file changed then the new content will be included in
the output.
<%@ include file = ... >: In this case the content of the included file is
textually embedded in the page that have <%@ include file=".."> directive. In
this case in the included file changes, the changed content will not included in the
output. This approach is used when the code from one jsp file required to include
in multiple jsp files.
Question: What is the difference between <jsp:forward page = ... > and
response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the
client request information from one JSP file to another file. The target file can be
an HTML file, another JSP file, or a servlet, as long as it is in the same application
context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and
browser creates a new request to go the redirected page. The
response.sendRedirect kills the session variables.
<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%
%>
</BODY>
</HTML>
Suppose you access this JSP file, Find out your answer.
a) A blank page will be displayed.
b) A page with the text Welcome is displayed
c) An exception will be thrown because the implicit out object is not used
d) An exception will be thrown because PrintWriter can be used in servlets only
Question: What are all the different scope values for the <jsp:useBean> tag?
Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Here
are the scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p><%=getCount()%></p>
</body>
</html>
The Context Parameters page lets you manage parameters that are accessed
through the ServletContext.getInitParameterNames and
ServletContext.getInitParameter methods.
Question: What you can stop the browser to cash your page?
Answer: Instead of deleting a cache, you can force the browser not to catch the
page.
<%
response.setHeader("pragma","no-cache");//HTTP 1.1
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.addDateHeader("Expires", -1);
response.setDateHeader("max-age", 0);
//response.setIntHeader ("Expires", -1); //prevents caching at the proxy server
response.addHeader("cache-Control", "private");
%>
put the above code in your page.
Question: What you will handle the runtime exception in your jsp page?
Answer: The errorPage attribute of the page directive can be used to catch run-
time exceptions automatically and then forwarded to an error processing page.
For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught
exception is encountered during request processing. Within "customerror.jsp",
you must indicate that it is an error-processing page, via the directive: <%@
page isErrorPage="true" %>.
21) How do you share session objects between servlets and JSP?
in the jsp page this is how you get the session value:
<%
session.getValue("varible");
%>
A servlet is a way of extending your web server with a Java program to perform
tasks previously dealt with by CGI scripts or proprietary server extension
frameworks.
23) Is there any method to unload a servlet from Web Server memory
without restarting the server?
Any amount of data can be stored there because the session is kept
on the server side.
26) What is the difference between the doGet and doPost methods?
Gack! No no no no no...
30) How can I determine the name and version number of the servlet or
JSP engine that I am using?
String thisServer=
getServletConfig().getServletContext().getServerInfo();
If you are using JSP, you can use this expression:
<%= application.getServerInfo() %>
2) How do I support both GET and POST protocol from the same Servlet?
The easy way is, just support POST, then have your doGet method
call your doPost method:
(Note that the server will also allocate a new instance if you
register the servlet with a new name and, e.g., new init
parameters.)
When the user clicks the "Upload" button, the client browser
locates the local file and sends it using HTTP POST, encoded using
the MIME-type multipart/form-data. When it reaches your servlet,
your servlet must process the POST data in order to extract the
encoded file. You can learn all about this format in RFC 1867.
Unfortunately, there is no method in the Servlet API to do this.
Fortunately, there are a number of libraries available that do. Some
of these assume that you will be writing the file to disk; others
return the data as an InputStream.
JSPSmart has a free set of JSP for doing file upload and
download.
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}
}
The JSP page Bean1.jsp can then process fBean, after first
extracting it from the default request scope via the useBean action.
<jsp:useBean id="fBean" class="govi.FormBean"
scope="request"/>
<jsp:getProperty name="fBean" property="name" />
<jsp:getProperty name="fBean" property="addr" />
<jsp:getProperty name="fBean" property="age" />
use a RequestDispatcher
send a redirect
- Alex ]
The code below shows how this named servlet can be accessed in
the service method of another servlet
14) Why use JSP when we can do the same thing with servlets?
While JSP may be great for serving up dynamic Web content and
separating content from presentation, some may still wonder why
servlets should be cast aside for JSP. The utility of servlets is not in
question. They are excellent for server-side processing, and, with
their significant installed base, are here to stay. In fact,
architecturally speaking, you can view JSP as a high-level
abstraction of servlets that is implemented as an extension of the
Servlet 2.1 API. Still, you shouldn't use servlets indiscriminately;
they may not be appropriate for everyone. For instance, while page
designers can easily write a JSP page using conventional HTML or
XML tools, servlets are more suited for back-end developers
because they are often written using an IDE -- a process that
generally requires a higher level of programming expertise.
When deploying servlets, even developers have to be careful and
ensure that there is no tight coupling between presentation and
content. You can usually do this by adding a third-party HTML
wrapper package like htmlKona to the mix. But even this approach,
though providing some flexibility with simple screen changes, still
does not shield you from a change in the presentation format itself.
For example, if your presentation changed from HTML to DHTML,
you would still need to ensure that wrapper packages were
compliant with the new format. In a worst-case scenario, if a
wrapper package is not available, you may end up hardcoding the
presentation within the dynamic content. So, what is the solution?
One approach would be to use both JSP and servlet technologies
for building application systems.
15) How do I send information and data back and forth between applet
and servlet using the HTTP protocol?
16) Can I get the path of the current servlet where it lives on the file
system (not its URL)?
Try using:
request.getRealPath(request.getServletPath())
out.println(request.getRealPath(request.getServletPath()));
17) How can I daisy chain servlets together such that the output of one
servlet serves as the input to the next?
There are two common methods for chaining the output of one
servlet to another servlet :
After that you can format your output with the data.
All the dbms provide the facility of locks whenever the data is being
modified. There can be two scenarios:
1. Multiple database updates on different rows, if you are using
servlets the servlets will open multiple connections for different users. In
this case there is no need to do additional programming.
2. If database updates are on the same row then the rows are locked
automatically by the dbms, hence we have to send requests to the dbms
repeatatively until the lock is released by dbms.
GenericServlet is for servlets that might not use HTTP, like for
instance FTP servlets. Of course, it turns out that there's no such
thing as FTP servlets, but they were trying to plan for future growth
when they designed the spec. Maybe some day there will be
another subclass, but for now, always use HttpServlet.
31) How can I get the absolute URL of a servlet/JSP page at runtime ?
You can get all the necessary information to determine the URL
from the request object. To reconstruct the absolute URL from the
scheme, server name, port, URI and query string you can use the
URL class from java.net. The following code fragment will
determine your page's absolute URL:
34) How do servlets differ from RMI? What are the advantages and
disadvantages of each technology?
36) How can I design my servlet/JSP so that query results get displayed
on several pages, like the results of a search engine? Each page should
display, say, 10 records each and when the next link is clicked, I should
see the next/previous 10 records and so on.
Use a Java Bean to store the entire result of the search that you have
found. The servlet will then set a pointer to the first line to be displayed in
the page and the number of lines to display, and force a display of the
page. The Action in the form would point back to the servlet in the JSP
page which would determine whether a next or previous button has been
pressed and reset the pointer to previous pointer + number of lines and
redisplay the page. The JSP page would have a scriplet to display data
from the Java Bean from the start pointer set to the maximum number of
lines with buttons to allow previous or next pages to be selected. These
buttons would be displayed based on the page number (i.e. if first then
don't display previous button).
38) How can I pass data retrieved from a database by a servlet to a JSP
page?
In general, look at each frame as a unique document capable of sending its own
requests and receiving its own responses. You can create a top servlet (say,
FrameServlet) that upon invocation creates the frame layout you desire and sets
the SRC parameters for the frame tags to be another servlet, a static page or any
other legal value for SRC.
out.println("<html>");
out.println("<head>Your Title</head>");
// definingthe three rows of Frames for the main
page
// top : frm_1
// middle : frm_2
// bottom : frm_3
out.println("<frameset rows=12%,70%,*
cols=*>");
out.println("<frame
src=/https/www.scribd.com/servlets/MenuServlet
name=frm_1>");
out.println("<frame src=/https/www.scribd.com/servlets/DummyServlet?
mode=full name=frm_2>");
out.println("<frame src=/https/www.scribd.com/servlets/DummyServlet?
mode=small name=frm_3>");
out.println("</frameset>");
out.println("<body>");
out.println("</body></html>");
out.close();
-------------------------- END
------------------------------------------
41) How do I handle FORMs with multiple form elements (e.g. radio
buttons) using the same name?
For radio buttons, the HTML spec assumes that a given group of
buttons will have the same NAME and different VALUEs; the
browser makes sure that only one button per group name will be
selected (at most). So you can just call
request.getParameter("groupname").
For lists using the <select multiple> FORM tag, multiple values can
be returned for the same parameter name. When that can happen,
use request.getParameterValues("param") which returns a String[]
you can iterate through.
It's bad form (so to speak), but you can also duplicate other
element types, like
Name 1: <input type="text" name="name"
value="Dick">
Almost anybody who has ever written a servlet can identify with
this one. We all know it's bad for to embed HTML code in our java
source; it's lame to have to recompile and re-deploy every time
you want an HTML element to look a bit different. But what are our
choices here? There are two basic options;
1. Use JSP: Java Server Pages allows you to embed Java code or
the results of a servlet into your HTML. You could, for instance,
define a servlet that gives a stock quote, then use the <servlet>
tag in a JSP page to embed the output. But then, this brings up the
same problem; without discipline, your content/presentation and
program logic are again meshed. I think the ideal here is to
completely separate the two.
Use SSI!
Remember SSI? It hasn't gotten much attention in recent years
because of embeddable scripting languages like ASP and JSP, but it
still remains a viable option. To leverage it in the servlet world, I
believe the best way is to use an API called SSI for Java from
Areane. This API will let you emulate SSI commands from a
templating system, and much more. It will let you execute any
command on any system, including executing java classes! It also
comes with several utility classes for creating stateful HTML form
elements, tables for use with iteration, and much more. It's also
open source, so it's free and you can tweak it to your heart's
content! You can read the SSI for Java documentation for detailed
info, but the following is an example of its use.
Here's the servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.areane.www.ssi.*;
Now, just create a template file, pass the servlet the template file
name, and have at it!
43) For an HTML FORM with multiple SUBMIT buttons, how can a servlet
ond differently for each button?
The servlet will respond differently for each button based on the
html that you have placed in the HTML page. Let's explain.
For a submit button the HTML looks like <input type=submit
name="Left" value="left">. A servlet could extract the value of this
submit by using the getParameter("Left") from the HttpRequest
object. It follows then that if you have HTML within a FORM that
appears as:
<input type=submit name="Direction" value="left"><br>
<input type=submit name="Direction" value="right"><br>
<input type=submit name="Direction" value="up"><br>
<input type=submit name="Direction" value="down"><br>
Then the getParameter("Direction") from the HttpRequest
would extract the value pressed by the user, either "left", "right",
"up" or "down". A simple comparision in the servlet with the these
values could occur and processing based on the submit button
would be performed.
Similiarly,for submit buttons with different names on a page, each
of these values could be extracted using the getParameter() call
and acted on. However, in a situation where there are multiple
buttons, common practice would be to use one name and multiple
values to identify the button pressed.
45) How can I explicitly unload a servlet or call the destroy method?
In general, you can't. The Servlet API does not specify when a
servlet is unloaded or how the destroy method is called. Your
servlet engine (ie the implementation of the interfaces in the JSDK)
might provide a way to do this, probably through its administration
interface/tool (like Webshpere or JWS). Most servlet engines will
also destroy and reload your servlet if they see that the class file(s)
have been modified.
Because if you don't, then the config object will get lost. Just
extend HttpServlet, use init() (no parameters) and it'll all work ok.
From the Javadoc: init() - A convenience method which can be
overridden so that there's no need to call super.init(config).
49) Which is the most efficient (i.e. processing speed) way to create a
server application that accesses a database: A Servlet using JDBC; a JSP
page using a JavaBean to carry out the db access; or JSP combined with
a Servlet? Are these my only choices?
50) How can I change the port of my Java Web Server from 8080
to something else?
You can, however, send a "redirect", which tells the user's browser
to send another request, possibly to the same servlet with different
parameters. Search this FAQ on "redirect" to learn more.
52) What is FORM based login and how do I use it? Also, what servlet
containers support it?
Form based login is one of the four known web based login
mechanisms. For completeness I list all of them with a description
of their nature:
53) How do I capture a request and dispatch the exact request (with all
the parameters received) to another URL?
• If the next servlet url is in the same host, then you can use the
forward method.
Here is an example code about using forward:
RequestDispatcher rd = null;
String targetURL = "target_servlet_name";
ServletContext ctx = this.getServletContext();
rd = ctx.getRequestDispatcher(targetURL);
rd.forward(request, response);
54) How can the data within an HTML form be refreshed automatically
whenever there is a change in the database?
When you have a generated page, JSP has already made its work.
From this moment you have a page.
If you want automatic refreshing, then this should be acomplished
by the technology included in the generated page (JSP will tell only
what to include in the page).
56) How can I call a servlet from a JSP page? How can I pass variables
from the JSP that the servlet can access?
57) Can there be more than one instance of a servlet at one time ?
It is important to note that there can be more than one instance of
a given Servlet class in the servlet container. For example, this can
occur where there was more than one servlet definition that
utilized a specific servlet class with different initialization
parameters. This can also occur when a servlet implements the
SingleThreadModel interface and the container creates a pool of
servlet instances to use.
58) How can I measure the file downloading time using servlets?
Request Dispatching
HTTP Redirect
Servlet Chaining
When you use Tomcat standalone as your web server, you can
modify the web.xml in $TOMCAT_HOME/webapps/myApp/WEB-INF
to add a url-pattern:
<web-app>
<servlet>
<servlet-name>
myServlet
</servlet-name>
<servlet-class>
myServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
myServlet
</servlet-name>
<url-pattern>
/jsp-bin/*
</url-pattern>
</servlet-mapping>
</web-app>
This will let you use: http://webserver:8080/myApp/jsp-
bin/stuff.html instead of:
http://webserver:8080/myApp/servlet/myServlet/stuff.html But it
won't work on port 80 if you've integrated Tomcat with Apache.
Graeme Wallace provided this trick to remedy the situation. Add
the following to your tomcat-apache.conf (or to a static version of
it, since tomcat re-generates the conf file every time it starts):
RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher( "/servlet/Se
rvlet_B" );
dispatcher.forward( request, response );
The originally called servlet has passed the control to the current
servlet, and now current servlet is acting as controller to other
resourses.
The in-process Servlet containers are the containers which work inside the JVM of
Web server, these provides good performance but poor in scalibility.
The out-of-process containers are the containers which work in the JVM outside
the web server. poor in performance but better in scalibility
In the case of out-of-process containers, web server and container talks with
each other by using the some standard mechanism like IPC.
All servlet containers that implement the Servlet 2.2 API must provide for session
tracking through either the use of cookies or through URL rewriting. All Tomcat
servlet containers support session tracking.
69) How can I set a servlet to load on startup of the container, rather
than on the first request?
The Servlet 2.2 spec defines a load-on-startup element for just this
purpose. Put it in the <servlet> section of your web.xml
deployment descriptor. It is either empty (<load-on-startup/>) or
contains "a positive integer indicating the order in which the servlet
should be loaded. Lower integers are loaded before higher integers.
If no value is specified, or if the value specified is not a positive
integer, the container is free to load it at any time in the startup
sequence."
For example,
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>com.foo.servlets.Foo</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
Some servlet containers also have their own techniques for
configuring this; please submit feedback with information on these.
Yes. It would spawn a thread that opens a ServerSocket, then listens for
incoming connections and speaks the FTP protocol.
Give the submit image (or button) an onClick() handler. Have the
handler check if a flag is set and if not set the flag and submit the
form and then clear the form.
72) What are the main differences between Servlets and ISAPI?
The first difference is obviously that Servlets is the technology from
Sun Microsystems and ISAPI is from Microsoft.
ï‚· Java is the only choice for writing Servlets, VC++/MFC is used
to write ISAPI code
ï‚· Servlets works on most of the Web servers plus third party
containers can be integrated with other web servers to provide
servlets on them. ISAPI works on only ISAPI-compliant Web server
(for example, Microsoft Internet Information Server)
e.g.
<mime-mapping>
<extension>
zzz
</extension>
<mime-type>
text/plain
</mime-type>
</mime-mapping>
<servlet-mapping>
<url>
*.zzz
</url>
<servlet-name>
MyServlet
</servlet-name>
</servlet-mapping>
So, when a file for type zzz is requested, the servlet gets called.
74) What are the different cases for using sendRedirect() vs.
getRequestDispatcher()?
document.cookie = "cookieName=cookieValue";
alert(document.cookie);
76) How do I write to a log file using JSP under Tomcat? Can I make use
of the log() method for this?
Yes, you can use the Servlet API's log method in Tomcat from
within JSPs or servlets. These messages are stored in the server's
log directory in a file called servlet.log.
77) How can I use a servlet to print a file on a printer attached to the
client?
If the servlet engine does the time-out, following code should help
you:
yes you can do that by modifying the web.xml file. You will have to invoke the
org.apache.jasper.runtime.JspServlet for all the requests having extension
.html. You can do that by changing the Servlet mapping code:
<servlet-mapping>
<servlet-name>
jsp
</servlet-name>
<url>*.html</url>
</servlet-mapping>
<mime-mapping>
<extension>
html
</extension>
<mime-type>
text/html
</mime-type>
</mime-mapping>
83) When building web applications, what are some areas where
synchronization problems arrise?
In general, you will run into synchronization issues when you try to
access any shared resource. By shared resource, I mean anything
which might be used by more than one request.
85) How can you embed a JavaScript within servlets / JSP pages?
The key thing to remember is it won't run in the server. It will run
back on the client when the browser loads the generate HTML, with
the included JavaScript.
Make the POST from your servlet, not from the client
You'll have to pass the JSP's URI in to the servlet, and have the
servlet call sendRedirect to go back to the JSP. For example:
<FORM ACTION="/foo/myservlet">
<INPUT TYPE="HIDDEN" NAME="redirect"
VALUE="/foo/thisjsp.jsp">
Shoe size: <INPUT NAME="shoesize">
<INPUT TYPE="SUBMIT">
</FORM>
response.sendRedirect(request.getParameter("redirect"));
getInitParameter
getInitParameterNames
getServletContext
getServletName
90) I have a global variable in a servlet class. What will happen to this
global variable if two requests hit on the same time?
92) How can I pass data from a servlet running in one context (webapp)
to a servlet running in another context?
There are three ways I can think of off the top of my head:
93) How can I write an "error page" -- that is, a servlet or JSP to report
errors of other servlets?
Most of the Servlet containers reload the servlet only it detects the
code change in the Servlet, not in the referenced classes.
In Tomcat's server.xml deployment descriptor, if you have
mentioned
<Context path="/myApp"
docBase="D:/myApp/webDev"
crossContext="true"
debug="0"
reloadable="true"
trusted="false" >
</Context>
The reloadable = true makes the magic. Every time the Servlet
container detects that the Servlet code is changed, it will call the
destroy on the currently loaded Servlet and reload the new code.
But if the class that is referenced by the Servlet changes, then the
Servlet will not get loaded. You will have to change the timestamp
of the servlet or stop-start the server to have the new class in the
container memory.
<BODY>
<% String base = request.getContextPath(); %>
<IMG src="<%=base%>/img/pic.gif">
</BODY>
<BODY>
<IMG src="img/pic.gif">
</BODY>
98) How can I return a readily available (static) HTML page to the user
instead of generating it in the servlet?
To solve your problem, you can either send a "Redirect" back to the
client or use a RequestDispatcher and forward your request to
another page:
1. Redirect:
A redirection is made using the HttpServletResponse object:
2. if(condition) {
3. response.sendRedirect("page1.html");
4. } else {
5. response.sendRedirect("page2.html");
6. }
7. RequestDispatcher:
A request dispatcher can be obtained through the
ServletContext. It can be used to include another page or to
forward to it.
8. if(condition) {
9. this.getServletContext()
10.
.getRequestDispatcher("page1.html").forward();
11. } else {
12. this.getServletContext()
13.
.getRequestDispatcher("page2.html").forward();
14. }
Both solutions require, that the pages are available in you
document root. If they are located somewhere else on your
filesystem, you have to open the file manually and copy their
content to the output writer.
If your application server is set up in combination with a normal
web server like Apache, you should use solution (1), because the
the web server usually serves static files much faster than the
application server.
100) How can I share data between two different web applications?
Q: What is Struts?
A: The core of the Struts framework is a flexible control layer based on
standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML,
as well as various Jakarta Commons packages. Struts encourages application
architectures based on the Model 2 approach, a variation of the classic Model-
View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other
technologies to provide the Model and the View. For the Model, Struts can interact
with standard data access technologies, like JDBC and EJB, as well as most any
third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the
View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as
Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web
application needs to survive. Struts helps you create an extensible development
environment for your application, based on published standards and proven
design patterns.
Q: What is ActionServlet?
A: 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.
Q: How you will make available any Message Resources Definitions file to the
Struts Framework Environment?
A: T Message Resources Definitions file are simple .properties files and these
files contains the messages that can be used in the struts project. Message
Resources Definitions files can be added to the struts-config.xml file through
<message-resources /> tag.
Example:
Q: What is ActionForm?
A: 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/>
Although one may simply extract BLOB & CLOB data from the
database using the methods of the java.sql.CLOB and
java.sql.BLOB, one must upload the data as normal java datatypes.
The example below inserts a BLOB in the form of a byte[] and a
CLOB in the form of a String into the database
// Perform insert
int rowsAffected = stmnt.executeUpdate();
}
23) What is the difference between client and server database cursors?
What you see on the client side is the current row of the cursor which called a
Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and
remains on the server side.
24) Are prepared statements faster because they are compiled? if so,
where and when are they compiled?
JDBC 2.0, introduced with the 1.2 version of Java, added several
capabilities to JDBC. Instead of completely invalidating all the older
JDBC 1.x drivers, when you try to perform a 2.0 task with a 1.x
driver, an UnsupportedOperationException will be thrown. You need
to update your driver if you wish to use the new capabilities.
29) Can I reuse a Statement or must I create a new one for each query?
When using a JDBC compliant driver, you can use the same Statement for any
number of queries. However, some older drivers did not always "respect the
spec." Also note that a Statement SHOULD automatically close the current
ResultSet before executing a new query, so be sure you are done with it before
re-querying using the same Statement.
java.sql.Blob, since it does not extract any data from the database
until you explicitly ask it to. The Java platform 2 type Blob wraps a
database locator (which is essentially a pointer to byte). That
pointer is a rather large number (between 32 and 256 bits in size) -
but the effort to extract it from the database is insignificant next to
extracting the full blob content. For insertion into the database, you
should use a byte[] since data has not been uploaded to the
database yet. Thus, use the Blob class only for extraction.
Conclusion: use the java.sql.Blob class for extraction whenever
you can.
java.sql.Clob, since it does not extract any data from the database
until you explicitly ask it to. The Java platform 2 type Clob wraps a
database locator (which is essentially a pointer to char). That
pointer is a rather large number (between 32 and 256 bits in size) -
but the effort to extract it from the database is insignificant next to
extracting the full Clob content. For insertion into the database, you
should use a String since data need not been downloaded from the
database. Thus, use the Clob class only for extraction.
Conclusion: Unless you always intend to extract the full textual
data stored in the particular table cell, use the java.sql.Clob class
for extraction whenever you can.
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 ?
15) What does ResultSet actually contain? Is it the actual data of the
result or some links to databases? If it is the actual data then why can't
we access it after connection is closed?
The next version of the ANSI/ISO SQL standard defines some new
datatypes, commonly referred to as the SQL3 types. The primary
SQL3 types are:
STRUCT: This is the default mapping for any SQL structured type,
and is manifest by the java.sql.Struct type.
REF: Serves as a reference to SQL data within the database. Can
be passed as a parameter to a SQL statement. Mapped to the
java.sql.Ref type.
BLOB: Holds binary large objects. Mapped to the java.sql.Blob
type.
CLOB: Contains character large objects. Mapped to the
java.sql.Clob type.
ARRAY: Can store values of a specified type. Mapped to the
java.sql.Array type.
You can retrieve, store and update SQL3 types using the
corresponding getXXX(), setXXX(), and updateXXX() methods
defined in ResultSet interface
17) How can I manage special characters (for example: " _ '
% ) when I execute an INSERT query? If I don't filter the
quoting marks or the apostrophe, for example, the SQL
string will cause an error.
The characters "%" and "_" have special meaning in SQL LIKE
clauses (to match zero or more characters, or exactly one
character, respectively). In order to interpret them literally, they
can be preceded with a special escape character in strings, e.g. "\".
In order to specify the escape character used to quote these
characters, include the following syntax on the end of the query:
{escape 'escape-character'}
18) What is SQLJ and why would I want to use it instead of JDBC?
19) How do I insert an image file (or other raw data) into a database?
Since your application retrieves a pooled connection, you don't consume your
time to connect / disconnect from your data source.
31) What separates one tier from another in the context of n-tiered
architecture?
32) What areas should I focus on for the best performance in a JDBC
application?
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
a new transaction is implicitly started.
Yes, you can use the driver directly. Create an instance of the
driver and use the connect method from the Driver interface. Note
that there may actually be two instances created, due to the
expected standard behavior of drivers when the class is loaded.
Often the answer is given that the correct driver is not loaded. This
may be the case, but more typically, the JDBC database URL
passed is not properly constructed. When a Connection request is
issued, the DriverManager asks each loaded driver if it understands
the URL sent. If no driver responds that it understands the URL,
then the "No Suitable Driver" message is returned.
The general answer to this is yes. If that were not true, connection
pools, for example, would not be possible. As always, however, this
is completely dependent on the JDBC driver.
You can find out the theoretical maximum number of active Connections that your
driver can obtain via the DatabaseMetaData.getMaxConnections method.
DDL is an abbreviation for Data Definition Language. This portion of the SQL
standard is concerned with the creation, deletion and modification of database
objects like tables, indexes and views. The core verbs for DDL are CREATE, ALTER
and DROP. While most DBMS engines allow DDL to be used dynamically ( and
available to JDBC ), it is often not supported in transactions.
48) How can I get information about foreign keys used in a table?
50) What isolation level is used by the DBMS when inserting, updating
and selecting rows from a database?
The answer depends on both your code and the DBMS. If the program does not
explicitly set the isolation level, the DBMS default is used. You can determine the
default using DatabaseMetaData.getDefaultTransactionIsolation() and the level
for the current Connection with Connection.getTransactionIsolation(). If the
default is not appropriate for your transaction, change it with
Connection.setTransactionIsolation(int level).
Establishing a Connection
First, you need to establish a connection with the DBMS you want to use. Typically, a
JDBC™ application connects to a target data source using one of two mechanisms:
• DriverManager: This fully implemented class requires an application to load
a specific driver, using a hardcoded URL. As part of its initialization, the
DriverManager class attempts to load the driver classes referenced in the
jdbc.drivers system property. This allows you to customize the JDBC
Drivers used by your applications.
• DataSource: This interface is preferred over DriverManager because it
allows details about the underlying data source to be transparent to your
application. A DataSource object's properties are set so that it represents a
particular data source.
Establishing a connection involves two steps: Loading the driver, and making the
connection.
Loading the driver you want to use is very simple. It involves just one line of code in
your program. To use the Java DB driver, add the following line of code:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Your driver documentation provides the class name to use. In the example above,
EmbeddedDriver is one of the drivers for Java DB.
After you have loaded a driver, it can make a connection with a DBMS.
The second step in establishing a connection is to have the appropriate driver connect
to the DBMS.
The DriverManager class works with the Driver interface to manage the set of
drivers available to a JDBC client. When the client requests a connection and provides
a URL, the DriverManager is responsible for finding a driver that recognizes the
URL and for using it to connect to the corresponding data source. Connection URLs
have the following form:
jdbc:derby:<dbName>[propertyList]
The dbName portion of the URL identifies a specific database. A database can be in
one of many locations: in the current working directory, on the classpath, in a JAR
file, in a specific Java DB database home directory, or in an absolute location on your
file system.
If you are using a vendor-specific driver, such as Oracle, the documentation will tell
you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For
example, if the driver developer has registered the name OracleDriver as the
subprotocol, the first and second parts of the JDBC URL will be
jdbc.driver.OracleDriver . The driver documentation will also give you
guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies
information for identifying the data source.
In place of " myLogin " you insert the name you use to log in to the DBMS; in place
of " myPassword " you insert your password for the DBMS. So, if you log in to your
DBMS with a login name of " Fernanda " and a password of " J8, " just these two
lines of code will establish a connection:
If one of the drivers you loaded recognizes the JDBC URL supplied to the method
DriverManager.getConnection, that driver establishes a connection to the DBMS
specified in the JDBC URL. The DriverManager class, true to its name, manages all
of the details of establishing the connection for you behind the scenes. Unless you are
writing a driver, you probably won't use any of the methods in the interface Driver,
and the only DriverManager method you really need to know is
DriverManager.getConnection
You can configure a DataSource using a tool or manually. For example, Here is an
example of a DataSource lookup:
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource)
org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection();
DataSource implementations must provide getter and setter methods for each
property they support. These properties typically are initialized when the DataSource
object is deployed.
For normal use, you should obtain a commercial JDBC driver from a vendor such as
your database vendor or your database middleware vendor. The JDBC-ODBC Bridge
driver provided with JDBC is recommended only for development and testing, or
when no other alternative is available.