Java J2ee Struts Hibernate Spring Interview Questions Java J2ee Struts Hibernate Spring Interview Questions
1 2 3 4 5    Next

1. What is the difference between getting a connection from DataSource and DriverManger?

DataSource and DriverManager are the two basic ways to connect to a database in a JEE application.
The DriverManager is older facility, the DataSource is newer.

It is recommended to use the new DataSource facility to connect to databases and other resources.

DriverManager will take time as it creates the connection whenever you require.
It involves loading the driver class and registering the driver. then it will creates the connection.

Connection    myConnection =  DriverManager.getConnection(prop.getProperty("DataBaseUrl"),prop.getProperty("user"),prop.getProperty("password"));

Using DataSource you can get connection from connection pool. High trafic enterprise applications need
fine tuned connection pools. you can implement Apache Commons DBCP, or C3P0 Connection pools.
C3P0 additionally pool statements also, apart from connection pool.

                    BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource();
                    ((BasicDataSource) dataSource).setDriverClassName(prop.getProperty("driverClassName"));
                    ((BasicDataSource) dataSource).setUrl(prop.getProperty("keyClockUrl"));
                    ((BasicDataSource) dataSource).setUsername(prop.getProperty("user"));
                    ((BasicDataSource) dataSource).setPassword(prop.getProperty("password"));
                    ((BasicDataSource) dataSource).setMaxActive(Integer.valueOf(prop.getProperty("initialSize")));
                    ((BasicDataSource) dataSource).setMaxActive(Integer.valueOf(prop.getProperty("minIdle")));
                    ((BasicDataSource) dataSource).setMaxActive(Integer.valueOf(prop.getProperty("maxActive")));
                    ((BasicDataSource) dataSource).setMaxIdle(Integer.valueOf(prop.getProperty("maxIdle")));
                    ((BasicDataSource) dataSource).setMaxWait(Integer.valueOf(prop.getProperty("maxWait")));
                    ((BasicDataSource) dataSource).setDefaultAutoCommit(Boolean.getBoolean(prop.getProperty("defaultAutoCommit")));
                    ((BasicDataSource) dataSource).setDefaultReadOnly(Boolean.getBoolean(prop.getProperty("defaultReadOnly")));
                    myConnection =  dataSource.getConnection();

 private static ComboPooledDataSource cpds = new ComboPooledDataSource();
        if (cpds.getNumBusyConnectionsAllUsers() >= cpds.getMaxPoolSize()) {
          //hardReset() immediately closes all Connections managed by the DataSource, including those that are currently checked out,
          //bringing the DataSource back to the state it was in before the first client called getConnection().
          System.out.println("SOFT RESET CP");
          // Connections aren't close()ed
        //create connection and do the stuff
        Connection myConnection = C3poDataSource.getConnection();

2. How do you configure DataSource in Struts ? How do you implement Connection Poooling in Struts ?

Connection Pooling in Struts :

In struts-config.xml file data sources tag is there? you can configure connection pool from that xml file and you can create the connection as below.

<data-source type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="url" value="jdbc:mysql://localhost/DBNAME" />
<set-property property="username" value="" /> 
<set-property property="password" value="abcdefgh" />
<set-property property="maxActive" value="20" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="false" />
<set-property property="defaultReadOnly"   value="false" />  
...//Here Other Struts Configuration Tags...
struts-config >

In the above file the default values comes with this file was maxActive 20.
You can set the values here as per your network traffic on your server?
Here totally 20 connection objects will be active in the pool and 5000 (5 seconds ) will be the time to wait for a connection object. You can set number of maxIdle connections also.

CODE : in your Action Class execute method or any other class you can create the connection object like this.
//Just declare the data source and connection objects;
javax.sql.DataSource dataSource = null;
java.sql.Connection myConnection = null;

//Just by using the following 2 lines of Code you can create a connection //object from the data source by using the concept of connection pooling.

dataSource = getDataSource(request);
myConnection = dataSource.getConnection();

You can also refer to EJB Instance Pooling...

How do you configure data source in Tomcat ?
How do you configure data source in WebLogic ?
How do you configure data source in JBoss ?
How do you configure data source in WebSphere ?

3. How do you implement the Connection Pooling in Java?

After this question is raised we will get 2 questions in mind?

What is connection pooling ?
What is instance pooling ?
Why should we go for instance pooling ?

Creation of Database Connection is an expensive task?

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.

Using a DataSource Object for a connection

Using a DataSource object increases application portability by making it possible for an application to use a logical name for a data source instead of having to supply information specific to a particular driver. The following example shows how to use a DataSource to establish a connection:

You can configure a DataSource using a tool or manually. For example, Here is an example of a DataSource lookup:

 InitialContext ic = new InitialContext(); 
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()

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.

VendorDataSource vds = new VendorDataSource();
String name = vds.getServerName();

4. Can you tell me the code for implementing the connection pooling in WebLogic Server ?

If we want a database connection from the pool, we need to create it from the DataSource not from DriverManager.
So DriverManager.getConnection() method will give you normal connection Where as DataSource.getConnection() method will give you a database connection from the connection pool.

To get a DataSource reference we need a JNDI name, from that name we can get InitialContext reference.
The following is the Standard code to get a connection from DataSource. For more information refer to WebLogic Docs.

The JNDI name will be there in the Directory Service. The Initial Context Object will get the information from the Directory Service.

InitalContext ic = new InitialContext();
Hashtable ht = new Hashtable();
ht.put( Context.INITIAL_CONTEXT_FACTORY,weblogic.jndi.WLInitialContextFactory);
//You have to set weblogic properties first and the JNDI name that you are defining in Weblogic while creating the connection pool
//here t3 means TENGA Protocol
ht.put( Context.PROVIDER_URL t3://localhost:7001);
ht.put( Context.SECURITY_PRINCIPAL username);
ht.put( Context.SECURITY_CREDENTIALS password_of_ weblogic);

Whenever you need a connection in your Java Class you can use the following lines of code.

DataSource ds = (DataSource)ic.lookup("jndiname");
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
//from here you can play normally

5. What do you know about Struts Token Feature ?

Struts Token Feature will be very much useful in common problems like Refresh Button, Back Button, double form submissions etc.

Most often after successful submission of the form just you redirect to your Home Page. Why because if you use RequestDispatcher.forward() method, this will not change the URL of the browser, so if the user presses Refresh Button or F5 Button or Back Button, the same form will be again submitted and you will get another record in side database. So we can use response.sendRedirect() method only to avoid refresh problems.

If we have a perfect tracking Id, say if a user is paying his credit card bill, if you uniquely identify that user with bill number plus due date kind of combinations, your logic should prevent the duplicate form submissions. Another idea is if you can store the values some where for sometime, if same kind of values are coming from the same user then you can decide if its is a fresh request or a duplicate post.

Struts has a token feature that puts a single-use token on a form to prevent duplicate submits. Redirecting after post prevents duplicate submissions using the "back" button but will not prevent a duplicate post if a user submits more than once in rapid succession. Typically when a Struts action is going to forward to a page that will post information the action will call Action.saveToken(HttpServletRequest). Struts will then automatically add the token to the form when the tag is rendered. When the post occurs the action should perform an Action.isValidToken(HttpServletRequest, true) to verify and invalidate the token. Any succeeding posts with the token will be cause isValidToken() to return false. I typically call Action.resetToken(HttpServletRequest) in any action that forwards to pages that will not alter state (session, db, ...).
We can write these methods inside Our Action Classes execte() method.The use of token in Struts is to prevent duplicate form submission due to the Back button. its NOT about resolving the double submit problem. After the user has logged out, none of the previous pages should even re-appear on the browsers. 2. Struts token is used to prevent double submits that could potentially occur after the user logs in and before the user logs out. You can prevent Refresh Button Problems. You can prevent going to back page using Back Button and submitting the same form. You can prevent just by entering the same URL and pressing enter button.

6. Can we create multiple struts configuration files in Struts web application ? If possible how to do that ?

We can combine some couple of Actions into a module and we can create a seperate struts configuration file in the struts web application. To do that we need to inform the web container through web.xml file init param Tag as follows.


7. What is the difference between Resultset and Rowset?

Difference between Resultset and Rowset
The interface that adds support to the JDBC API for the JavaBeansTM component model. A rowset, which can be used as a JavaBeans component
in a visual Bean development environment, can be created and configured at design time and executed at run time.

The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and
read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters
to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is
generally the case.

The RowSet interface supports JavaBeans events, allowing other components in an application to be notified when an event occurs on a
rowset, such as a change in its value.

The RowSet interface is unique in that it is intended to be implemented using the rest of the JDBC API. In other words, a RowSet implementation
is a layer of software that executes "on top" of a JDBC driver. Implementations of the RowSet interface can be provided by anyone,
including JDBC driver vendors who want to provide a RowSet implementation as part of their JDBC products.
A RowSet object may make a connection with a data source and maintain that connection throughout its life cycle, in which case it is called a
connected rowset. A rowset may also make a connection with a data source, get data from it, and then close the connection. Such a rowset
is called a disconnected rowset. A disconnected rowset may make changes to its data while it is disconnected and then send the changes back to
the original source of the data, but it must reestablish a connection to do so.

A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next
method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in
a while loop to iterate through the result set.

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from
the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code
fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by
others, and that is updatable. See ResultSet fields for other options.

8. How can you create a DataSource connection pool ?

<bean id="dataSource" 
<property name="driver">
           <property name="url">
           <property name="username">
           <property name="password">

9. How do you implement DynaValidatorForm in Struts ?

First you need to inform in Struts-Config.xml file.

You need not create a BeanClass with setters and getters. Its automatically created.

So using this form is very easy but have performance costs... <FORM-BEANS><FORM-BEAN name="submitQstnForm" type="org.apache.struts.validator.DynaValidatorForm">form-property  name="USER"  type="java.lang.String"/&gt;
</FORM-BEAN>import org.apache.struts.validator.DynaValidatorForm;
Inside Action Class you can access like this:
DynaValidatorForm submitQstnForm = (DynaValidatorForm)form;
String user = submitQstnForm.get("USER").toString();
String mail = submitQstnForm.get("MAIL").toString();
//Now play with the data.

10. How can you configure a bean to get DataSource from JNDI ?

<bean id="dataSource"               
<property name="jndiName">

Java J2ee Struts Hibernate Spring Interview Questions
1 2 3 4 5    Next
Menu - - Java J2ee Struts Spring Hibernate Interview Questions - A home for your website
Ads By Google