Wednesday, July 29, 2009

Enterprise JavaBeans FAQs

What is Enterprise JavaBeans?
Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object system similar to CORBA and Microsoft Transaction Server, but based on the Java platform.
EJB specifies how developers should build components that can be accessed remotely and how EJB vendors should support those components. EJB components, called enterprise beans, automatically handle transactions, persistence, and authorization security, so that the developer can focus on the business logic.

What's so special about Enterprise JavaBeans?
Enterprise JavaBeans simplifies the task of developing distributed objects systems. It's easier for developers to create transactional distributed object applications with EJB than with any other Java based component architecture. With Enterprise JavaBeans, transactions, security, and persistence can be handled automatically allowing developer to focus on the business logic.
Enterprise JavaBeans has been adopted by most distributed object vendors and is considered a standard for developing distributed object systems in Java. All EJB vendors must implement the same EJB specification which guarantees a consistent programming model across servers. In addition, because EJB is widely supported by many vendors, corporations do not have to worry about vendor lock-in; enterprise beans will run in any EJB compliant server.

What is a session bean?
A session bean is a type of enterprise bean; a type of EJB server-side component. Session bean components implement the javax.ejb.SessionBean interface and can be stateless or stateful. Stateless session beans are components that perform transient services; stateful session beans are components that are dedicated to one client and act as a server-side extension of that client.
Session beans can act as agents modeling workflow or provide access to special transient business services. As an agent, a stateful session bean might represent a customer's session at an online shopping site. As a transitive service, a stateless session bean might provide access to validate and process credit card orders.

Session beans do not normally represent persistent business concepts like Employee or Order. This is the domain of a different component type called an entity bean.

What is a CMP bean?
A CMP bean is an entity bean whose state is synchronized with the database automatically. In other words, the bean developer doesn't need to write any explicit database calls into the bean code; the container will automatically synchronize the persistent fields with the database as dictated by the deployer at deployment time.
When a CMP bean is deployed, the deployer uses the EJB tools provided by the vendor to map the persistent fields in the bean to the database. The persistence fields will be a subset of the instance fields, called container-managed fields, as identified by the bean developer in the deployment descriptor.

In the case of a relational database, for example, each persistent field will be associated with a column in a table. A bean may map all its fields to one table or, in the case of more sophisticated EJB servers, to several tables. CMP are not limited to relational database. CMP beans can be mapped to object databases, files, and other data stores including legacy systems.

What is a BMP bean?
A BMP bean is an entity bean that synchronizes its state with the database manually. In other words, the bean developer must code explicit database calls into the bean itself. BMP provides the bean developer with more flexibility in the how the bean reads and writes its data than a container-managed persistence (CMP) bean. CMP bean is limited to the mapping facilities provided by the EJB vendor, BMP beans are only limited by skill of the bean developer.
Are Enterprise JavaBeans and JavaBeans the same thing?
Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension of the other. They are both component models, based on Java, and created by Sun Microsystems, but their purpose and packages (base types and interfaces) are completely different.
How does a client application create a transaction object?
For a servlet or other clients to obtain a UserTransaction object, there must be a JTS-capable server to deliver the object.
Typically, the server provides the JNDI look-up name either directly or via a system or server property. For example, with the WebLogic server, you would use a code segment similar to the following:

...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction) c.lookup("javax.jts.UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...
With J2EE implementations, you obtain the UserTransaction object with a code segment similar to the following:
...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction) c.lookup("java:comp/UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...
JNDI remote look-up names and property names vary, of course, across servers/environment.
Why would a client application use JTA transactions?
One possible example would be a scenario in which a client needs to employ two (or more) session beans, where each session bean is deployed on a different EJB server and each bean performs operations against external resources (for example, a database) and/or is managing one or more entity beans. In this scenario, the client's logic could required an all-or-nothing guarantee for the operations performed by the session beans; hence, the session bean usage could be bundled together with a JTA UserTransaction object.
In the previous scenario, however, the client application developer should address the question of whether or not it would be better to encapsulate these operations in yet another session bean, and allow the session bean to handle the transactions via the EJB container. In general, lightweight clients are easier to maintain than heavyweight clients. Also, EJB environments are ideally suited for transaction management.

How does a session bean obtain a JTA UserTransaction object?
A session bean can obtain a UserTransaction object via the EJBContext using the getUserTransaction() method.
How does an enterprise bean that uses container-managed transactions obtain a JTA UserTransaction object?
It doesn't! By definition, container-managed transaction processing implies that the EJB container is responsible for transaction processing. The session bean has only limited control of transaction handling via the transaction attribute.
How do you configure a session bean for bean-managed transactions?
You must set transaction-type in the deployment descriptor.
How does an entity bean obtain a JTA UserTransaction object?
It doesn't. Entity beans do not employ JTA transactions; that is, entity beans always employ declarative, container-managed transaction demarcation.
Is it necessary for an entity bean to protect itself against concurrent access from multiple transactions?
No. One of the motivations for using a distributed component architecture such as Enterprise JavaBeans is to free the business logic programmer from the burdens that arise in multiprogramming scenarios.
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:

<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,foo.AccountHome,foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;

public void jspInit()
{
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>


<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>

Alternatively you can use a Java Bean to call EJB instead of writing the code in JSP.
How do enterprise beans access native libraries?
They can NOT access native library.
The enterprise bean must not attempt to load a native library. This function is reserved for the EJB Container. Allowing the enterprise bean to load native code would create a security hole.

How do I introspect a bean at run time to discover its type(s) and available methods?
Client applications or beans can access meta data about a bean from its EJBMetaData object. The EJBMetaData object is obtained from the bean's EJB home reference using the EJBHome.getEJBMetaData( ) method as shown below:
AccountHome acctHome = ... get a reference to the bean's EJB home.

EJBMetaData ejbMetaData = acctHome.getEJBMetaData( );

The EJBMetaData object implements the javax.ejb.EJBMetaData interface which defines methods for obtaining the class of the bean's remote interface, home interface, bean type (entity, stateful or stateless session), and the primary keys type (entity only). A reference to the bean's EJB home can also be obtained. Below is the interface definition of EJBMetaData.

package javax.ejb;

public interface EJBMetaData {
// Obtain the home interface of the enterprise Bean.
public EJBHome getEJBHome();
//Obtain the home interface of the enterprise Bean.
java.lang.Class getHomeInterfaceClass();
//Obtain the Class object for the enterprise Bean's home interface.
java.lang.Class getPrimaryKeyClass();
//Obtain the Class object for the enterprise Bean's primary key class.
java.lang.Class getRemoteInterfaceClass();
//Obtain the Class object for the enterprise Bean's remote interface.
boolean isSession();
//Test if the enterprise Bean's type is "session".
boolean isStatelessSession();
}

Once a client application has a reference to bean's remote and home interface classes, normal Java reflection can be used to introspect the methods avaiable to client. Below is an example:

Class remoteClass = ejbMetaData.getRemoteInterfaceClass();

java.lang.reflect.Method [] methods = remoteClass.getDeclaredMethods();

for(int i = 0; i methods.length; i++){
System.out.println(methods[i].getName());

}

There are no mechanisms a client can use to introspect on a the bean class itself. This makes sense since a bean, as a component, is represented by its remote and home interfaces. The bean class itself should not be visible to the client.
The EJBMetaData is designed to be used by IDEs and other builder tools that may need generic methods for obtaining information about a bean at runtime.

Does the EJB programming model support inheritance?
Inheritance is supported in EJB in a limited fashion. Enterprise beans are made up of several parts including: a remote interface; a home interface, a bean class (implementation); and a deployment descriptor.
The remote interface, which extends javax.ejb.EJBObject can be a subtype or a super-type of remote interfaces of other beans. This is also true of the home interface, which extends javax.ejb.EJBHome. The bean class, which implements either javax.ejb.EntityBean or javax.ejb.SessionBean can also be a subtype or super-type of the bean class used by another enterprise bean. Deployment descriptors are XML files, so there is no Object-Oriented (OO) inheritance in the deployment descriptor.

Because an enterprise bean is not one object -- its the composition of several parts -- traditional OO inheritance is not possible. The constituent Java parts (remote, home, bean class) of an enterprise bean may themselves subtype or serve as super-type, but the bean as a whole (the sum of its parts) doesn't support inheritance.

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.
What classes does a client application need to access EJB?
It is worthwhile to note that the client never directly interacts with the bean object but interacts with distributed object stubs or proxies that provide a network connection to the EJB container system. The mechanhism is as follows:
The client uses the JNDI context to get a remote reference (stub) to the home object ( the EJBHome).
It uses the home to get a remote reference (stub) to the EJBs remote object (the EJBObject)
It then invokes business methods on this remote object.
The client needs the remote interface, the home interface, the primary key (if it is an entity bean). In addition to these, the client would need the JNDI factory implementation, and the remote and home stubs. In some EJB servers the Factory and/or stubs can be dynamically loaded at run time. In other EJB servers they must be in the classpath of the client application.

What's an .ear file?
An .ear file is an "Enterprise Archive" file. The file has the same format as a regular .jar file (which is the same as ZIP). The .ear file contains everything necessary to deploy an enterprise application on an application server. It contains both the .war (Web Archive) file containing the web component of the application as well as the .jar file. In addition there are some deployment descriptor files in XML.
Is method overloading allowed in EJB?
Yes you can overload methods.
Can primary keys contain more than one field?
Yes, a primary key can have as many fields as the developer feels is necessary, just make sure that each field you specify as the primary key, you also specify a matching field in the bean class. A primary key is simply one or more attributes which uniquely identify a specific element in a database. Also, remember to account for all fields in the equals() and hashCode() methods.
What happens when two users access an Entity Bean concurrently?
EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be connected to one EJB object, but only one client thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the EJB object, no other client can access that bean instance until the method invocation is complete.
So, to answer your question, two users will never access an Entity Bean concurrently.

What's the reason for having two interfaces -- EJBHome for creating, finding & removing and EJBObject for implementing business methods. Why not have an single interface which supports both areas of functionality?
This design reflects the common "Factory" Design pattern. The EJBHome interface is the Factory that creates EJBObjects. EJBObject instances are the product of the factory. The reason for having two interfaces is because they are both responsible for different tasks. The EJBHome is responsible for creating and finding EJBObjects, whilst the EJBObject is responsible for the functionality of the EJB.
What are the differences between EJB 1.1 and EJB 2.0?
There are many differences, all of them should give different type of advantages among the previous 1.1 version.
New CMP Model. It is based on a new contract called the abstract persistence schema, that will allow to the container to handle the persistence automatically at runtime.
EJB Query Language. It is a sql-based language that will allow the new persistence schema to implement and execute finder methods.
Local interfaces. These are beans that can be used locally, that means by the same Java Virtual Machines, so they do not requires to be wrapped like remote beans, and arguments between those interfaces are passed directly.
ejbHome methods. Entity beans can declare ejbHome methods that perform operations related to the EJB component but that are not specific to a bean instance
Message Driven Beans (MDB). Is a completely new enterprise bean type, that is designed specifically to handle incoming JMS messages.
What are the additional features of EJB 2.1 over EJB 2.0
Compared to the 2.0 specifications, EJB 2.1 have focused the attention in trying to be more "web-services" oriented, and the addition of a Timer service.
The biggest addition in EJB 2.1 is the new support for the Web-Services technology. With this new specifications, in fact, developers can expose their Stateless Session and Message-Driven EJBs as Web Services based on SOAP. This will mean that any client that complies with SOAP 1.1 will be able to access to the exposed EJBs. The APIs that will allow this and that have been added, are JAXM and JAX-RPC.

Another addition is the Timer Service, that can be seen as a scheduling built right inside the EJB Container. With EJB 2.1, any Stateless Session or Entity Bean can register itself with the Timer Service, requesting a notification or when a given timeframe has elapsed, or at a specific point in time. From a developer point of view, the Timer Service uses a very simple programming model based on the implementation of the TimedObject interface.

From the enhancement side, the Query Language is definitely the topic where the improvements are definitely more visible. The ORDER BY clause has finally been added. This will improve performance on orederd queries, because this will be handled by the underneath database, and not through the code by sorting the resulting collection.

The WHERE clause has been improved with the addition of MOD, while the SELECT clause has been improved by adding aggregate functions, like COUNT, SUM, AVG, MIN and MAX.

Both RMI and EJB are distributed applications.In EJB we use Home interface which is not avaliable in RMI?
RMI is a lower level technology that allows java objects to be distributed across multiple JVMs. Essentially, RMI abstracts sockets and inter-JVM communications.
EJB, on the other hand, is a technology built atop of RMI but does so much more than allow java objects to be distributed. It is a framework that allows you to build enterprise applications by (among other things) abstracting transactions, database access and concurent processing.

The home interface is EJB's way of creating an object. Home interfaces act as factories to create session beans and entity beans. These factories are provided by the application container and take care of many low level details. Since RMI is a lower level technology, it does not offer the home interface. You would have to create it yourself.

How many EJB Objects are created for a Bean
There is absolutely no relationship between the amount of EJBObjects you create on the client side and the amount of bean instances that actually exist on the server side.
When a client invokes a method on the stub, the container will look into the bean pool and see if there are any available bean instances that can satisfy that request. It will create more instances if all instances are currently being used by other clients.

You can control the size of the pool thru the deployment descriptor.

What is session facade?
Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design.
Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction.

As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability.

The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest.

What is the default time for transaction manager? And how to set maximum time(timeout) for transaction?.
The default time depends on your app server. It is usually around 30 seconds. If you are using bean-managed transactions, you can set it like this:

// One of the methods from the SessionBean interface
public void setSessionContext(SessionContext context) throws EJBException
{
sessionContext = context;
}

// Then, when starting a new transaction

UserTransaction userTransaction = sessionContext.getUserTransaction();
userTransaction.setTransactionTimeout(60);
userTransaction.begin();
// do stuff
userTransaction.commit();


If you are using container-managed transactions, this value is set in a app server specific way. Check your app server's deployment descriptor DTD.
What is the diffrence between ejbCreate() and ejbPostCreate() in EntityBean?
ejbCreate() is called before the state of the bean is written to the persistence storage (database). After this method is completed, a new record (based on the persistence fields) is created and written. If the Entity EJB is BMP, then this method must contain the code for writing the new record to the persistence storage.
ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an EJB object, so when the bean is available. In an CMP Entity EJB, this method is normally used to manage the beans' container-managed relationship fields.

Can a primitive data type be specified as a method parameter, in the deployment descriptor?
There are no specific restriction for using Java primitive types in the tag in the Deployment descriptor.
If you are using classes, use fully qualified class name such as java.lang.String and not just String.



java.lang.String
int
...


How can i get user name from inside inside EJB.
Inside an EJB you may retrieve the "Caller" name, that is the login id by invoking:
ctx.getCallerIdentity().getName()

Where ctx is the instance of "SessionContext" passed to the Session Bean, or the instance of "EntityContext" passed to the Entity Bean.

How is Stateful Session bean maintain their states with client?
When a client refers to a Stateful Session object reference, all calls are directed to the same object on the EJB container. The container does not require client identity information or any cookie object to use the correct object. This means that for a client to ensure that calls are directed to the same object on the container, all it has to do is to use same reference for every call.
Thus, if you're calling a Stateful Session Bean from a servlet, your servlet need to keep the reference to the remote object in the HttpSession object between client calls for you to be able to direct calls to the same object on the container. Likewise, if you're calling from an application, you only obtain the reference to the bean once and reuse the object throughout the application session.

With EJB 1.1 specs, why is unsetSessionContext() not provided in Session Beans, like unsetEntityContext() in Entity Beans?
ejbRemove()is called for session beans every time the container destroyes the bean. So you can use this method to do the stuff you typically would do in unsetEntityContext().
For entity beans ejbRemove() is only called if the user explicitly deletes the bean. I think that is the reason why the engineers at SUN invented the unsetEntityContext() for this kind of bean.

How u map a composite Primary Key in CMP Entity Bean and how u handle the same composite primary key in primary key class? What is the usage of HashCode() and Equals() methods? They return only one single primary key value?
equals() returns a boolean that indicates whether another object is "equal" to this one, while hashCode() returns an int that represent the hashcode of an object, that is used for the benefit of hashtables, like java.util.Hashtable.
The reason why we have 2 methods is that hashcode may not always return unique values. So the container also calls the equals method to verify the uniqueness.

Implementing an EJB CMP compound primary key?
A Primary Key Class is a class that follows few simple rules:
It has to implement the java.io.Serializable interface.
All its fields have to be made public, to allow the container to use the Relfection API during the synchronization with the database.
To allow the class to be better handled inside Collections, it should override the hashCode() and equals() methods.
When using CMP Entity Beans, be sure that the fields of the Primary Key class are also present in the Bean class, to allow the container to set the values, always using Reflection API.

Java Servlets FAQ's

How do I set my CLASSPATH for servlets?
For developing servlets, just make sure that the JAR file containing javax.servlet.* is in your CLASSPATH, and use your normal JAVAC to compile servlet.
Incase of Tomcat 4.x, you must set classpath to tomcat/common/lib/servlet.jar. Incase of Tomcat 5.x, you must set classpath to tomcat/common/lib/servlet-api.jar

Note: Please check the documentation of the Server you are using for exact location and .jar file name.

To run servlet, you need not set any classpath since Server (like Tomcat) is already having access to the required .jar files.

How do I support both GET and POST protocol from the same Servlet?
The easy way is, just write code for POST, then have your doGet method call your doPost method.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
doPost(req, res);
}
How do I use Session Tracking? That is, how can I maintain "session scope data" between servlets in the same application?
Session Tracking is one of the most powerful features of Servlets and JSP. Basically, the servlet engine takes care of using Cookies in the right way to preserve state across successive requests by the same user. Your servlet just needs to call a single method getSession() and it has access to a persistent hashtable of data that's unique to the current user.
How can my applet or application communicate with my servlet?
It's pretty straightforward. You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way.
Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

Of course, you can write a servlet that is meant to be called only by your applet, in which case it *does* know the difference. You can also open a ServerSocket on a custom TCP port, and have your applet open a Socket connection. You must then design and implement a custom socket-level protocol to handle the communication. This is how you could write, e.g., a Chat applet communicating with a servlet. In general, a custom protocol requires more work than HTTP, but is more flexible. However, custom protocols have a harder time getting through firewalls.

How do I create an image (GIF, JPEG, etc.) on the fly from a servlet
Once you have an image file in your servlet, you have two choices:
Write the file to disk and provide a link to it. Make sure you write it to a location that's in your web server directory tree (not just anywhere on the server's disk).
Output the image directly from the servlet.You do this by setting the Content-type header to image/gif (for GIFs), or image/jpeg (for JPEGs). You then open the HttpResponse output stream as a raw stream, NOT as a PrintStream, and send the bytes directly down this stream using the write() method.
How do I upload a file to my servlet or JSP?
On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee.For example,





The input type "file" brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.
How do I access a database from my servlet or JSP?
JDBC allows you to write SQL queries as Java Strings, pass them to the database, and get back results that you can parse.
To access database from your servlet, make sure JDBC driver for the database you are accessing is accessible to Web Server (Tomcat).

For example, in Tomcat to access Oracle database through JDBC driver for Oracle, you need to place classes111.zip (renamed to classess111.jar) or classes12.jar in /WEB-INF/lib directory of the application or /common/lib directory of Tomcat.

How does a servlet communicate with a JSP page?
A servlet can send data to JSP in the following ways.
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, test.jsp, by means of a request dispatcher. This method can be used for any kind and any amount of data.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try
{
demo.FormBean f = new demo.FormBean();
String name = request.getParameter("name");
f.setName(request.getParameter("name"));
request.setAttribute("fBean",f);
request.getRequestDispatcher("test.jsp").forward(request, response);
}
catch (Exception ex)
{

}
}
The JSP page test.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.




Second method is to pass data as parameter along with URL. This can be used only when simple data is to be sent from servlet to JSP.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
String name;
// get name from database or some other source
response.sendRedirect("test.jsp?name='" + name+ "'"); // for example, test.jsp?name='pragada srikanth'
}
The JSP page test.jsp can then read the value from parameter as follows:


<%
String name;
name = request.getParameter("name");
%>


Q: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing synchronization for your variables. The key however, is to effectively minimize the amount of code that is synchronized so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

Can I invoke a JSP error page from a servlet?
Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute.
How can I download a file (for instance, a Microsoft Word document) from a server using a servlet and an applet?
Try telling the applet to call getAppletContext().showDocument()
In case or servlet, provide an anchor tag pointing to file that is to be downloaded.

out.println("Document");

Can I call a JSP, then have it return control to the original JSP, like a subroutine or method call?
Yes. That is exactly the purpose served by the action. The syntax of the include action is:


How can I download files from a URL using HTTP?
One way to do this is by using a URLConnection to open a stream to your desired URL, then copy the data out of the stream to a file on your local file system.
Q:How do I send information and data back and forth between applet and servlet using the HTTP protocol?
Use the standard java.net.URL class, or "roll your own" using java.net.Socket. Note: The servlet cannot initiate this connection! If the servlet needs to asynchronously send a message to the applet, then you must open up a persistent socket using java.net.Socket (on the applet side), and java.net.ServerSocket and Threads (on the server side).
What is a servlet engine?
A "servlet engine" is a program that plugs in to a web server and runs servlets. The term is obsolete; the preferred term now is "servlet container" since that applies both to plug-in engines and to stand-alone web servers that support the Servlet API.
What is the difference between GenericServlet and HttpServlet?
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.
In short GenericServlet is protocol independent, whereas HttpServlet is protocol dependent Generic servlet is used for small data transfer whereas HttpServlet is used for huge data transfer.

How do I deal with multi-valued parameters in a servlet?
Instead of using getParameter() with the ServletRequest, as you would with single-valued parameters, use the getParameterValues() method. This returns a String array (or null) containing all the values of the parameter requested.
What is a servlet bean?
A servlet bean is a serializable servlet that follows the JavaBeans component architecture, basically offering getter/setter methods.
What is a web application (or "webapp")?
A web application is a collection of servlets, html pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. A web application is rooted at a specific path within a web server.
The contents of the WEB-INF directory are: /WEB-INF/web.xml deployment descriptor /WEB-INF/classes/* directory for servlet and utility classes. The classes in this directory are used by the application class loader to load classes from. /WEB-INF/lib/*.jar area for Java ARchive files which contain servlets, beans, and other utility classes useful to the web application. All such archive files are used by the web application class loader to load classes from.

What is a WAR file and how do I create one?
WAR (or "web archive") file is simply a packaged webapp directory. It is created using the standard Java jar tool.
For example: jar cf ../mywebapp.war *

How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?
You can use or response.sendRedirect("http://path/YourServlet").
What is inter-servlet communication?
As the name says it, it is communication between servlets. Servlets talking to each other.
There are many ways to communicate between servlets, including :
Request Dispatching
HTTP Redirect
Servlet Chaining
HTTP request (using sockets or the URLConnection class)
Shared session, request, or application objects (beans)
How do I get the name of the currently executing script?
Use request.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info.
The following example demonstrates it:

URL http://www.host.com/servlets/HelloEcho/extra/info?height=100&width=200

getRequestURI /servlets/HelloEcho/extra/info
getServletPath /servlets/HelloEcho
getPathInfo /extra/info
getQueryString height=100&width=200

This is useful if your form is self-referential; that is, it generates a form which calls itself again.
For example:

out.println("
");
out.println("");
out.println("");
out.println("
");
Note: encodeURL() adds session information if necessary.

JDBC FAQ's

How does the Java Database Connectivity (JDBC) work?
The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible classes and interfaces used in the JDBC are placed in package Java
Main JDBC classes:

DriverManager. Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under jdbc will be used to establish a database Connection.
Driver. The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
Connection. Interface with all methods for contacting a database
Statement. Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
ResultSet. The answer/result from a statement. A ResultSet is a 2D list which encapsulates all outgoing results from a given SQL query.
What is a database URL
A database URL (or JDBC URL) is a platform independent way of addressing a database. Exact formation changes from database to database and from one type of driver to another.A database/JDBC URL is of the form
jdbc:[subprotocol]:[node]/[databaseName] Example :

jdbc:odbc:oracle --> to access ODBC data source
jdbc:oracle:thin:@oracleserver:1521:oracle9i --> to access Oracle using thin driver

What types of JDBC drivers exist?
There are four types of JDBC database driver:
Driver type Explanation Comment
1 The JDBC/ODBC bridge driver A piece of native C-code that translates a JDBC call to an ODBC call. Use this driver for development, not for industrial-strength application environments. Note that you have to have an ODBC database driver manager + an ODBC database driver installed on the server in addition to the JDBC/ODBC bridge.
2 Native API partly java driver A piece of native C-code that translates a java JDBC call to a native database call level API. Use this driver for development and deployment. Due to its native code, this driver can only be used by Java Applications with full computer access (i.e. not Applets).
3 JDBC-Net pure Java driver A piece of pure java code that translates an incoming JDBC call to an outgoing database Net protocol call (such as SQL*Net). Use this driver for development and deployment. Flexible and powerful, This driver can be used by any Java component and requires only connect access to work.
4 Native protocol pure Java driver A piece of pure java code that translates an incoming JDBC call to an outgoing database native protocol call (such as Oracle CLI). Use this driver for development and deployment. This driver type is the recommended one for server-side java development.
How do I create a database connection?
The database connection is created in 3 steps:
Load the database driver
Find a proper database URL
Ask the Java DriverManager class to open a connection to your database
What is the difference between a Statement and a PreparedStatement?
The PreparedStatement is a slightly more powerful version of a Statement,and should always be at least as quick and easy to handle as a Statement.
Another advantage of the PreparedStatement class is the ability to create an incomplete query and supply parameter values at execution time.
What is Metadata and why should I use it?
Metadata (data about data) is information about one of two things
Database information (java.sql.DatabaseMetaData), or
Information about a specific ResultSet (java.sql.ResultSetMetaData).
Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as name, size and type of each column.
What is a "dirty read"?
Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value.

While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

Q:How do I extract a BLOB from a database?
A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You extract the data in two steps:
Call the getBlob() method of the Statement class to retrieve a java.sql.Blob object
Call either getBinaryStream() or getBytes() in the extracted Blob object to retrieve the java byte[] which is the Blob object.
Note A Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. Thus, you must extract all data from the database blob.

// Prepare a Statement:
PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");
// Execute
ResultSet rs = stmnt.executeQuery();

while(rs.next())
{
try
{

// Get as a BLOB
Blob aBlob = rs.getBlob(1);
byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length());

}
catch(Exception ex)
{
}
}

}
Q:Which is the preferred collection class to use for storing database result sets?
When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include:
Retains the original retrieval order
Has quick insertion at the head/tail
Doesn't have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created (or you have to find out size beforehand to size properly)
Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized
ResultSet result = stmt.executeQuery("...");
List list = new LinkedList();
while(result.next()) {
list.add(result.getString("col"));
}

If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from database, instead of later.
How can I check whether the value I read from a column is null or not null?
After using one of the getXXX() methods of ResultSet, you can use wasNull() method to test whether you got null value or not null.
rs.getString("email");

if ( rs.wasNull() )
// no email
else
// use email

Do I need to commit after an INSERT call in JDBC or does JDBC do it automatically in the DB?
If your autoCommit flag (managed by the Connection.setAutoCommit() method) is false, you are required to call the commit() method - and vice versa. The default is setting to AutoCommit flag is True.
How can I retrieve only the first N rows, second N rows of a database using a particular WHERE clause ? For example, if a SELECT typically returns a 1000 rows, how do first retrieve the 100 rows, then go back and retrieve the next 100 rows and so on ?
Use the setFetchSize() method of Statement to indicate the size of each database fetch.

Statement stmt = con.createStatement();
stmt.setFetchSize(100);
ResultSet rs = stmt.executeQuery("select * from customers");


You can also control the direction in which the rows are processed. For instance:

stmt.setFetchDirection(ResultSet.FETCH_REVERSE)

will process the rows from bottom up.
The driver manager usually defaults to the most efficient fetch size...so you may try experimenting with different value for optimal performance.



How can I make batch updates using JDBC?
One of the more advanced features of JDBC 2.0 is the ability to submit multiple update statements to the database for processing as a single unit. This batch updating can be significantly more efficient compared to JDBC 1.0, where each update statement has to be executed separately.

try
{
dbCon.setAutoCommit(false);

Statement stmt= dbCon.createStatement();
stmt.addBatch("INSERT INTO bugs VALUES (...)");
stmt.addBatch("INSERT INTO bugs VALUES (...)");

int[] updCnt = stmt.executeBatch();

dbCon.commit();

}
catch (BatchUpdateException be)
{
//handle batch update exception
int[] counts = be.getUpdateCounts();
for (int i=0; i < counts.length; i++) {
System.out.println("Statement["+ i + "] :" + counts[i]);
}
dbCon.rollback();
}
catch (SQLException e)
{
//handle SQL exception
dbCon.rollback();
}

What are SQL3 data types?
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

Can I use the JDBC-ODBC bridge driver in an applet?
No. JDBC-ODBC driver using ODBC driver,which is Native Code. Applets cannot use native code.
You may create a digitally signed applet using a Certificate to circumvent the security sandbox of the browser.

Q:What is SQLJ and why would I want to use it instead of JDBC?
SQL/J is a technology, originally developed by Oracle Corporation, that enables you to embed SQL statements in Java. The purpose of the SQLJ API is to simplify the development requirements of the JDBC API while doing the same thing. Some major databases (Oracle, Sybase) support SQLJ, but others do not.
How do I insert an image file (or other raw data) into a database?
All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[].
Read all data from the file using a FileInputStream.
Create a byte array from the read data.
Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to upload the data.
I am using a type 4 (pure Java) JDBC driver in an applet. It works fine in Netscape, but doesn't work properly in Internet Explorer. Why not?
Microsoft's VM loads classes/drivers differently than the Java VM in Netscape browsers (and Sun's reference implementation). Just having a Class.forName(driverClassName) line is insufficient, as it doesn't consider it an active use. You'll also need to create a new instance of the driver Class.forName(driverClassName).newInstance() which registers the driver with the driver manager (java.sql.DriverManager.registerDriver(new DriverClass())).
How can I get data from multiple ResultSets?
With certain database systems, a stored procedure can return multiple result sets, multiple update counts, or some combination of both. Also, if you are providing a user with the ability to enter any SQL statement, you don't know if you are going to get a ResultSet or an update count back from each statement, without analyzing the contents.
The Statement.execute() method helps in these cases.Method Statement.execute() returns a boolean to tell you the type of response: true indicates next result is a ResultSet,Use Statement.getResultSet() to get the ResultSet false indicates next result is an update count Use Statement.getUpdateCount() to get the update count false also indicates no more results Update count is -1 when no more results (usually 0 or positive).

After processing each response, you use Statement.getMoreResults() to check for more results, again returning a boolean.

The following demonstrates the processing of multiple result sets:

boolean result = stmt.execute(" ... ");
int updateCount = stmt.getUpdateCount();

while (result || (updateCount != -1))
{
if(result)
{
ResultSet r = stmt.getResultSet();
// process result set
}
else
if(updateCount != -1)
{
// process update count
}
result = stmt.getMoreResults();
updateCount = stmt.getUpdateCount();
}

How do I execute stored procedures?
Here is an example on how to execute a stored procedure with JDBC. CallableStatement cs = con.prepareCall("{? = call procedure(?,?) }"); cs.registerOutParameter(1, java.sql.Types.VARCHAR ); cs.setInt(2, value1 ); cs.setInt(3, value2 ); ResultSet lrsReturn = null; lrsReturn = msProcedure.executeQuery(); while( lrsReturn.next() ) { System.out.println("Got from result set: " + lrsReturn.getInt(1)); } System.out.println( "Got from stored procedure: " + cs.getString( 1 ) );
What are database cursors?
A cursor is actually always on the database server side. When you execute an SQL SELECT and create a ResultSet in JDBC, the RDBMS creates a cursor in response. When created, the cursor usually takes up temporary memory space of some sort inside the database.
How can I connect to an Excel spreadsheet file using jdbc?
Let's say you have created the following Excel spreadsheet in a worksheet called Sheet1 (the default sheet name). And you've saved the file in c:\users.xls.
USERID FIRST_NAME LAST_NAME abc a b xyz x y

Since Excel comes with an ODBC driver, we'll use the JDBC-ODBC bridge driver that comes packaged with Sun's JDK to connect to our spreadsheet.

In Excel, the name of the worksheet is the equivalent of the database table name, while the header names found on the first row of the worksheet is the equivalent of the table field names. Therefore, when accessing Excel via jdbc, it is very important to place your data with the headers starting at row 1.

Create a new ODBC Data Source using the Microsoft Excel Driver. Name the DSN "excel", and have it point to c:\users.xls.
Type in the following code:
Connection conn=null;
Statement stmt=null;
String sql="";
ResultSet rs=null;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:excel","","");
stmt=conn.createStatement();
sql="select * from [Sheet1$]";
rs=stmt.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getString("USERID")+ " "+ rs.getString("FIRST_NAME")+" "+ rs.getString("LAST_NAME"));
}
}
catch (Exception e)
{ System.err.println(e); }
finally
{
try
{
rs.close();
stmt.close();
conn.close();
}
catch(Exception e){}
}
Notice that we have connected to the Excel ODBC Data Source the same way we would connect to any normal database server.
The only significant difference is in the SELECT statement. Although your data is residing in the worksheet called "Sheet1", you'll have to refer to the sheet as Sheet1$ in your SQL statements. And because the dollar sign symbol is a reserved character in SQL, you'll have to encapsulate the word Sheet1$ in brackets, as shown in the code.

Can ResultSets and Connections be passed around like other objects?
Yes, although, as usual, technically we are passing object references. However, there is a chain of dependency that must be kept in mind and should be tracked for Connection, Statement and ResultSet. For example, If a ResultSet is not scrollable, rows already read are not available, so passing the same ResultSet to different methods may not work as expected. If the originating Statement is closed, the ResultSet is generally no longer available.
How can I pass data retrieved from a database by a servlet to a JSP page?
One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:
com.foo.dbBean bean = new com.foo.dbBean();
//call setters to initialize bean
req.setAttribute("dbBean", bean);
url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);

The bean can then be accessed within the JSP page via the useBean tag as:



...



Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine.
How can I read and write serialized objects to and from a database?
If your RDBMS supports them, you can store serialized objects as BLOBs. These are JDBC 2.0 features, but take a look at java.sql.Blob, ResultSet and PreparedStatement.
Why do I get an UnsupportedOperationException?
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
Could we get sample code for retrieving more than one parameter from a stored procedure?
Assume we have a stored procedure with this signature:
MultiSP (IN I1 INTEGER, OUT O1 INTEGER, INOUT IO1 INTEGER)
The code snippet to retrieve the OUT and INOUT parameters follows:

CallableStatement cs = connection.prepareCall( "(CALL MultiSP(?, ?, ?))" );
cs.setInt(1, 1); // set the IN parm I1 to 1
cs.setInt(3, 3); // set the INOUT parm IO1 to 3

cs.registerOutParameter(2, Types.INTEGER); // register the OUT parm O1
cs.registerOutParameter(3, Types.INTEGER); // register the INOUT parm IO1

cs.execute();
int iParm2 = cs.getInt(2);
int iParm3 = cs.getInt(3);
cs.close();

The code really is just additive; be sure that for each IN parameter that setXXX() is called and that for each INOUT and OUT parameter that registerOutParameter() is called.
Q:Can a stored procedure return an updatable ResultSet?
A:This depends on your driver. If it supports JDBC 2.0, then the answer is yes, although the functionality is in the driver. As you can see from Creating a CallableStatement Object, there is no difference in the stored procedure itself.
What areas should I focus on for the best performance in a JDBC application?
These are few points to consider:
Use a connection pool mechanism whenever possible.
Use prepared statements. These can be beneficial, for example with DB specific escaping, even when used only once.
Use stored procedures when they can be created in a standard manner. Do watch out for DB specific SP definitions that can cause migration headaches.
Even though the jdbc promotes portability, true portability comes from NOT depending on any database specific data types, functions and so on.
Select only required columns rather than using select * from Table.
Always close Statement and ResultSet objects as soon as possible.
Write modular classes to handle database interaction specifics.
Work with DatabaseMetaData to get information about database functionality.
Softcode database specific parameters with, for example, properties files.
Always catch AND handle database warnings and exceptions. Be sure to check for additional pending exceptions.
Test your code with debug statements to determine the time it takes to execute your query and so on to help in tuning your code. Also use query plan functionality if available.
Use proper ( and a single standard if possible ) formats, especially for dates.
Use proper data types for specific kind of data. For example, store birthdate as a date type rather than, say, varchar.
Why do I get "Driver Not Capable" errors and what does it mean?
This error indicates that: the operation is valid but not supported by either the driver or the data source.
How do I get a scrollable ResultSet?
You can get scrollable ResultSets by using the JDBC 2.0 API. You must have a driver that supports JDBC 2.0. The following code will give a Statement the capability to create scrollable ResultSets:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

Now use the Statement object to execute the query: For example:-

ResultSet srs = stmt.executeQuery("SELECT FIRST_NAME, AGE FROM STUDENTS_TABLE");

What's new in JDBC 3.0?
Probably the new features of most interest are:
Savepoint support
Reuse of prepared statements by connection pools
Retrieval of auto-generated keys
Ability to have multiple open ResultSet objects
Ability to make internal updates to the data in Blob and Clob objects
Ability to Update columns containing BLOB, CLOB, ARRAY and REF types
How do I create an updatable ResultSet?
Just as is required with a scrollable ResultSet, the Statement must be capable of returning an updatable ResultSet. This is accomplished by asking the Connection to return the appropriate type of Statement using Connection.createStatement(int resultSetType, int resultSetConcurrency). The resultSetConcurrency parameter must be ResultSet.CONCUR_UPDATABLE. The actual code would look like this:

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE );

Note that the spec allows a driver to return a different type of Statement/ResultSet than that requested, depending on capabilities and circumstances, so the actual type returned should be checked with ResultSet.getConcurrency().
How do I get runtime information about the JDBC Driver?
Use the following DatabaseMetaData methods:
getDriverMajorVersion()
getDriverMinorVersion()
getDriverName()
getDriverVersion()
Why do I get the message "No Suitable Driver"?
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
How can I ensure that my app has the latest data?
Typically an application retrieves multiple rows of data, providing a snapshot at an instant of time. Before a particular row is operated upon, the actual data may have been modified by another program. When it is essential that the most recent data is provided, a JDBC 2.0 driver provides the ResultSet.refreshRow() method.
How can I connect to mysql database using jdbc?
// loads the JDBC driver
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
// get a database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://hostname/databaseName", "user","password");
Where is console output sent (System.out/System.err) in stored procedures written in Java?
With Oracle, console output from System.out.println() statements will be written to trace files in the Oracle UDUMP destination directory.
What is JDO?
JDO provides for the transparent persistence of data in a data store agnostic manner, supporting object, hierarchical, as well as relational stores.
What is the difference between setMaxRows(int) and SetFetchSize(int)? Can either reduce processing time?
setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows() method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit.

Can I get information about a ResultSet's associated Statement and Connection in a method without having or adding specific arguments for the Statement and Connection?
Yes. Use ResultSet.getStatement(). From the resulting Statement you can use Statement.getConnection().
What is pessimistic concurrency?
With a pessimistic approach, locks are used to ensure that no users, other than the one who holds the lock, can update data. It's generally explained that the term pessimistic is used because the expectation is that many users will try to update the same data, so one is pessimistic that an update will be able to complete properly. Locks may be acquired, depending on the DBMS vendor, automatically via the selected Isolation Level. Some vendors also implement 'Select... for Update', which explicitly acquires a lock.
What is optimistic concurrency?
An optimistic approach dispenses with locks (except during the actual update) and usually involves comparison of timestamps, or generations of data to ensure that data hasn't changed between access and update times. It's generally explained that the term optimistic is used because the expectation is that a clash between multiple updates to the same data will seldom occur
What is a JDBC 2.0 DataSource?
The DataSource class was introduced in the JDBC 2.0 Optional Package as an easier, more generic means of obtaining a Connection. The actual driver providing services is defined to the DataSource outside the application (Of course, a production quality app can and should provide this information outside the app anyway, usually with properties files or ResourceBundles ). The documentation expresses the view that DataSource will replace the common DriverManager method.
Some downsides are:

Vendor specific set up tools must be used, with no particular standards specified. To quote from the source: "Now he ( the developer - JS ) needs to have his system administrator, SoLan, deploy the DataSource objects so that he... can start using them".
JNDI must be used to implement a lookup for the DataSource.
Why can't Tomcat find my Oracle JDBC drivers in classes111.zip?
TOMCAT throws the following exception when i try to connect to Oracle DB from JSP.
javax.servlet.ServletException : oracle.jdbc.driver.OracleDriver

Root Cause : java.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriver

But, the Oracle JDBC driver ZIP file (classes111.zip)is available in the system classpath.
The problem can be solved by using the following procedure:

Copy the Oracle Driver class file (classes111.zip) into /WEB-INF/lib directory
Rename it to classess111.jar. Because only .jar files are recognized and not .zip files.
How do I insert/update records with some of the columns having NULL value?
Use the following method of PreparedStatement:
public void setNull(int parameterIndex, int sqlType) throws SQLException
What does it mean to "materialize" data?
This term generally refers to Array, Blob and Clob data which is referred to in the database via SQL locators. "Materializing" the data means to return the actual data pointed to by the Locator.
For Arrays, use the various forms of getArray() and getResultSet().

For Blobs, use getBinaryStream() or getBytes(long pos, int length).

For Clobs, use getAsciiStream() or getCharacterStream().

How can I write to the log used by DriverManager and JDBC drivers?
The simplest method is to use DriverManager.println(String message), which will write to the current log.
How do I install the Thin driver?
Put the jar files in a convenient location and include the appropriate jar files in your classpath.
How do I install the OCI driver?
The JDBC OCI driver generally requires an Oracle client-installation of the same version the driver

Applets, AWT and Swing FAQs

What is z-order?
Z-order controls how components are drawn on top of one another. The 0 layer is the highest layer, or the one drawn last. Layer 1 is next, then 2, and so on.

How can I get Pixel Info (width, height, pixel colors) for a text string?
The width and height are actually very easy. All you need to do is get a FontMetrics object for the font you used to draw the string, and ask it:
FontMetrics fm = getFontMetrics(getFont()); System.out.println(fm.getHeight()); System.out.println(fm.getLeading()); System.out.println(fm.stringWidth("This is a sample string")); 
Note that the height is the actual space the font requires, while leading is the space the font requests be used between lines of text on the screen.

Which layouts respect which sizing methods?
The Component class defines several size accessor methods to assist the layout process. Each of these methods returns a Dimension object describing the requested size. These methods are as follows:
  • public Dimension getPreferredSize() : This returns the desired size for a component.
  • public Dimension getMinimumSize() : This returns the smallest desired size for a component.
  • public Dimension getMaximumSize(): This returns the largest desired size for a component.
Layout managers will use these sizing methods when they are figuring out where to place components and what size they should be. Layout managers can respect or ignore as much or as little of this information as they see fit. Each layout manager has its own algorithm and may or may not use this information when deciding component placement.

Layout ManagerRespects...
BorderLayoutpreferred height (NORTH, SOUTH)
preferred width (EAST, WEST)
FlowLayoutpreferred size
CardLayoutnone
GridLayoutnone
GridBagLayoutpreferred size (for initial component sizes)

How do I create radio buttons in AWT?
AWT uses the Checkbox class for both check boxes and radio buttons.

To create a radio button, you need to create check boxes, and add them to a checkboxgroup.

public class Test {   public static void main(String[] args)   {     Frame f = new Frame();     f.setLayout(new GridLayout(0,1));  // one columns and multiple rows     CheckboxGroup group = new CheckboxGroup();     f.add(new Checkbox("One", group, true));     f.add(new Checkbox("Two", group, false));     f.add(new Checkbox("Three", group, false));     f.pack();     f.setVisible(true);   } }  
What is the difference between AWT and SWT?
SWT (Standard Widget Toolkit) is a completely independent Graphical User Interface (GUI) toolkit from IBM. They created it for their new Eclipse Integrated Development Environment (IDE).

IBM began work on SWT a few years ago, because Swing was still immature and didn't perform well. They decided to create a new toolkit to provide better performance using native widgets.

What is the default layout manager of an applet?
For a java.applet.Applet, the default layout manager is FlowLayout.

For the content pane of a javax.swing.JApplet, the default layout manager is a BorderLayout.

How can I get a reference to the container to which a component has been added?
Use component.getParent() method.

How do we stop the AWT Thread? Our Swing application will not terminate.
You need to explicitly call System.exit(exit_value) to exit a Swing application. This is because the event dispatcher thread is not a Daemon thread, and won't allow the JVM to shut down when other threads are dead.

How can I determine the active JFrame?
Call Frame.getFrames() which will return all frames created by the application.
Frame[] f = Frame.getFrames(); Frame active = null; for (int i = 0; i < active =" f[i];">
How do I change the current look and feel of my Swing program?
You can either call the setLookAndFeel() method of the UIManager class or set the swing.defaultlaf property of your Java program before it starts.

If you wish to change the look and feel of a running program, you will need to call the updateComponentTreeUI() method of the SwingUtilities class to update each top-level window.

Is it possible to know which button user pressed in mouse events?
Use the following code to know which button is pressed.
  public void mousePressed( java.awt.event.MouseEvent evt)   {         if (  evt.getModifiers() == InputEvent.BUTTON1_MASK)              // left button process         else             // right button process   }  

How do I ensure a specific row is visible in my JTable?
To ensure a specific row (or cell) is visible, you need to get the rectangle surrounding a specific row/column (cell) than make sure that is visible:
Rectangle rect = table.getCellRect(row, column, true); table.scrollRectToVisible(rect);  

What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?
When you run a GUI applet or application, the code in your main() method creates a GUI and sets up event handling. When you call setVisible(true) for your Frame, Window, Dialog, or when the browser displays the Applet, the user must be able to interact with the GUI.

The problem is that your main() method may not end at that point. It could be busy doing some other task. If the user had to wait for the main() method to finish before they could interact with the GUI, they could end up quite unhappy.

So the AWT library implements its own thread to watch GUI interaction. This thread is essentially a little loop that checks the system event queue for mouse clicks, key presses and other system-level events. (You can also put your own events in the system queue, but that's another story...).

The AWT thread (aka the "Event Dispatch" thread) grabs a system event off the queue and determines what to do with it. If it looks like a click on top of a component, it calls the mouse click processing handler for that component. That component, in turn, could fire other events. For example, if you click on a JButton, the AWT thread passes the mouse click to the JButton, which interprets it as a "button press", and fires its own actionPerformed event. Anyone listening will have their actionPerformed method called.

The AWT thread also handles repainting of your GUI. Anytime you call repaint(), a "refresh" request is placed in the event queue. Whenever the AWT thread sees a "refresh" request, it calls the appropriate methods to layout the GUI and paint any components that require painting.

Note: The AWT "thread" may in fact be implemented by multiple threads under some runtime environments. These threads coordinate effort to watch for mouse clicks, keypresses, repaint requests, etc. As far as you're concerned you can treat this all as one "AWT thread".

How can I validate data entered in a TextField?
You can validate the data in any of the three location
  • As the user types characters
    Register a DocumentListener with the JTextField and validate data in the events of DocumentListener.
  • After the user is done with the field
    You need to register listeners for: Focus change (leaving the JTextField), Pressing enter (ActionListener). With any of these events, perform the data validation.
  • After the user is done with the GUI
    In this case, only perform your validation when the user presses "Done" or whatever action ends the user interaction with the GUI.

How do I display a multi-line tooltip?
You can include HTML content in tooltip text as follows:
setToolTipText("This is the first line
This is the second line");

How do I let my Swing text component support undo/redo?
The Swing text components come with built in support for undoing and redoing text operations. All you have to do is associate an UndoManager to the Document of the text component:
JTextField textField = new JTextField(); UndoManager manager = new UndoManager(); Document document = textField.getDocument(); document.addUndoableEditListener(manager);  
Then, when it comes time to undo or redo the last edit, you would notify the UndoManager by calling either the undo() or redo() method of the manager. If the manager cannot undo an operation, the runtime exception CannotUndoException is thrown. If a redo operation cannot be redone, the runtime exception CannotRedoException is thrown.

Java Language FAQs

What is JDK 1.5? Is it same as J2SE 5.0/1.5? Also I heard about Tiger. What is Tiger?
JDK 1.5 or J2SE 1.5 or 5.0 or Tiger all mean the same. They all refer to the latest version of Java.

Tiger is the code name of Java 5.0 during its development. Then Sun gave the name J2SE (Java2 Standard Edition) 1.5. But compared with J2SE 1.4, J2SE 1.5 has some very important changes to Java language. So Sun preferred to call it as J2SE 5.0 to signify major changes to language.

The new name gave by Sun is Java SE 5.0 (they are dropping 2 from name as it refers to Java2 and now Java2 is not appopriate any more).

What is the difference between Java and C++?
Java and C++ are two different object oriented programming languages. Both of them are widely used.

C++ is a powerful and flexible language used mainly in system programming.

Java is a roubust and platform independent language which is used to develop business and internet applications.

A lot of features of C++ are not found in Java and vice-versa.

C++ features not in Java

  • Pointers
  • Friend functions
  • Operator overloading
  • Default function arguments
  • Function and class Templates. Java has Generics (which are simlar to Templates though not same) in version 5.0
  • delete keyword
  • Multiple inheritance
  • Types of derivation - public, private and protected.

Java features not in C++

  • Interfaces
  • Packages (Namespace added later to C++)
  • Default access method
  • Multithreading
  • Applets
  • Garbage Collection
  • Standard classes for Collections, Network programming etc.

What is a JAR file?
JAR file is similar to a .LIB file in C and C++.
JAR (Java Archive) file contains a collection of packages and classes. It is used to distribute packages and classes.
Jar file is created using JAR.EXE, which is found in BIN directory of JDK. For example the following command creates a jar file with the name srikanth.jar and contains all .class files in the current directory.
jar cvf srikanth.jar . 
To use classes of a jar file one has to keep jar file in CLASSPATH.

How can we create a executable jar file?
An executable jar file is the one with a manifest file specifying which class is to start when user executes it (double clicks it in explorer) or invokes with -jar flag of java ( java -jar test.jar).

Assume we have First.class and Second.class to be placed in a jar file test.jar. We want First.class to start execution when user runs test.jar.

Create a manifest file with the name test.mf as follows:

Main-Class: First 
Note, we should not mention the .class extesion for the file in Manifest file.

Create test.jar file as follows:

jar cfm test.jar test.mf  First.class  Second.class 
You can now either double click .jar file in explorer to start running First.class of test.jar or you can run it with java as follows:
java -jar test.jar 

What is Serializable interface? How do we use?
Serializable interface is an empty interface present in java.io package. It is implemented by classes that are to be serialized. Serialization is the process of converting an object into a stream of bytes.

An object must be serializable if it is to be written to disk or transfered in distributed applications.

The following example shows class Student implementing this interface to indicate to Java that its object can be serialized by Java.

public class  Student implements java.io.Serializable {   // body of class }  

What is the base/super class for all classes in Java?
Every class that is not extending another class is implicitly extending Object class in Java. So java.lang.Object class is the super most class of all classes in Java.

What is the difference between interface and abstract class
An interface contains only declaration of methods and can not have any body for methods.
Whereas an abstract class can contains abstract methods without any body but it can also have non-abstract methods with body (which is not possible with interfaces).

Interfaces cannot contain instance variables
Abstract class can contains instance variables.

However, interface and abstract classes can not have objects. They can only have object references which point to object of implementing class or sub class.

What is a null interface in JAVA? What does it mean? Are there any null interfaces in JAVA?
A null interface is an interface without any methods. Null interfaces are used to inform Java regarding what it can do with a class. For example, Serializable interface informs Java that objects of the implementing class can be serialized.

The following are important null interfaces in Java.

  • java.lang.Cloneable
  • java.io.Serializable
  • java.rmi.Remote
How do I access environment variables?
Starting with JDK 1.5, the getenv() method of System class returns an environment variable setting.

How do you clear a system property?
Starting with JDK 1.5, you can use the clearProperty method of System class.

How do I loop through a set of enum values in 1.5+?
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }  for (Suit suit : Suit.values()) {     System.out.println(suit); }  

How do I compute a Date 24 hours from now?
Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, 1); Date d = cal.getTime(); 
How do I change the starting directory for running a command with ProcessBuilder?
Use the directory() method of ProcessBuilder to change the starting / working directory. Once setting the directory, start() the sub-process.
   ProcessBuilder processBuilder = new ProcessBuilder(                                        command, arg1, arg2);    processBuilder.directory("DirectoryLocation");    Process p = processBuilder.start(); 

What's the difference between Runtime.exec() and ProcessBuilder?
JDK 5.0 added a new class, ProcessBuilder to do the equivalent of the exec() method of Runtime. In addition to running commands in forked off subprocesses, you can adjust environment variables and change the starting working directory with ProcessBuilder.

What's a static import?
It lets you avoid qualifying static members with class names. If you import static java.lang.Math.PI; you can then use PI without qualifications.

Sometimes when I try to override a method, I get the signature wrong. The program still compiles, but the code never runs. How can I make sure my method actually overrides the method of the superclass?
The @Override

Can Java use attributes?
Yes. In Java, however, these are called annotations. They were added in version 5.0.

What is "Tiger"?
"Tiger" was the code name for Java 2 Platform Standard Edition (J2SE) 5.0 that released on September 29th, 2004.

This major release included over a dozen JSRs and nearly 100 other significant updates from the JCP. You should note that this can also be considered developer release 1.5.0.

This release included features such as the addition of generics, an enhanced for loop, enumerated types, static imports, automatic boxing of primitive types and much more.

Tiger is followed by the "Mustang", which will be J2SE 6.0 (1.6.0), which in turn will be followed by "Dolphin", which will be J2SE 7.0 (1.7.0).

What is "Mustang"?
Mustang is the code name for J2SE 6.0. (1.6.0)

The Mustang release of J2SE is expected to include a number of key changes to J2SE including changes to the release model of the JDK, XML and Web Services, Transparency, Ease-of-Development improvements, better compatibility, an updated to the API for accessing JDBC, and the addition of a scripting engine. There will a refined GUI as well as graphics performance improvements.

Which kind off error can stop jvm in java?
Actually, the JVM will exit if unchecked-exceptions (for example RuntimeException etc) are not caught.

How can i find out which JAR file or Directory from where my class was loaded?
class Test {   public static void main (String args[]) {  System.out.println("Loaded Test from:" + Test.class.getProtectionDomain().getCodeSource().getLocation());   } } 
Why the following code doesn't work?
float f;     f = 10.50; 
The above code doesn't work because, by default all floating point constants in Java are treated as double, the float variable f cannot take a double value. The remedy is to convert it using type casting ( (float)10.50) or declare variable f as double.

Can I use standard data types like int, float and char with Vector class?
No. You cannot use them as Vector deals with objects. Standard data types are not objects. However, you can use wrapper classes to convert standard data types to object so that they can be used with Vector.
    Vector v = new Vector();      // v.add(10);  -- cannot be done     v.add ( new Integer(10));   // int 10 is converted to object of type Integer class. 

How do i convert an int to String?
You can use String.valueOf(int) method to convert int to String.