Friday, 13 July 2012

JDBC - Interview Questions(Part -II)


1. How will you retreive database warnings from a Connection object in JDBC?


//Retrieving warning from connection object
SQLWarning warning = conn.getWarnings();

//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();


2. How will you retreive database warnings from a Statement object in JDBC?


//Retrieving warning from statement object
stmt.getWarnings();

//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();



3. How will you retreive database warnings from a ResultSet object in JDBC?

//Retrieving warning from resultset object
rs.getWarnings();

//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();


4. What does the clearWarnings() method do?

A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object.

5. What happens when I try to call the getWarning() method on a connection/statement/resultset after it has been closed?

Trying to call the getWarning() method on either of these 3 objects after they are closed will cause an SQLException to be thrown.

6. Let us say that I just closed my Statement object so, I cannot access the getWarning() on my statement. Can I still access the getWarning() on my ResultSet?

No. Closing a Statement automatically closes the ResultSet connected to it. So, you will get the same SQLException if you try to do so.

7. What is DatabaseMetaData?

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Use DatabaseMetaData to find information about your database, such as its capabilities and structure.

8. How will you use the DatabaseMetaData? Can you write a sample example code?


DatabaseMetaData md = conn.getMetaData();
System.out.println("Database Name: " + md.getDatabaseProductName());
System.out.println("Database Version: " + md.getDatabaseProductVersion());
System.out.println("Driver Name: " + md.getDriverName());
System.out.println("Driver Version: " + md.getDriverVersion());


9. What is ResultSetMetaData?

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns.

10. How will you use the ResultSetMetaData? Can you write a sample example code?


ResultSet rs = stmt.executeQuery("SELECT * FROM TABLE_NAME");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);



11. What is rowset?

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet.

12. Why do we need a RowSet?

RowSet is a interface that adds support to the JDBC API for the JavaBeans 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. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet

13. What are the advantages of using RowSet over ResultSet?

There are two clear advantages of using RowSet over ResultSet:

* RowSet makes it possible to use the ResultSet object as a JavaBeans component.
* RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

14. What are the different types of RowSet ?
There are two types of RowSet are there. They are:
* Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.
* Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

15. Can you give an example of Connected RowSet?

A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver.

16. Can you give an example of Disconnected RowSet?

A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).

17. What are the benefits of having JdbcRowSet implementation?

The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet
* This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet 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.
* It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object.

18. What is the need of BatchUpdates feature in JDBC?

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single shot instead of multiple calls.

19. What is a DataSource?

A DataSource object is the representation of a source of data in the Java programming language.

In basic terms:
* A DataSource is a facility for storing data.
* DataSource can be referenced by JNDI.
* Data Source may point to RDBMS, file System , any DBMS etc..

Typically in enterprise application perspective, the term DataSource can be used interchangeably with a RDBMS database because in almost all cases, our DataSource will be pointing to an RDBMS database.

20. What are the advantages of DataSource?

The few advantages of using data source are :
* An application does not need to hardcode driver information, as it does with the DriverManager.
* The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details.
* The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.

21. What is the difference between a Statement and a PreparedStatement?

Some of the main differences between a statement & PreparedStatement are:


Statement PreparedStatment
A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
Statement has to verify its metadata against the database every time. A prepared statement has to verify its metadata against the database only once.
If you want to execute the SQL statement once go for STATEMENT If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries.
22. What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE in ResultSets?

Some of the main differences between a TYPE_SCROLL_INSENSITIVE & TYPE_SCROLL_SENSITIVE are:

TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE
An insensitive resultset is like the snapshot of the data in the database when query was executed. A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive. Since a trip is made for every ‘get’ operation, the performance drastically get affected.

JDBC - Interview Questions(Part -I)


1. What is the JDBC?

Java Database Connectivity (JDBC) is a standard Java API that is used to interact with relational databases from within a Java application. JDBC has set of classes and interfaces which can use from our Java application and interact with the database.

2. What are the Basic Steps in writing a Java program to connect to a database using JDBC?

The basic steps in connecting to a database using JDBC are:

1. Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded).
2. Open the connection to database which is then used to send SQL statements and get results back.
3. Create JDBC Statement object. This object contains SQL query.
4. Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
5. Process the result set.
6. Close the connection.

3. What are the main components of JDBC ?

The five main components of JDBC are:

1. Driver Manager
2. Driver
3. Connection
4. Statement &
5. ResultSet

4. How does a JDBC application work?

A JDBC application can be logically divided into two layers:
1. Driver layer
2. Application layer

First the Driver layer consists of DriverManager class and the available JDBC drivers. The application begins with requesting the DriverManager for the connection. An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer. The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.


5. How do I load a database driver with JDBC 4.0 / Java 6?

Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.

Remember - if the correct JAR Files are missing in the classpath, this auto feature will not work

6. What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver so that the Java classes that connect to the database can use them.

7. What does the connection object represents?

The connection object represents a literal connection or a communication context through which our Java code can interact with a database. i.e., all communication with database is through connection object only.

8. What is a Statement?

The Statement acts like a vehicle through which SQL commands can be sent. You can create a Statement as follows:

Statement stmt = conn.createStatement();


This method returns an object which implements statement interface which can be executed.

9. What is a PreparedStatement?

A prepared statement is an SQL statement that is precompiled by the database. It is a sub-set of the Statement. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

You can create a prepared statement as follows:

PreparedStatement pstmt = conn.prepareStatement("UPDATE Emp_Salary SET Salary = ? WHERE Emp_Id = ?");
pstmt.setBigDecimal(1, 75000.00);
pstmt.setInt(2, 12345);


Note that conn is an instance of the collection class and the "?" represent the parameters that are to be passed to the query/prepared statement before it can be executed.


10. What are callable statements?

Callable statements are used from JDBC application to invoke stored procedures and functions objects of a database.

11. Can you call a stored procedure using JDBC? If so, how?

Yes, you can call Stored Procedures using JDBC. we have to use the CallableStatement to do so.

Example:


CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");


Here conn is an instance of the Connection class.

12. How many types of JDBC drivers are there and What are they?

There are four types of drivers defined by JDBC as follows:
1. Type 1 – JDBC-ODBC Bridge
2. Type 2 – Native API (Partly Java) Driver
3. Type 3 – Net-Protocol Fully Java Driver
4. Type 4 – Pure Java Driver

Type 4 JDBC driver is most preferred kind of approach in JDBC.

13. Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.

14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

15. What are the standard transaction isolation levels defined by JDBC?

The values are defined in the class java.sql.Connection and are:

TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE

You need to double check that the database you are connecting to, supports these isolation levelts.

16. What is a ResultSet?

The ResultSet represents set of rows retrieved due to query execution. You get a result set object as the output when you execute a query using the Statement or the PreparedStatement objects.
Example:

ResultSet rs = stmt.executeQuery(sqlQuery);


17. What are the types of resultsets?

JDBC supports 3 types of ResultSets. They are:

1. TYPE_FORWARD_ONLY
2. TYPE_SCROLL_INSENSITIVE and
3. TYPE_SCROLL_SENSITIVE

18. What are the types of statements in JDBC?

The JDBC API has 3 types of Statement Interfaces. They are:

1. Statement
2. PreparedStatement
3. CallableStatement

19. What are the differences/key features between the 3 different types of Statements in JDBC?

Statement
* This interface is used for executing a static SQL statement and returning the results it produces.
* The object of Statement class can be created using Connection.createStatement() method.

PreparedStatement
* A SQL statement is pre-compiled and stored in a PreparedStatement object.
* This object can then be used to efficiently execute this statement multiple times.
* The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface.

CallableStatement
* This interface is used to execute SQL stored procedures.
* This extends PreparedStatement interface.
* The object of CallableStatement class can be created using Connection.prepareCall() method.

20. What is Connection pooling? What are the advantages of using a connection pool?

Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database. Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool. Apart from performance this also saves you resources as there may be limited database connections available for your application.

21. What does the Class.forName() method do?

Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName('MyClass') is going to do following
- Load the class MyClass.
- Execute any static block code of MyClass.
- Return an instance of MyClass.

JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this

Class.forName("org.mysql.Driver");

All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this:

static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}

Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager.

22. When to use a PreparedStatement and when to use a Statement?

Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

There are few advantages of using PreparedStatements over Statements
* Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster.
* In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.
* SQL injection attacks on a system are virtually impossible while using PreparedStatements.

23. What do you mean by the term pre-compiled from a PreparedStatemnet perspective?

The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution which makes it much faster than executing a fresh query that has to be compiled before execution.

24. What does setAutoCommit(false) do?

A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode manually as follows:

con.setAutoCommit(false);


Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method as follows:


con.commit();


Alternately, if you want to ensure that all further transactions/queries are auto-committed then you can enable auto-commit as follows:

con.setAutoCommit(true);


25. What are database warnings and How can I get them?

Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects.

The call to the getWarnings() method of either of these objects retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously.









JSP - Interview Questions(Part - I)

Question 1: Explain include Directive and include Action of JSP
Ans:  This is a very popular interview question on JSP, which has been asked from long time and still asked in various interview. This question is good to test some fundamental concept like translation of JSP and difference between translation time and run time kind of concept.

Syntax for include Directive is <%@ include file="fileName" %> which means we are including some file to our JSP Page when we use include directive contents of included file will be added to calling JSP page at translation time means when the calling JSP is converted to servlet ,all the contents are added to that page .one important thing is that any JSP page is complied if we make any changes to that particular page but if we have changed the included file or JSP page the main calling JSP page will not execute again so the output will not be according to our expectation, this one is the main disadvantage of using the include directive that why it is mostly use to add static  resources, like Header and footer .

Syntax for include action is <jsp:include page=”relativeURL” /> it’s a runtime procedure means the result of the JSP page which is mentioned in relative URL is appended  to calling JSP at runtime on their response object at the location where we have used this tag
So any changes made to included page is being effected every time, this is the main advantage of this action but only relative URL we can use here ,because request and response object is passed between calling JSP and included JSP.

Question 2: Difference Between include Directive and include Action of JSP
This JSP interview question is a continuation of earlier question I just made it a separate one to write answer in clear tabular format.

Include Directive
Include Action
include directive is processed at the translation time
Include action is processed at the run time.
include directive can use relative or absolute path
Include action always use relative path
Include directive can only include contents of resource it will not process the dynamic resource
Include action process the dynamic resource and result will be added to calling JSP
We can not pass any other parameter
Here we can pass other parameter also using JSP:param
We cannot  pass any request or response object to calling jsp to included file or JSP or vice versa
In this case it’s possible.


Question 3: Is it possible for one JSP to extend another java class if yes how?

Ans: Yes it is possible we can extends another JSP using this <%@ include page extends="classname" %> it’s a perfectly correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage interface, so for jsp page its possible to extend another java class . This question can be tricky if you don’t know some basic fact J, though its not advisable to write java code in jsp instead its better to use expression language and tag library.

Question 4: What is < jsp:usebean >tag why it is used.


Ans: This was very popular JSP interview question during early 2000, it has lost some of its shine but still asked now and then on interviews.

JSP Syntax
<jsp:useBean
        id="beanInstName"
        scope="page | request | session | application"
       
            class="package.class"    type="package.class"

           </jsp:useBean>

This tag is used to create a instance of java bean first of all it tries to find out the bean if bean instance already exist assign stores a reference to it in the variable. If we specified type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is simple way to create a java bean.
Example:
     
<jsp:useBean id="stock" scope="request" class="market.Stock" />
<jsp:setProperty name="bid" property="price" value="0.0" />
a <jsp:useBean> element contains a <jsp:setProperty> element that sets property values in the Bean,we have <jsp:getProperty>element also to get the value from the bean.

Explanation of Attribute

 id="beanInstanceName"
A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.
scope="page | request | session | application"
The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:
  • page – we can use the Bean within the JSP page with the <jsp:useBean> element
  • request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.
  • session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean exists across the entire session, and any page that participates in the session can use it..
  • application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.
class="package.class"
Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor.
type="package.class"
If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

Question 5: How can one Jsp Communicate with Java file.

Ans:we have import tag <%@ page import="market.stock.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is  servlet can send  the instance of the java class to our  jsp and we can retrieve that object from the request obj and use it in our page.

Question 6: what are the implicit Object

Ans: This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

They are: request, response, pageContext, session, and application, out, config, page, and exception.

Question 7: In JSP page how can we handle runtime exception?

Ans: This is another popular JSP interview question which has asked to check how candidate used to handle Error and Exception in JSP. We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.

Example: <%@ page errorPage="error.jsp" %>

It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>


Question 8: Why is _jspService() method starting with an '_' while other life cycle methods do not?

Ans: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we cant override this method.


Question 9: How can you pass information form one jsp to included jsp:

Ans: This JSP interview question is little tricky and fact based. Using < Jsp: param> tag we can pass parameter from main jsp to included jsp page

Example:
<jsp:include page="newbid.jsp" flush="true">
<jsp:param name="price" value="123.7"/>
<jsp:param name="quantity" value="4"/>

Question 10: what is the need of tag library?

Ans tag library is a collection of custom tags. Custom actions helps recurring tasks will be handled more easily they can be reused across more than one application and increase productivity. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services. Some of the popular tag libraries are Apache display tag library and String tag library. You can also check my post on display tag library example on Spring.


Q1) What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation phase?
Ans) JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(â€Å“….. â€?) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

The JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send response.

Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application server tools/settings or by writing your own script.
Q2) Explain the life cycle methods of a JSP?
Ans) Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.
Q3) What are different type of scripting elements?
Ans)
Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Important: declaring variables via this element is not thread-safe, because this variable ends up in the generated Servlet as an instance variable, not within the body of the _jspservice() method. Ensure their access is either read-only or synchronized.

Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date()>

Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method.
(Note: Not recommended to use Scriptlet elements because they don̢۪t provide reusability and maintainability. Use custom tags (like JSTL, JSF tags, etc) or beans instead).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>


Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />

Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=�java.util.Date� %>
<%@ include file=�myJSP� %>
<%@ taglib uri=�tagliburi� prefix=�myTag�%>

Q4) What are the different scope values or what are the different scope values for "jsp:usebean"?
Ans)
Scope
Object
Comment
Page
PageContext
Available to the handling JSP page only.
Request
Request
Available to the handling JSP page or Servlet and forwarded JSP page or Servlet.
Session
Session
Available to any JSP Page or Servlet within the same session.
Application
Application
Available to all the JSP pages and Servlets within the same Web Application.
Q5) What are the differences between static and a dynamic include?
Ans)
Static <%@include%>
Dynamic include <include....>
During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.
The dynamically included JSP is compiled into a separate Servlet. It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response.
No run time performance overhead.
Has run time performance overhead.
Q6) Is JSP variable declaration thread safe?
Ans) No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared.
<% int a = 5 %>;
Q7) Explain JSP URL mapping? What is URL hiding or protecting the JSP page?
Ans) The JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a servlet who is responsible for authenticating and authorising the user before returning the protected JSP page or its resources.
Q8) What are custom tags? Explain how to build custom tags?
Ans) Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web development.
Step 1
Create a Custom tag class using only doStartTag()
 package myTagPkg;
  public class MyTag extends TagSupport
   {
    int attr = null;
    public int setAttr(int a ttr){this.attr = a ttr}
    public int getAttr(){return attr;}
    public int doStartTag() throws JspException {
    .......
    return 0;
    }
    public void release(){.....}
   }

Step 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The code sample MyTagDesc.tld is shown below:
<taglib>
  <tag>
   <name>tag1</name>
   <tagclass>myTagPkg.MyTag</tagclass>
   <bodycontent>empty</bodycontent>
   <attribute>
    <name>attr</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
   </attribute>
  </tag>
</taglib>

Step 3
The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The code sample web.xml file is shown below:
 <web-app>
  <taglib>
   <taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
   <taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
  </taglib>
 </web-app>

STEP: 4 The JSP file declares and then uses the tag library as shown below:
<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=�abc� />
<taglib>
  <tag>
   <name>tag1</name>
   <tagclass>myTagPkg.MyTag</tagclass>
   <bodycontent>empty</bodycontent>
   <attribute>
    <name>attr</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
   </attribute>
  </tag>
</taglib>

Struts - Interview Questions(Part -I)

Question 1: What is Struts? Why you have used struts in your application or project.

Ans: This is the first interview questions anyone asks in Struts to get the interview rolling. Most commonly asked during less senior level. Struts is nothing but open source framework mostly used for making web application whenever we use the term framework means it comprises JSP ,servlet ,custom tags message resources all in one bundle which makes developer task very easy. Its is based on MVC pattern which is model view Controller pattern.

Now why we use Struts? So main reason is if we go with servlet all HTML code which is related with design part mostly will come inside java code which makes code unmaintainable and complex similarly if use JSP, all java code related with business come inside design part which again make code complex, that’s why MVC pattern come into existence and which separate the business, design and controller and struts was made based upon this pattern and easy to develop web application. The keyword to answer this Struts interview questions is MVC design pattern, Front Controller Pattern and better flow management which mostly interviewer are looking to hear. You can read more design pattern interview question on my post 

Question 2: What are the main classes which are used in struts application?
Ans 2: This is another beginner’s level Struts interview question which is used to check how familiar candidate is with Struts framework and API. Main classes in Struts Framework are:

Action servlet: it’s a back-bone of web application it’s a controller class responsible for handling the entire request.
Action class: using Action classes all the business logic is developed us call model of the application also.
Action Form: it’s a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is automatically populated on the server side with data entered from a form on the client side.
Action Mapping: using this class we do the mapping between object and Action.
ActionForward: this class in Struts is used to forward the result from controller to destination.

Question 3: How exceptions are handled in Struts application?

Ans: This is little tough Struts interview question though looks quite basic not every candidate knows about it. Below is my answer of this interview questions on Struts:

There are two ways of handling exception in Struts:

Programmatically handling: using try {} catch block in code where exception can come and flow of code is also decided by programmer .its a normal java language concept.

Declarative handling: There are two ways again either we define <global-Exception> tag inside struts config.xml file

<exception

      key="stockdataBase.error.invalidCurrencyType"

      path="/AvailbleCurrency.jsp"

      type="Stock.account.illegalCurrencyTypeException">
</exception>

Programmatic and Declarative way is some time also asked as followup questions given candidate’s response on knowledge on Struts.

Key: The key represent the key present in MessageResource.properties file to describe the exception.
Type: The class of the exception occurred.
Path: The page where the controls are to be followed is case exception occurred.

Question 4: How validation is performed in struts application?

Ans: Another classic Struts interview question it’s higher on level than previous interview questions because it’s related to important validation concept on web application. In struts validation is performed using validator framework, Validator Framework in Struts consist of two XML configuration files.

1. validator-rules.xml file: which contains the default struts pluggable validator definitions. You can add new validation rules by adding an entry in this file. This was the original beauty of struts which makes it highly configurable.
2. Validation.xml files which contain details regarding the validation routines that are applied to the different Form Beans.

These two configuration file in Struts should be place somewhere inside the /WEB-INF folder of the application to keep it safe from client and make it available in Classpath.

<!--  Validator plugin -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  <set-property
  property="pathnames"
   value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

Now the next step towards validation is create error messages inside the message resource property file which is used by validator framework.
Message resource Contain:
1. CurrencyConverterForm.fromCurrency = From Currency
2. CurrencyConverterForm.toCurrency=To currency
3. errors.required={0} is required.

Then validation rules are defined in validation.xml for the fields of form on which we want desire validation

Form bean code that extend DynaValidatorForm
Eg; <form-beans>
<form-bean name="CurrencyConverterForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="fromCurrency" type="java.lang.double" />
<form-property name="toCurrecny" type="java.lang.double" />
</form-bean>
</form-beans>

Validation.xml file contains

<form-validation>
<formset>
<form name=" CurrencyConverterForm ">
<field property=" fromCurrency " depends="required">
<arg key=" CurrencyConverterForm. fromCurrency "/>
</field>
<field property=" toCurrecny " depends="required ">
<arg key=" CurrencyConverterForm.toCurrency "/>
</field>
</form>
</formset>
</form-validation>

To associate more than one validation rule to the property we can specify a comma-delimited list of values. The first rule in the list will be checked first and then the next rule and so on. Answer of this Struts questions gets bit longer but it’s important to touch these important concept to make it useful.

Question 5: What is the Difference between DispatchAction and LookupDispatchAction in Struts Framework?

This Struts interview questions is pretty straight forward and I have put the differences in tabular format to make it easy to read.


Dispatch Action
LookupDispatchAction

It’s a parent class of  LookupDispatchAction
Subclass of Dispatch Action
DispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create separate actions for each function.
An abstract Action that dispatches to the subclass mapped executes method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping.
If not using Internalization functionality then dispatch action is more useful.

Lookup Dispatch Action is useful when we are using Internalization functionality

DispatchAction selects the method to execute depending on the request parameter value which is configured in the xml file.
LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method.
DispatchAction is not useful for I18N

LookupDispatchAction is used for I18N




Question 6: How you can retrieve the value which is set in the JSP Page in case of DynaActionForm?

Ans: DynaActionForm is a popular topic in Struts interview questions. DynaActionForm is subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

For Example: we have a CurrencyConverterForm and we don't want a java class.
CurrencyConverterForm has properties fromCurrency, toCurrency

in the struts-config.xml file, declare the form bean

<form-bean name=" CurrencyConverterForm "
type="org.apache.struts.action.DynaActionForm">
<form-property name=" fromCurrency " type="java.lang.String"/>
<form-property name=" toCurrency " type="java.lang. String "/>
</form-bean>

Add action mapping in the struts-config.xml file:

<action path="/convertCurrency" type="com.techfaq.action.ConvertCurrencyAction"
name=" CurrencyConverterForm "
scope="request"
validate="true"
input="/pages/ currencyConverterform.jsp">

<forward name="success" path="/jsp/success.jsp"/>
<forward name="failure" path="/jsp/error.jsp" />

</action>

In the Action class.

public class ConvertCurrencyAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{

DynaActionForm currencyConverterForm = (DynaActionForm)form;

// by this way we can retrieve the value which is set in the JSP Page

String fromCurrency = (String) currencyConverterForm.get("fromCurrency ");
String toCurrency = (String) currencyConverterForm.get("toCurrency ");
return mapping.findForward("success");
}
}
}

In the JSP page

<html:text property=" fromCurrency " size="30" maxlength="30"/>
<html:text property=" toCurrency " size="30" maxlength="30"/>


Question 7: what the Validate () and reset () method does?

Ans: This is one of my personal favorite Struts interview questions. validate() : validate method is Used to validate properties after they have been populated, and this ,method is  Called before FormBean is passed  to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
                        
ActionErrors errors = new ActionErrors();
if ( StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){
     errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.usernamepassword.required"));
}
return errors;
}

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

Example :
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.password = null;
this.username = null;
}

Set null for every request.

Question 8: How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Ans: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < message-resources / > tag. Example: < message-resources parameter= MessageResources / >

Message resource definition files can available to the struts environment in two ways
1. using web.xml as
<servlet>
<servlet-name>action<servlet-name>
servlet-class>org.apache.struts.action.ActionServlet<servlet-class>
<init-param>
<param-name>application<param-name>
<param-value>resource.Application<param-value>
</servlet>

2.
<message-resource key="myResorce" parameter="resource.Application" null="false">

Question 9: What configuration files are used in Struts?
Ans: ApplicationResources.properties and struts-config.xml these two files are used to between the Controller and the Model.

Question 10: Explain Struts work Flow?
Ans: Some time this Struts interview questions asked as first questions but I recall this now J . Here is the answer of this Struts interview questions
1) A request comes in from a Java Server Page into the ActionServlet.
2) The ActionServlet having already read the struts-config.xml file, knows which form bean relates to this JSP, and delegates work to the validate method of that form bean.

3) The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that need to be performed.

4) If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields returns back to the ActionServlet.

5) The ActionServlet checks the ActionErrors that were returned from the form beans validate method to determine if any errors have occurred. If errors have occurred, it returns to the originating JSP displaying the appropriate errors.

6) If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class.

7) The Action class performs any necessary business logic, and then forwards to the next appropriate action (probably another JSP).



Are Struts's action classes Thread-safe?
Yes. Action classes are based on "one-instance and many-threads". This is to conserve resources and to provide the best possible throughput.

What are the various Struts Tag libraries?
There are various struts tags. But the most-repeated tags are:
struts-bean.tld
struts-html.tld
struts-logic.tld
struts-nested.tld

What is ActionMapping in struts?
Action mapping defines the flow of one request. The possible sequence is
User -> request -> Form -> Validation -> Business Code -> Forward -> JSP -> response -> User.
The components involved are Action classes, Forms and JSP.

What are the advantages of having multiple struts-config in the same application?
The implementation with many struts-config is to organize the development work, so that many people may be involved and it is some organized way of doing things. But this would result in some compromise in performance(speed). Technically there is no any difference between single and multiple struts-config files.

What are the ways in which resource file can be used in struts?
Defining message resources in struts-config file.
Programmatically using resource files in Java classes or in JSP files.

Explain the term 'architecture of the application'?
Architecture is the set of rules (or framework) to bring in some common way of assembling or using J2EE components in the application. This helps in bringing consistency between codes developed by various developers in the team.

Which is the architecture followed by struts?
Struts follows MVC architecture.

What are components corresponding o M, V and C in struts?

Model : The model represents the data of an application. Anything that an application will persist becomes a part of model. The model also defines the way of accessing this data ( the business logic of application) for manipulation. It knows nothing about the way the data will be displayed by the application. It just provides service to access the data and modify it. Here 'Form Bean' represents Model layer.

View : The view represents the presentation of the application. The view queries the model for its content and renders it. The way the model will be rendered is defined by the view. The view is not dependent on data or application logic changes and remains same even if the business logic undergoes modification. JSP represents View Layer.

Controller : All the user requests to the application go through the controller. The controller intercepts the requests from view and passes it to the model for appropriate action. Based on the result of the action on data, the controller directs the user to the subsequent view. Action classes (action servlets) represent Controller layer.

Differentiate between the terms 'Design Patterns', 'Framework' and 'Architecture'.
Design Pattern: The various solutions arrived at for the known problem. This helps to avoid re-inventing the wheel. The risk-free solution can be easily used by others. For example, singleton is the design pattern that you can use instantly to enfore one object per class. You do not need to think of this on your own.
Framework: A framework is a structure or set of rules, used to solve or address complex issues. It is basically a reusable designf for the J2EE applications. For example, Struts, JSF,etc., are the frameworks. You can use these frameworks based on the requirements of your application and each has its own set of advantages.

Architecture: It is a design that describes how the various components in the application fit together. For example, MVC is an architecture which is helpful to define how the components interact within the application.


What is the difference between ActionForm and DynaActionForm?
In action form, you need to define the form class that extends ActionForm explicitly, whereas you can define the form dynamically inside the struts-config file when using DynaActionForm.

How can you use Validator framework in struts?Validator Frameworks are helpful when the application needs server-side validation such that the particular set of validations occur very frequently within the same application. This avoids writing complex code in validation() method in every form bean. Using validator framework, there are different pre-written validations in place. You can customize these validations in XML file.

What are client-side and server-side vaidations?
Client-side validations: These are the validations that id done using javascripts. There is always a danger involved that the user can get through (crack-through) these validations. But for some simple validations, like converting lower-case to upper-case or date validations can be done, you can use javascripts.
Server-side validations: These are the validations done in server-side using Java components (Form bean or in business logics) where the user has no chance to crookedly get through the system.

What are the advantages & differences between using validate() method in form over validations using validator framework.
Refer to the previous-answer.

Define the terms authentication and authorisation.
Authentication is the process/rule that validates if the user is allowed to access the system or not.
Authorization is the process/rule that validates if the user is allowed to access the particular part of the system or not. This occurs after user's successful authentication.

What are the components provided in J2EE to perform authentication and authorization?Authentication – RequestProcessor and/or Filter.
Authorization - DTO, JDO or Java or Action classes.

Give the difference between between 'DispatchAction' and 'Action'.
A DispatchAction contains various different methods other than the standard execute() method in Action classes. These methods are executed based on some request parameter. For example, you can code in such a way that three buttons (namely Insert, Delete, Update) buttons correspond to different methods such as insert(), delete() and udpate(). The submit button in JSP would have the property that has the value which matches to any one of the methods defined in DispatchAction class.

What is pagination technique? How can you design them in struts?
Pagination is the technique where the bulk of results are split into different pages and only the information where the user can conveniently see are displayed in a page. (Like in Goooooogle). This can be achieved in many ways, but the simplest method is to have a query string (say http://www.testwebsite?pageNumber=2) would lead to information corresponding to resultset rows from 11 to 20. Assuming that you want to display 10 related rows of information, you can set the formula as follows:
Starting row = (pageNumber-1) * + 1 which is equal to 11.
Ending row = Starting row + which is equal to 20.

How can you populate the drop-down list using form properties?
There are many ways for this. But the best method is to use which defines collection that needs to be used to populate the drop-down list, the property to store the selected value and the collection that is used to display the labels (what we see in JSP page). For Example,

html:options collection="form-collection-property"
property="form-property"
labelProperty="form-another-collection-property"

What is the XML parser provided in struts? Can you use it for other purposes?
'Digester' framework. Yes we can use for our applications to store and parse our application-related data.

Difference between Struts 1.0 and 1.1
  • Perform() method was replaced by execute()
  • DynaActionForms are introduced.
  • Tiles Concept is introduced
  • We can write our own Controller by Inheriting RequestProcessor