JavaScript Interview Questions for both Experienced Programmers and Freshers

1) What is JavaScript?
Ans:JavaScript is a scripting language most often used for client-side web development.

2) What is the difference between JavaScript and Jscript?
Ans:Both JavaScript and Jscript are almost similar. JavaScript was developed by Netscape. Microsoft reverse engineered Javascript and called it JScript.

3) How do we add JavaScript onto a web page?
Ans:There are several way for adding JavaScript on a web page, but there are two ways which are commonly used by developers
If your script code is very short and only for single page, then following ways are the best:
a) You can place <script type="text/javascript"> tag inside the <head> element.

Collapse | Copy Code
<title>Page Title</title>
<script language="JavaScript" type="text/javascript">
   var name = "Vikas Ahlawta"

b) If your script code is very large, then you can make a JavaScript file and add its path in the following way:

Collapse | Copy Code
<title>Page Title</title>
<script type="text/javascript" src="myjavascript.js"></script>

4) Is JavaScript case sensitive?
A function getElementById is not the same as getElementbyID.

5) What are the types used in JavaScript?
Ans:String, Number, Boolean, Function, Object, Null, Undefined.

6) What are the boolean operators supported by JavaScript? And Operator: &&
Or Operator: ||
Not Operator: !

7) What is the difference between “==” and “===”?
“==” checks equality only,
“===” checks for equality as well as the type.

8) How to access the value of a textbox using JavaScript?
Ans: ex:-

Collapse | Copy Code
<!DOCTYPE html>
Full name: <input type="text" id="txtFullName" 
name="FirstName" value="Vikas Ahlawat">

There are following ways to access the value of the above textbox:

Collapse | Copy Code
var name = document.getElementById('txtFullName').value;



we can use the old way:

Collapse | Copy Code

var name = document.forms[0].FirstName.value;


Note: This uses the “name” attribute of the element to locate it.

9) What are the ways of making comments in JavaScript?

Collapse | Copy Code
// is used for line comments
ex:- var x=10; //comment text

*/  is used for block comments


Collapse | Copy Code
var x= 10; /* this is
block comment example.*/

10) How will you get the Checkbox status whether it is checked or not?

Collapse | Copy Code
var status = document.getElementById('checkbox1').checked; 

will return true or false.

11) How to create arrays in JavaScript?
Ans:There are two ways to create array in JavaScript like other languages:

a) The first way to create array
Declare Array:

Collapse | Copy Code
var names = new Array(); 
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";

b) This is the second way:

Collapse | Copy Code
var names = new Array("Vikas", "Ashish", "Nikhil");

12) If an array with name as “names” contain three elements, then how will you print the third element of this array?
Ans: Print third array element document.write(names[2]);
Note:- Array index starts with 0.

13) How do you submit a form using JavaScript?
Ans:Use document.forms[0].submit();

14) What does isNaN function do?
Ans: It returns true if the argument is not a number.

Collapse | Copy Code
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");

The output will be:

Collapse | Copy Code

15) What is the use of Math Object in JavaScript?
Ans: The math object provides you properties and methods for mathematical constants and functions.

Collapse | Copy Code
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90);    Returns the sine of 90

16) What do you understand by this keyword in JavaScript?
Ans: In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

Collapse | Copy Code
var obj = { outerWidth : 20 };

function say() {

say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth

17) What does “1″+2+4 evaluate to?
Ans: Since 1 is a string, everything is a string, so the result is 124.

18) What does 3+4+”7″ evaluate to?
Ans: Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it is concatenation, so 77 is the result.

19) How do you change the style/class on any element using JavaScript?

Collapse | Copy Code
document.getElementById(“myText”).style.fontSize = “10";


Collapse | Copy Code
document.getElementById(“myText”).className = “anyclass”;

20) Does JavaScript support foreach loop?
Ans: JavaScript 1.6(ECMAScript 5th Edition) support foreach loop,

See example here

21) What looping structures are there in JavaScript?
Ans: for, while, do-while loops

22) What is an object in JavaScript, give an example?
Ans: An object is just a container for a collection of named values:

// Create the man object

Collapse | Copy Code
var man = new Object(); = 'Vikas Ahlawat'; = true;
man.age = 27;

23) How you will add function as a property in a JavaScript object? Give an example.

Collapse | Copy Code
var man = new Object(); = 'Vikas Ahlawat'; = true;
man.age = 27;
man.getName = function() { return;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.

24) What is the similarity between the 1st and 2nd statement?
1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans: Both will call String() constructor function
You can confirm it by running the following statement:

Collapse | Copy Code
console.log(myString.constructor, myStringLiteral.constructor);

25) What will be the output of the following statements?

Collapse | Copy Code
var myString = 'Vikas' // Create a primitive string object.
var myStringCopy = myString; // Copy its value into a new variable.
var myString = null; // Manipulate the value
console.log(myString, myStringCopy);
Ans: // Logs 'null Vikas'

26) Consider the following statements and tell what would be the output of the logs statements?

Collapse | Copy Code
var price1 = 10;
var price2 = 10;
var price3 = new Number('10'); // A complex numeric object because new was used.
console.log(price1 === price2); 
console.log(price1 === price3);


Collapse | Copy Code
console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3 
contains a complex number object and price 1
is a primitive value. */

27) What would be the output of the following statements?

Collapse | Copy Code
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);

Ans: // Logs false, JavaScript does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same object (i.e., have the same address). Two variables containing identical objects are not equal to each other since they do not actually point at the same object.

28) What would be the output of the following statements?

Collapse | Copy Code
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);

Ans: // Logs true

29) What is this?

Collapse | Copy Code
var myArray = [[[]]];

Ans: Three dimensional array

30) Name any two JavaScript functions which are used to convert nonnumeric values into numbers?

Collapse | Copy Code
Collapse | Copy Code
var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //NaN

31) Does JavaScript Support automatic type conversion, If yes give example.

Ans: Yes! Javascript support automatic type conversion. You should take advantage of it, It is most common way of type conversion used by Javascript developers.


Collapse | Copy Code
var s = '5';
var a = s*1;
var b = +s;
typeof(s); //"string"
typeof(a); //"number"
typeof(b); //"number"

Drupal Interview Questions and Answers

1. Why do you think Drupal is powerful & popular CMS compare to others?

Drupal Allows to create multiple content types using content construction kit (cck) without any programming skills. Also allows customize theme template for each content type. For example you can have page, article , story, slideshow content type.

2. What makes “Search” in drupal as an excellent feature than Other CMS?

Drupal uses search indexing using content type, classification information from taxonomy system and the content meta data.

Drupal treats its content as fine-grained semantic information that Drupal knows about can be used to fine-tune search results.

Also, you can tweak and override the search system to adjust the user interface, the way content is ranked, and the way results are displayed. That said, Drupal integrates well with external search engines such as Apache Solr, Xapian, and Sphinx if the built-in search does not meet your needs very easily.

3. What is a Module in drupal ?

A module is software (code) that extends Drupal features and/or functionality. Drupal Supports – Core modules – included with the main download of Drupal, and you can turn on their functionality without installing additional software. Contributed modules are downloaded from the Modules download section of, and installed within your Drupal installation. You can also create your own module – CustomModules” using PHP programming, and Drupal’s module API.

4. What modules do you always recommend and why?

  • Views - This module is essential in every website I build. It makes displaying lists of content very easy. If you want an image slideshow, a list of blog posts, a list of products, etc., views is the best place to start.
  • Panels - Panels gives you the ability to create custom pages easily. These custom pages can have multiple regions of content. For example, you may want to create a home page that has a Slideshow on the top, and a two column layout below.
  • Ctools - On its own, Ctools does not seem to do a lot. However, it is actually a very powerful framework if you begin developing your own modules. I have used Ctools in the past for developing multi-step forms, modal dialog boxes, and even multi-step forms inside of modal dialog boxes.
  • Token - Tokens are little snippets of text that can be used as replacement patterns. For example, if your website sends out emails and you want to add in the users name, or you want fill in a link path with a node id to provide a helpful link to content, tokens will save the day.
  • Pathauto - The Pathauto module is a necessity for any website that frequently adds new content. It is also especially important if you have a website that allows users to create content using content types. Pathauto simplifies creating clean and search engine friendly URLS for the various content you add to your site.
  • Webform - If you want to provide easy to fill out forms for the visitors of your site, the Webform module will help you out.
  • Rules - Drupal rules will allow you to set up condition actions.
  • Date - This is useful for allowing the easy selections of dates in content types (with a nice date popup). It also integrates nicely with the views module.
  • Quicktabs - Makes it easy to add tabbed content without having to write your own Javascript/Jquery. What more do I have to say?
  • Libraries - Makes organizing your various libraries of functionality easy (see Jquery UI above for an example).
  • Google Analytics - I don’t build a Drupal website without adding Google Analytics. This module makes it very simple. What gets measured, gets improved after all.

5. What are hooks in Drupal ?
hooks are drupal api code which allows module to interact with the Drupal core.
Drupal’s module system is based on the concept of “hooks”. A hook is a PHP function that is named foo_bar(), where “foo” is the name of the module (whose file name is thus foo.module) and “bar” is the name of the hook. Each hook has a defined set of parameters and call back functions to trigger functionality on specific event.  For example if you use form with submit button, on submit event you can have specific functionality.

6. How does caching work in Drupal?

Drupal caching system allows customized settings to speed up website using different configuration with page caching, block caching and lifetime for cached pages.

Page caching:

  • If enables, page caching will only be used for anonymous users.
  • If you enable page caching, the entire HTML of each page will be stored in the database. This significantly reduces the amount of queries needed.
  • This automatically means that blocks will also get cached, disregarded their own cache settings.
  • If Varnish is configured, this will also enable varnish caching
  • The page cache max-age will be used (see below) for each page.
  • You can check the “X-Drupal-Cache” HTTP header to check if this cache is HIT.

Block caching:

  • If you enable block caching, without enabling page caching, the block cache settings will be used (for anonymous and authenticated).
  • The defaults for most blocks is “don’t cache” because that is the default for blocks who don’t have their cache settings specifically declared.
  • You can use block_cache_alter module to set this for each block.
  • When it’s block created by Views, you can set the cache settings for a block in Views.

Minimum cache lifetime:

  • This is the amount of time before the page cache is cleared.
  • Page caches are cleared on each cron run (system_cron).
  • Be warned: incorrect settings of your cron and this setting might kill your website performance. See also this issue.

Expiration of cached pages:

  • This only applies for external caching mechanisms, for example your browser cache or Varnish.
  • It sets the Cache-Control max-age value in the HTTP-HEADERS.
  • This setting only takes effect when page caching is turned on.

7. How database system of Drupal works ?

In Drupal, each type of information has its own database table. For instance, the basic information about the nodes of your site are stored in the Node table, Comments and Users also have their own database tables, and roles, permissions, and other settings are also stored in database tables.

8. What is Database abstraction layer in Drupal ?

Allow the use of different database servers using the same code base.
Drupal provides  an abstraction layer  with the ability to support multiple database servers easily. The intent of this layer is to preserve the syntax and power of SQL as much as possible, while letting Drupal control the pieces of queries that need to be written differently for different servers and provide basic security checks.
Most Drupal database queries are performed by a call to db_query() or db_query_range(). Module authors should also consider using pager_query() for queries that return results that need to be presented on multiple pages, and tablesort_sql() for generating appropriate queries for sortable tables.

9. How do you handle upgrades?

Steps to Upgrade drupal minor version.

  • backing up the site,
  • putting it into maintenance mode
  • downloading the new version of the module
  • uncompressing it
  • running update.php
  • testing the site
  • taking the site out of maintenance mode

Steps to Upgrade Drupal major version.

  • Backup your existing site and database.
  • Log in as user ID 1
  • Put your site in maintenance mode
  • Change all themes to Garland
  • Disable non-core modules
  • Remove default settings file
  • Remove all old core files and directories
  • Remove uninstalled modules
  • Download Drupal 7
  • Re-apply modifications to core files
  • Make your settings.php file writeable
  • Run the update script
  • Backup your database
  • Upgrade fields
  • Update contrib modules and themes
  • Check the Status Report
  • Make sure settings.php is secure
  • Check Drupal Core Modules
  • Remove your site from Maintenance Mode

10. How to debug code in Drupal?

Simple using print_r or var_export , you can debug code within Drupal.
$node = node_load(123);
Drupal devel module provides dsm and dpm functions to debug code within drupal.
$node = node_load(123);
drupal latest version provides debug inbuilt function to print errors, notices and warnings as well.This could be in the page or in the logs depending on how php is configured.
For example,
$node = node_load(123);
The full options for debug function are:
debug($data, $label, $print_r);
The $data is pretty self explanatory. It can be anything you could pass through print_r or var_export. The $label allows for a custom label to be added. This is ideal when you are sending the information to a log and you want a key to search the logs for. The 3rd argument is whether to use print_r or var_export. The default is var_export. If you are interested between the two I’d suggest reading the manual pages.

Zend Interview Questions and Answers

Is Zend Framework a component library or a framework? 

ZF is both. Zend Framework provides all the components required for most web applications in a single distribution. But Zend Framework components are also loosely coupled, making it easy to use just a few components in a web application- even alongside other frameworks! Using this use-at-will architecture, we are implementing features commonly found in more monolithic frameworks. In fact, we are currently working on a tooling component for the 1.8 release that will make it simpler to build applications using ZF components, yet will not sacrifice the use-at-will nature of existing ZF components.

What is autoloader?
Autoloader is function that load all the object on start up.

What is use of Zend front controller?
Routing and dispatching is managed in the front controller. It collects all the request from the server and handles it.

What is the use of Bootstrap?
Apart from index if we want to do any extra configuration regarding database and other things that is done within bootstrap.

How you can set Module name, Controller name, and Action name in Zend framework?

  •  $request->setModuleName(‘front’);
  •  $request->setControllerName(‘address’);
  •  $request->setActionName(‘addresslist’);

Configuration in Zend Framework, application.ini file?
Configuration can be done in application.ini file in Zend framework. This file in the path application/configs/application.ini.

Checking whether form posted or not in Zend framework?
$request = $this->getRequest();
$getData = $request->getParams();
$postData = $request->getPost();

$isPost = $request->isPost();

Fetch last inserted id, fetch all record,find and fetch a single record.


Difference between Zend_Registry and Zend_Session?

Zend_Registry is used to store objects/values for the current request. In short, anything that you commit to Registry in index.php can be accessed from other controllers/actions (because EVERY request is first routed to the index.php bootstrapper via the .htaccess file). Config parameters and db parameters are generally prepped for global use using the Zend_Registry object.

Zend_Session actually uses PHP sessions. Data stored using Zend_Session can be accessed in different/all pages. So, if you want to create a variable named ‘UserRole’ in the /auth/login script and want it to be accessible in /auth/redirect, you would use Zend_Session.

When do we need to disable layout?
At the time of calling AJAX to fetch we need to disable layout.

How to call two different views from same action?
Public function indexAction() {

Public function indexAction() {
Now in your index.phtml you can have this statement to call other view
$this->action(‘action name’,’controller name’,’module name’,array(‘parameter name’=>’parameter value’));

Can we call a model in view?
Yes, you can call a model in view. Simple create the object and call the method.

$modelObj = new Application_Model_User();

Can we rename the application folder ?
yes, we can

Can we move the index.php file outside the public folder?
yes, we can

How to include js from controller and view in zend?

From within a view file: $this->headScript()->appendFile(‘filename.js’);
From within a controller: $this->view->headScript()->appendFile(‘filename.js’);
And then somewhere in your layout you need to echo out your headScript object:

How to include css from controller and view in zend? 
From within a view file: $this->headLink()->appendStylesheet(‘filename.css’);
From within a controller: $this->view->headLink()->appendStylesheet(‘filename.css’);
And then somewhere in your layout you need to echo out your headLink object:

How do you protect your site from sql injection in zend when using select query? 

We have to quote the strings,
$this->getAdapter ()->quote ( <variable name> );
$select->where ( ” <field name> = “, <variable name> );
OR (If you are using the question mark after equal to sign)
$select->where ( ” <field name> = ? “, <variable name> );

What is zend framework?
Answer: It is opensource framework created by (PHP company). It is object oriented and follow the MVC. Zend Framework is focused on building more secure, reliable and fast development.

How to add extra HTML (i.e link) in Zend_Form?
Answer: use Desciption decorator with (escape =false in second parameter).

How can I detect if an optional file has been uploaded?
Answer:  Zend_File_Transfer_Adapter_Http’s receive()  return true.

What is Zend registry?
Answer: It is container for object and values  in applications, when you set an object in zend_registry you can access in whole site.

What is Zend_Form?
Answer: It is mainly used to display the form. but along with this we use for filter, validation and formating our form. It have following elements
Element filter
Element validation
Element ordering.
Sub form
Rendering form elments in single call or one by one for elements.

What is zend helpers?
It can be divided in two parts,
a) Action Helper: the helper is created for controller
b) View Helper: the helper is created for view files (.phtml).

What do you know about zend layout.
Answer: It work as a site template and have following features.
Automatic selection and rendering layout
Provide separate scope for calling element i.e parital, render, partialLoop

What is Inflection?
Answer: It is class in zend used to modify the string like convert to lowercase, change to url by removing special chars and convert underscore to hyphen.

What is Front Controller?
Answer:  It used Front Controller pattern.  zend also use singleton pattern.
routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
routeShutdown: This function  is called after the router finishes routing the request.
dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
preDispatch: called before an action is dispatched by the dispatcher.
postDispatch: is called after an action is dispatched by the dispatcher.

What is Zend_filter?
Zend_filter is used to filter the data as remove the tags, trailing the spaces, remove all except digits.

40 spring interview questions and answers

Q.1 What is Aspect oriented Programming (AOP)?

Basically Aspect oriented programming complements object oriented programming by providing another way of programming model structure.

In addition to classes, AOP gives you aspect, which enables modularization of concerns such as Transaction management or logging and can be separated out from the application business logic of the code (these kinds of concerns are termed as crosscutting concerns). AOP supports separating application business logic from System services.

What is IOC or Dependency Injection?

The basic concept of IOC (Dependency of Injection) is that you do not create your objects but describe how they should be created.

You don’t directly connect your component and services together in code but describe which services are needed by which component in configuration file.

You just need to describe the dependency, the Spring container is then responsible for hooking it all up.

When to use Dependency Injections?

There are different scenarios where you Dependency Injections are useful.

  • You need to inject configuration data into one or more component.
  • You need to inject the same dependency into multiple components.
  • You need to inject different implementation of the same dependency.
  • You need to inject the same implementation in different configuration.
  • You need some of the services provided by container.

When you should not use Dependency Injection?

There were scenarios where you don’t need dependency injections e.g.

  • You will never need a different implementation.
  • You will never need different configurations.

What is Bean Factory in Spring?

A Bean Factory is like a factory class that contains collections of beans. The Bean Factory holds bean definition of multiple beans within itself and then instantiates the bean when asked by client.

Bean Factory is actual representation of the Spring IOC container that is responsible for containing and managing the configured beans.

Different Spring Bean Scope.

singleton: Return a single bean instance per Spring IOC container.

prototype: Return a new bean instance each time when requested.

request: Return a single bean instance per HTTP request.

session: Return a single bean instance per HTTP session.

global session: Return a single bean instance per global HTTP session and only valid when used in portlet context.

Q.7 How you will decide when to use prototype scope and when singleton scope bean?

You should use the prototype scope for all beans that are stateful and the singleton scope should be used for stateless beans.

Q.8 What are the different types of IOC?

There are three types of dependency Injection:

Constructor Injection: dependencies are provided as a constructor parameter.

Example: You want to inject some object say Foo through constructor in class HellowWorld like below.

public class HelloWorld{
public HelloWorld(Foo foo){ = foo;

In configuration file you need to do following entry.

<bean id=”helloWorldBean” >

<constructor-arg ref=”fooBean” />


<bean id=”fooBean” >


Setter Injection: Dependencies are assigned through setter method.

Example: same example as above.

public class HelloWorld{
private Foo fooBean;
public HelloWorld(){ }
public void setFooBean(Foo fooBean){
And in configuration file you need to do following entry.

<bean id=”helloWorldBean”>

<property name=fooBean ref=”fooBean” />


<bean id=”fooBean” >


Interface Injection: Injection is done through an interface and not supported in spring framework.

Q: 9 How to Call Stored procedure in Spring Framework?

To call a Stored procedure in Spring framework you need to create Class which will should extends StoredProcedure class. Take the example of getting Employee Details by Employee Id. package com.mytest.spring.storeproc

import java.sql.ResultSet;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class EmployeeInfo extends StoredProcedure {

private static final String EMP_ID = “EMP_ID”;
private static final String EMP_NAME = “EMP_NAME”;
private static final String JOIN_DATE = “JOIN_DATE”;
public SnapshotSearchStoredProcedure(DataSource dataSource, String procedureName)
super(dataSource, procedureName);
declareParameter(new SqlParameter(EMP_ID, Types.NUMERIC));
declareParameter(new SqlOutParameter(EMP_NAME, Types.VARCHAR));
declareParameter(new SqlOutParameter(JOIN_DATE, Types.VARCHAR));
compile ();

public Map execute(Integer empId)
Map<String, Object> inputs = new HashMap<String, Object>();
inputs.put(P_CLD_IDR, empId);
Map<String, Object> result = execute (inputs);
return result;

You just need to call the execute method from the DAO layer.

Spring interview questions - posted on June 27, 2013 at 17:05 PM by Kshipra Singh

1. Differentiate between BeanFactory and ApplicationContext in spring.

- With ApplicationContext more than one config files are possible while only one config file or .xml file is possible with BeanFactory.
- ApplicationContext publishes events to beans that are registered as listeners while BeanFactory doesn’t support this
- ApplicationContext support internationalization messages, application life-cycle events, validation and many enterprise services like JNDI access, EJB integration, remoting etc. while BeanFactory doesn’t support any of these.

2. What is the difference between singleton and prototype bean?

Mainly it is the scope of a beans which defines their existence on the application
- Singleton: It means single bean definition to a single object instance per Spring IOC container.
- Prototype: It means a single bean definition to any number of object instances.

3. How do beans become ‘singleton’ or prototype?

- There exists an attribute in bean tag, called ‘singleton’.
- If it is marked ‘true’, the bean becomes singleton.
- If it is marked ‘false’, the bean becomes prototype.

4. What type of transaction Management Spring support?

Spring supports two types of transaction management:

1. Programmatic transaction management
2. Declarative transaction management.

5. When do you use programmatic and declarative transaction management ?

- Programmatic transaction management is used preferably when you have a small number of transactional operations.
- Incase of large number of transactional operations it is better to use declarative transaction management.

6. What is IOC?

- IOC stands for Inversion of Control pattern.
- It is also called as dependency injection.
- This concept says that you do not create your objects but describe how they should be created.
- Similarly, you do not directly connect your components and services together in code but describe which services are needed by which components in a configuration file.
- A container then hooks them all up.

7. What are the different types of IoC (dependency injection) ?

There are three types of dependency injection:

a.) Constructor Injection : Here dependencies are provided as constructor parameters.
b.) Setter Injection : Dependencies are assigned through JavaBeans properties.
c.) Interface Injection : Injection is performed through an interface.

Spring supports only first two categories of Injection.

8. What are the benefits of IOC?

The main benefits of IOC or dependency injection are:

a.) It minimizes the amount of code in your application.
b.) It makes your application easy to test as it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.
c.) Loose coupling is promoted with minimal effort and least intrusive mechanism.
d.) IOC containers support eager instantiation and lazy loading of services.

9. What is Bean Wiring ?

Bean wiring means creating associations between application components i.e. beans within the spring container.

10. How do you access Hibernate using Spring ?

There are two ways to Spring’s Hibernate integration:
a.) By Inversion of Control with a HibernateTemplate and Callback
b.) By extending HibernateDaoSupport and Applying an AOP Interceptor

11. How would you integrate Spring and Hibernate using HibernateDaoSupport?

This can be done through Spring’s SessionFactory called LocalSessionFactory. The steps in integration process are:

a.) Configure the Hibernate SessionFactory
b.) Extend your DAO Implementation from HibernateDaoSupport
c.) Wire in Transaction Support with AOP

12.What are the various transaction manager implementations in Spring ?

1. DataSourceTransactionManager : PlatformTransactionManager implementation for single JDBC data sources.

2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories.

3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories.

4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions.

Q: 13 What are the different modules in spring framework?

The Spring features or organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test, as depicted below.

Q: 14 What is Auto Wiring in Spring?

The Auto-wiring in spring framework can be performed by configuring in xml and Spring Auto-Wiring with Annotation @Autowired.

Auto-wiring beans with xml configuration: In Spring framework, you can wire beans automatically with auto-wiring feature. To enable auto-wiring just define the “autowire” attribute in <bean> tag.

<bean id=”customer” autowire=”byName” />

There are 5 modes of Auto-wiring supported.

no – Default, no auto wiring, set it manually via “ref” attribute

<bean id=”customer” >
<property name=”person” ref=”person” />

<bean id=”person” />

byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.

In below example the name of the person bean is same as name of “customer” bean’s property Person object. So spring will auto-wire it via setter method.

<bean id=”customer” autowire=”byName”/>

<bean id=”person” />

byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.

In below example the data type of the person bean is same as name of “customer” bean’s property Person object. So spring will auto-wire it via setter method.

<bean id=”customer” autowire=”byType”/>

<bean id=”person” />

constructor – byType mode in constructor argument.

Here the data type of “person” bean is same as the constructor argument data type in “customer” bean’s property (Person object), so, Spring auto wired it via constructor method – “public Customer(Person person)”

<bean id=”customer” autowire=”constructor”/>

<bean id=”person” />

autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.

If a default constructor is found, uses “constructor”; Otherwise, uses “byType”. In this case, since there is a default constructor in “Customer” class, so, Spring auto wired it via constructor method – “public Customer(Person person)”

<bean id=”customer” autowire=”autodetect”/>

<bean id=”person” />

Q:15 What is JdbcTemplate in Spring? And how to use it?

The JdbcTemplate class is the main class of the JDBC Core package. The JdbcTemplate (The class internally use JDBC API) helps to eliminate lot of code you write with simple JDBC API (Creating connection, closing connection, releasing resources, handling JDB Exceptions, handle transaction etc.). The JdbcTemplate handles the creation and release of resources, which helps you to avoid common error like forgetting to close connection.


1. Getting row count from database.

int rowCount = this.jdbcTemplate.queryForObject(“select count(*) from t_employee”, int.class);

2. Querying for a String.

String lastName = this.jdbcTemplate.queryForObject( “select last_name from t_employee where Emp_Id = ?”, new Object[]{377604L}, String.class);

3. Querying for Object

Employee employee = this.jdbcTemplate.queryForObject( “select first_name, last_name from t_employee where Emp_Id = ?”, new Object[]{3778604L}, new RowMapper()
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
return employee;

4. Querying for N number of objects.

List<Employee> employeeList = this.jdbcTemplate.query(“select first_name, last_name from t_employee”, new RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
return employee;

Q:16 What NamedParameterJdbcTemplate in Spring?

The NamedParameterJdbcTemplate allow basic set of JDBC operations, it allows named parameter in the query instead of traditional (?) placeholder, the functionality is similar to JdbcTemplate class.


NamedParameterJdbcTemplate namedParameterJdbcTemplate;

String empInsrtQuery = “INSERT INTO Employee (name, age, salary) VALUES (:name, :age, :salary)”;
Map namedParameters = new HashMap();
namedParameters.put(“name”, name);
namedParameters.put(“age”, age);
namedParameters.put(“salary”, salary);
namedParameterJdbcTemplate.update(empInsrtQuery, namedParameters);

Q: 17 What are Advice, Aspect, Join-point and point cut in spring?

Advice: An advice is an action taken by the aspect at particular join-point is called Advice.

Aspect: An aspect is a subprogram which is associated with specific property of a program (Example separating logging code from the main program).

An aspect is functionality or feature that cross cuts over object. AOP increase modularity of a program.

Join-Point: A join point is a point used in spring AOP framework to represent a method execution. It always point during execution of program, method or exception. A join point is basically an opportunity within the code to apply aspect.

Point Cut: In AOP a point cut is a set of many join points where an advice can execute. A chunk of code (known as Advice) associated with join point get executed.

Q:18 What are the different types of Advice?

There are different types of Advice.

Before Advice: The advice which executed before a join point called before advice. The before advice does not have the ability to prevent the execution flow proceeding at the join point (unless it throws an exception).

After Return Advice: The advice which executed after a join point completed normally without any exception.

Around Advice: It is responsible for choosing whether to proceeds to the join point or shortcut the advised method execution by returning its own return value or throwing an exception. This is most powerful kind of advice. With Around advice you can perform custom behavior before and after method execution.

After throwing advice: The advice executed when a method throws an exception.

After (finally) advice: The advice is executed when program exits the join points either normally or by throwing an exception.

Q: 19 What is Weaving in Spring?

Weaving is the process of linking aspect with other application types or object to create an advised object. This can be performed at compile time, runtime and load time. In spring framework weaving is performed at runtime.

Q:20 What is AOP Proxy?

AOP proxy is an object to implement the aspect contracts (advice method executions and so on). The AOP proxy is object is created by the AOP framework. In spring framework AOP proxy is JDK dynamic proxy or CGLIB proxy.

Q: 21 What is front controller in Spring MVC?

The Front Controller is basically a type of Design pattern which are being implemented in different framework (e.g. Struts and Spring MVC etc.). In Spring MVC DispatcherServlet act as a Front Controller for the framework and responsible for intercepting every request and then dispatches/forwards request to appropriate controller. Configure the DispatcherServlet in the web.xml file of web application and request which we want to be handled by DispatcherServlet should be mapped using URL mapping. For example all requests ending with *.do will be handled by the DispatcherServlet.


Q:22 Difference between FileSystemResource and ClassPathResource?

In FileSystemResource you need to give the configuration file (i.e. spring-config.xml) relative to your project or the absolute location of the file.

In ClassPathResource spring looks for the file in the ClassPath so configuration (i.e. spring-config.xml) file should be included in the classpath. If spring-config.xml is in classpath, you can simply give the name of the file.

For Example: If your configuration file is at src/main/java/com/test/loadresource then your FileSystemResource would be:

FileSystemResource resource = new FileSystemResource(“src/main/java/com/test/loadresource/spring-config.xml”);

And ClassPathResource would be:

ClassPathResource resource = new ClassPathResource(“com/test/loadresource /spring-config.xml”);

Q: 23 What is inner Bean Definition?

A bean definition added inside the property or constructor-arg elements are called inner bean.


<bean id=”outerbean”>
<!– instead of using a reference to a target bean, simply define the target bean inline –>
<property name=”targetbean”>
<bean > <!– this is the inner bean –>
<property name=”name” value=”XYZ”/>
<property name=”age” value=”35″/>

24. List in brief the new features Spring 3.0 has to offer

Spring 3.0 offers the following new features:
1. Spring Expression Language
2. IoC enhancements or Java based bean metadata
3. field formatting and General-purpose type conversion system
4. Object to XML mapping functionality (OXM) moved from Spring Web Services project
5. Comprehensive REST support
6. @MVC additions
7. Declarative model validation
8. Early support for Java EE 6
9. Embedded database support

25. What are the annotations supported by the spring framework?

Due to addition of some core features from the JavaConfig project to the Spring Framework,the following annotations are now directly supported:
• @Configuration
• @Bean
• @DependsOn
• @Primary
• @Lazy
• @Import
• @ImportResource
• @Value

26. Explain in brief the metadata contained in the BeanDefinition objects

Bean definitions contain the following metadata:
1. A package-qualified class name: which is the actual implementation class of the bean being defined.
2. Bean behavioral configuration elements, which state the procedure for how the bean should behave in the container
3. References to other beans that are required for the bean to do its work; these references are also called collaborators or dependencies.
4. Other configuration settings to set when a new object is created, for example, the number of connections to use in a bean that manages a connection pool or the size limit of the pool.

27. What are the different properties the metadata translates into to make up the bean definition?

Metadata translates into the following properties to make up
1. Property defined in class the section called “Instantiating beans”
2. Property defined in name the section called “Naming beans” scope constructor arguments the section known as “Dependency injection”
3. Properties the section known as “Dependency injection” auto wiring mode the section known as “Autowiring collaborators”
4. lazy-initialization mode the section called “Lazy-initialized beans”
5. Initialization method the section called “Initialization callbacks”
6. Destruction method the section called “Destruction callbacks”

28. Briefly describe the 2 ways in which the class property can be used.

The class property can be put to use in the following ways:
1. It is used to specify the java bean for class to be constructed when container directly creates java bean by calling constructor reflectively. This procedure is also used for java code which uses a new operator.
2. It is also used to specify the class which contains static factory method which is invoked for creating object. Another case in this which doesn’t occur much is when static factory method is invoked by container on a class for creating the bean.

29. Explain the dependency resolution process.

The dependency resolution process is carried out as follows:
1. Creation an initialization of application text inside configuration metadata( can be specified in XML, java code,annotations) is done. This describes all the beans.
2. For each bean, its dependency is expressed in the form of properties, constructor arguments, or
arguments to the static-factory method if that is used instead of a normal constructor.
3. Each property or constructor argument is actual definition of the value which belong to set, or a reference to another bean which is in the container.
4. Each property or constructor argument which is a value is gone through conversion from its specified format to the actual type of that property or constructor argument.

30. How can you use spring to resolve collaborators for your bean? Also state the advantages of auto wiring?

The spring can be used to resolve collaborators automatically by inspecting contents of the
The Autowiring has the following advantages in spring:
1. Reduces requirement for specifying properties or construction arguments.
2. Updates configuration while evolving of objects.
To understand this lets consider an example: modifying would not be required in configuration of a dependency while adding it to a class.
3. Switching to explicit wiring when code base is stable can be neglected.

31. List the limitations of auto wiring.

Autowiring has the following limitations:
1. Overriding and auto wiring are caused due to dependency in property and constructor argument setting.
2. Less precise as compared to explicit wiring.
3. Tools that generate documentation using a spring might not have access to wiring information.
4. There is a possibility of clash between bean definitions and argument or method to be wired.
The problem does not occur much in case of maps, arrays and collection and cannot be resolved randomly for dependencies which expect one value.

32. In scenarios where you have to avoid using auto wiring, what are the other options that can be explored to achieve the same.

In scenarios where using autowiring is prohibited, the following replacements can achive the same:
1. Abandon autowiring for favor of explicit wiring.
2. Avoid autowiring for a bean definition by setting the autowire-candidate for attributes to false as described in the next section.
3. Set a single bean definition as the primary candidate by setting the primary attribute of its
<bean/> element to true.
4. When Java 5 or later is used, implementation needs more fine-grained control available with
annotation-based configuration.

33. How do you call the multiple lifecycle mechanisms configured for the same bean?

Multiple lifecycle mechanisms which are configured for the same bean, with different initialization methods, are called by the following ways :
1. Methods annotated with use of @PostConstruct
2. afterPropertiesSet() as stated by the InitializingBean callback interface
3. Custom configuration init() method
Destroy methods are called in the same order as follows :
1. Methods annotated with use of @PreDestroy
2. destroy() as stated by the DisposableBean callback interface
3. destroy() method with custom configuration

34. What are the methods associated with the FactoryBean interface?

Following are the methods associated with factory bean interface:
1> Object getObject(): this returns an instance of the object which the factory creates. This instance can
possibly be shared, depending on the factory returns singletons or prototypes.
2> boolean isSingleton(): this returns true if this FactoryBean returns singletons, false
3> Class getObjectType(): this returns the object type returned by the getObject() method or
null if the type is unknown in advance.

35. What are the functionalities provided by the context package to enhance the BeanFactory functionality?

The functionalities provided by context package are as follows:
1. message access in i18n-style, through the MessageSource interface.
2. Resources access such as URLs and files, through which, the ResourceLoader interface, can be accessed and used.
3. Publication of events, through the beans that allow, implementing the ApplicationListener interface. It is done through the use, of the ApplicationEventPublisher interface.
4. Multiple loading contexts, allowing each to be focused on one particular layer, such as the web layer of an application, through the HierarchicalBeanFactory interface.

36. How can you achieve Internationalization using MessageSource?

Internationnalization using message source can be achieved by the following:
1>String get Mesage(String code, Objct[] args, String default, Local
loc): The basic method used for retrieving a message from the MessageSource. When no message is to be
found for the specified locale, the default message is used.
2> String getMessage(String code, Objct[] args, Locale loc): Essentially the
same as the last method, but with a difference: no default message is specified; if the
message cannot be found, a NoSuchMessageException is shown.
3> String getMessage(MessageSourceResolvable resolvable, Local locale):
properties used for the preceding methods are also wrapped in a class named
MessageSourceResolvable, which you can use with this method.

37. Enlist and explain the main methods associated with the Resource interface.

Methods associated with resource interface are as follows:
1> getInputStream(): it locates and opens the resource, returning an InputStream to read from
the resource.
2> exists(): returns a boolean which indicates whether this resource actually exists in physical form.
3> isOpen(): returns a boolean which indicates whether this resource represents a handle with an open
4> getDescription(): returns a description for this resource, which is used for error output when
working with the resource.

38. Give some examples where property editing is used in spring.

Following are examples for property editing in spring
1> setting of properties on beans is done by using PropertyEditors. To mention
java.lang.string as the value for a property of some bean you’re declaring in XML file, Spring will use the ClassEditor to try resolving the parameter to a Class object.
2> passing HTTP request parameters in Spring’s MVC framework can be done using all kinds of PropertyEditors that can be manually bind in all subclasses of the CommandController.

40. Explain the main AOP concepts and terminology

The main AOP concepts are as follows:
1> Aspect: a modularization of a concern that cuts through multiple classes.
2> Join point: is a point during which the execution of a programming, such as the execution of method or handling of an exception.
3> Advice: action taken by an aspect for a particular join point.
4> Point cut: a predicate that is matched to join points.
5> Introduction: declaration of additional methods or fields on behalf of a type.
6> Target object: object which is advised by one or more aspects.
7> AOP proxy: an object which is created by AOP framework for implementing the aspect contracts.
8> Weaving: linking of aspects with other application types or objects to create an advised object.


Hibernate interview Questions

Q:1 What is Hibernate?

Ans: Hibernate is an ORM (Object Relational Mapping) and persistent framework. The framework helps to map plain java object to relational database table using xml configuration file.

The framework helps to perform following things.

• Perform basic CURD operations.
• Write queries referring to java classes (HQL queries).
• Facilities to specify metadata.
• Dirty checking, lazy association fetching.

Q: 2 Why hibernate and how does it help in the programming?

Ans: The main advantage of Hibernate (ORM) framework is that it helps developer to write a messy SQL. Apart from that ORM provides following benefits.

• Improve Productivity of the developer by providing high level object oriented API (e.g. API for easily maintaining the connection to data base, mapping java classes to relational database tables), less java code to write, helps to avoid writing SQL query.
• Improved performance by providing sophisticated caching, lazy loading and eager loading features.
• Provide portability, the framework helps to generate database specific SQL for you.

Q:3 How will you configure Hibernate?

Ans: To configure hibernate, you need hibernate.cfg.xml or file and *.hbm.xml files, all these files are used by Configuration class to create sessionFactory, which in turn creates the session instances. Session instances are the primary interface for persistence services.

The hibernate.cfg.xml or files are used to configure the hibernate service (database connection driver class, database connection URL, connection user name, connection password, dialect, mapping resources etc.).

The *hbm.xml files are used for mapping persistent objects to relational database.

From Java 5 onwards you can configure and map persistent objects through annotations.

Q:4 Which settings will be loaded if both and files are present in the classpath?

Ans: If both and hibernate.cfg.xml files are present in the classpath then hibernate.cfg.xml file will override the settings found in So please make sure that your project should include either or hibernate.cfg.xml file.

Q:5 What are the Core interfaces of Hibernate framework?

Ans: There are five core interfaces being used extensively in every Hibernate application. Using these interfaces you can store or retrieve any persistent objects and also control transactions.

- Session interface
- SessionFactory interface
- Configuration interface
- Transaction interface
- Query and Criteria interfaces

Q:6 What is the role of Session interface in Hibernate?

Ans: The session interface is the primary interface used in Hibernate Application. It is single threaded sort-lived object and represents conversation between Application and the persistent store. It helps to create query objects to retrieve persistent objects.

You can get the session object from session factory

Session session = sessionFactory.openSession();

Session Interface role:

–Wraps a JDBC connection
–Factory for Transaction
–Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

Q: 7 What is the role of SessionFactory?

Ans: The application obtains session object from SessionFactory interface. Typically there should be only one sessionFacory for whole application and is loaded during application initialization. The SessionFactory caches generate SQL Statement and other mapping metadata that Hibernate use at runtime. It also hold cached data that has been read in one unit of work and can be reused in a future unit of work.

You can get the instance of SessionFactory by the configuration object as below

SessionFactory sessionFactory = configuration.buildSessionFactory();

Q:8 How do you implement one to one relationship in Hibernate with XML mapping?

Ans: For example you have table emp and emp_detail and assuming there is a one to one relationship between them. For the above tables you have to create corresponding POJO classes and hbm.xml files.

So for emp table the java class is with property empId and xml file is emp.hbm.xml.

And for emp_details the java class is (properties are name, address etc.) and xml file is empdetail.hbm.xml.

So the final code will look like as below

package com.test.onetoone.mapping

public class Employee implements{
private Integer empId;
private EmployeeDetail empDetail;

package com.test.onetoone.mapping
public class EmployeeDetail implements{
private Integer empId;
private Employee emp;
private String name;
private String address;
—– emp.hbm.xml —-
<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
<class name=”com.test.onetoone.mapping.Employee” table=”emp”>
<id name=”empId” type=”java.lang.Integer”>
<column name=”EMP_ID” />
<generator />
<one-to-one name=”empDetail” class=”com.test.onetoone.mapping.EmployeeDetail”


<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
<class name=”com.test.onetoone.mapping.EmployeeDetail” table=”emp_detail”
<id name=”stockId” type=”java.lang.Integer”>
<column name=”EMP_ID” />
<param name=”property”>emp</param>
<one-to-one name=”emp”
<property name=”name” type=”string”>
<column name=”EMP_NAME” length=”100″ not-null=”true” />
<property name=”address” type=”string”>
<column name=”EMP_ADDR” not-null=”true” />

Q:9 How do you implement one to one relationship in Hibernate with java annotation?

Ans: Taking the same Employee and Employee Details example of the above question.
package com.test.onetoone.mapping
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Table(name = “emp”)
public class Employee implements{
private Integer empId;
private EmployeeDetail empDetail;
public Employee(){}
@GeneratedValue(strategy = IDENTITY)
@Column(name = “EMP_ID”, unique = true, nullable = false)
public Integer getEmpId(){
return this.empId;
public void setEmpId(Integer empId){
this.empId = empId;
@OneToOne(fetch = FetchType.LAZY, mappedBy = “emp”, cascade = CascadeType.ALL)
public EmployeeDetail getEmpDetail() {
return this.empDetail;
public void setEmpDetail(EmployeeDetail empDetail) {
this.empDetail = empDetail; }


package com.test.onetoone.mapping
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Table(name = “emp_detail”)
public class EmployeeDetail implements {
private Integer empId;
private Employee emp;
private String name;
private String address;
public EmployeeDetail() {
public EmployeeDetail(Employee emp, String name, String address) {
this.emp = emp; = name;
this.address = address;
@GenericGenerator(name = “generator”, strategy = “foreign”,
parameters = @Parameter(name = “property”, value = “emp”))
@GeneratedValue(generator = “generator”)
@Column(name = “EMP_ID”, unique = true, nullable = false)
public Integer getEmpId() {
return this.empId;
public void setEmpId(Integer empId) {
this.empId = empId;
@OneToOne(fetch = FetchType.LAZY)
public Employee getEmp() {
return this.emp; }

public void setEmp(Employee emp) {
this.emp = emp;
@Column(name = “ADDRESS”, nullable = false, length = 400)
public String getAddress() {
return this.address;
public void setAddress(String address) {
this.address = address;
@Column(name = “EMP_NAME”, nullable = false)
public String getName() {
public void setName(String name) { = name;

3. Hibernate Configuration File

Puts annotated classes and in your Hibernate configuration file, and also MySQL connection details.
File : hibernate.cfg.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”

<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/mytestdb</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”>password</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”show_sql”>true</property>
<mapping />
<mapping />

Q:10 How do you implement one to many relationships in Hibernate?

Ans: For one to many relationships we can consider the example Author and Books (i.e. one Author can have written many books).
Below code will help you to understand how you can implement one to many relationship in hibernate.


public class Author implements{
private Integer authorId;
private String authorName;
private Set<Book> books;
// getter and setter

public class Book implements{
private Author author;
private Integer bookId;
private String bookName;
// getter and setter

File: Author.hbm.xml
<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
<class name=”” table=”author”>
<id name=”authorId” type=”java.lang.Integer”>
<column name=”AUTHOR_ID” />
<generator />
<property name=”authorName” type=”string”>
<column name=”AUTHOR_NAME” length=”100″ not-null=”true” unique=”true” />
<set name=”books” table=”book” inverse=”true” lazy=”true” fetch=”select”>
<column name=”AUTHOR_ID” not-null=”true” />
<one-to-many />

File: Book.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
<class name=”” table=”book”>
<id name=”bookId” type=”java.lang.Integer”>
<column name=”BOOK_ID” />
<generator />
<many-to-one name=”author” fetch=”select”>
<column name=”AUTHOR_ID” not-null=”true” />
<property name=”bookName” type=”string”>
<column name=”BOOK_NAME” />

File: hibernate.cfg.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/mytestdb</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”>password</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”show_sql”>true</property>
<property name=”format_sql”>true</property>
<mapping resource=”com/test/one/to/many/Author.hbm.xml” />
<mapping resource=”com/test/one/to/many/Book.hbm.xml” />

Q:11 How to implement one to many relationships with Annotation?

Ans: You can implement one to many relationship with the help Annotation also. Below code will help you to understand the one to many relationship with java Annotation.

File :
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Table(name = “Author”)
public class Author implements {
private Integer authorId;
private String authorName;
private Set<Book> books;
// getter and setter

public Author() {
@GeneratedValue(strategy = IDENTITY)
@Column(name = “AUTHOR_ID”, unique = true, nullable = false)
public Integer getAuthorId() {
return this.authorId;

public void setAuthorId(Integer authorId) {
this.authorId = authorId;

@Column(name = “AUTHOR_NAME”, nullable = false, length = 100)
public String getAuthorName() {
return this.authorName;
public void setAuthorName(String authorName) {
this.authorName = authorName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = “author”)
public Set<Book> getBooks() {
return this.books;
public void setBooks(Set<Book> books) {
this.books = books;

File :
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Table(name = “book”)
public class Book implements {
private Author author;
private Integer bookId;
private String bookName;
public Book() {
@GeneratedValue(strategy = IDENTITY)
@Column(name = “BOOK_ID”, unique = true, nullable = false)
public Integer getBookId() {
return this.bookId;
public void setBookId(Integer bookId) {
this.bookId = bookId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = “AUTHOR_ID”, nullable = false)
public Author getAuthor() {
return this.auther;
public void setAuther(Author author) {
this.auther = auther;
@Column(name = “BOOK_NAME”, length = 400, nulaable=false)
public Float getBookName() {
return this.bookName;
public void setBookName(String bookName) {
this.bookName = bookName;

3. Hibernate Configuration File
Puts annotated classes and in hibernate.cfg.xml like this :

File : hibernate.cfg.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”

<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/mytestdb</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”>password</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”show_sql”>true</property>
<mapping />
<mapping />

Q:12 How will you integrate Hibernate with spring framework?

Ans: To integrate hibernate with spring framework, the hibernate configuration will go in spring configuration file.
The configuration file will look like as below
<bean id=”propertyConfigurer”
<!— database related properties -?

<bean id=”dataSource”
class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”
p:url=”${jdbc.databaseurl}” p:username=”${jdbc.username}”

<bean id=”sessionFactory”
<property name=”dataSource” ref=”dataSource”></property>
<property name=”configLocation”>
<property name=”configurationClass”>
<property name=”hibernateProperties”>
<prop key=”hibernate.dialect”>${jdbc.dialect}</prop>
<prop key=”hibernate.show_sql”>true</prop>

<bean id=”employeeDAO”></bean>
<bean id=”employeeManager” class=”com.test.service.EmployeeManagerImpl”></bean>

<tx:annotation-driven />

<bean id=”transactionManager”
<property name=”sessionFactory” ref=”sessionFactory”></property>

Q:13 What are the Collection types in Hibernate?

• Bag
• Set
• List
• Array
• Map

Q:14 What is HibernateTemplate?

Ans: The spring framework provides HibernateTemplate (org.springframework.orm.hibernate.HibernateTemplate) which is kind of helper class and provides following benefits.

- HibernateTemplate class simplifies interaction with Hibernate session.
- Common functions are simplified to single method calls.
- Sessions are automatically closed.
- Exception are automatically caught and converted to runtime exceptions.

Q:15 What is the difference between load() and get() method?



- Use load() method only when you are sure that object you want to read already exists.
- If unique Id of an object does not exists in database then load() method will throw an exception.
- load() method return proxy object default and database won’t be hit until the proxy is first invoked.


- Use get() method when you are not sure obout the object existance in the database.
- If object does not exists in the database, the get() method will return null.
- get() method will hit database immediately.

Q:16 What is lazy fetching in Hibernate?

Ans: In Hibernate Lazy fetching is associated with child objects loading for its parents. Through Hibernate mapping file (.hbm.xml) you can specified the selection of loading child objects. By default Hibernate does not load child objects. Lazy=rue means not to load the child objects.

Q:17 What is the difference between merge and update method?

Ans: Use update() method when you are sure that session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

Q:18 How do you define sequence generated primary key in hibernate?

Using <generator> tag.
<id column=”CUST_ID” name=”id” type=”java.lang.Long”>
<param name=”table”>SEQUENCE_NAME</param>

Q:19 What are the different types of caches in Hibernate?

Ans: Hibernate uses two different type of caches for objects: first-level cache and second-level cache. First level of cache is associated with Session object, while second-level of cache is associated with the SessionFactory object. By default, Hibernate uses first-level of cache on a per-transaction basis. Hibernate mainly use this cache to reduce the number of SQL queries it needs to generate within a given transaction.

Q:20 What do you mean by Named – SQL query?

Ans: Named SQL queries are defined in the mapping xml document and called wherever required.
<sql-query name = “empdetails”>
<return alias=”emp”/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {}
FROM Employee EMP WHERE emp.NAME LIKE :name
Invoke Named Query :
List people = session.getNamedQuery(“empdetails”)
.setString(“Deepak”, name)

28. How does Hibernate useful in mapping object and its relations?

Hibernate is a framework for Java that is used to map the object and its relations. It is used to build persistent objects using the terminologies of JAVA. It uses the following properties to perform the function of mapping:
• Association: where the one object can be associated with another object of the same or different class.
• Inheritance: is a property of inheriting the properties and features of the parent class.
• Polymorphism: is a feature that allows more than one data type to be handled by a single function.
• Composition: is used to combine the simple data types into complex data types.

It also consists of collection of APIs to show the relationship of the objects.

29. What is the function performed by code generator in Hibernate?

Code generator is a framework that allow simple and easy mapping of objects using pre-defined tags. It follows Model driven architecture which uses models of the objects separately and link them with each other. Code generator adds attributes to the source code. I uses the java-doc tags to generate the hibernate mapping. It is also used to generate the database definition language from the source code to map the objects correctly. It allows easy mapping of objects from an existing database and allow it to be connected to some different database model as well.

30. What is the need of hibernate tools when ORM tools can be used?

The use of hibernate tools is to allow the programmer to code efficiently and saves them from being involved with the SQL code directly. It is used to increase the productivity of the work and uses high level object oriented APIs to increase the efficiency and performance of the work. It allows the programming to be more objects oriented and the code in Java has to be written less. It also save programmers time to write the SQL code as there is no need to write the SQL code in it. These tools provide very good caching system that keeps all the files and they provide it when it is required. It allows easy maintenance of the overall system and the code that is being written in it.

31. What are the tags that are importantly used in Hibernate configuration file?

Hibernate configuration file is the most important file. The configuration file consists of many tags and they are as follows:
• DTD: this is also called as Document type definition and is written as:
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD/EN”
“ dtd”>

• JDBC connection configuration tag: JDBC stands for Java Database connectivity tags that gives the driver name and the database related information and represented as:
<property name= “hibernate connection.driver_class”>org.hsqldb.jdbcDriver</property>
• SQL variant: it specifies the SQL statement to generate the particular property in the database. It is given as:
<property name= “dialect”>org.hibernate.dialect.HSQLDialect</property>
• Conn pool: this tag is very important to set the size of the conn pool for the correct connection. It is given as:
<property name= “hibernate.connection.pool_size”>10</property>
• Property to generate the database schema: this property tag generates the database schema automatically. It is given as:
<property name= “”>create-drop</property>
• Mapping files: these files are important to map the resources of the same or different objects. It is given as:
<mapping resource= “Event.hbm.xml”>

32. What is the role played by Session interface in Hibernate?

Session interface is the primary interface used by Hibernate. It is the important interface for the applications that uses single thread, and a short lived object representing a conversation between application and the objects that are stored. This object allows creating query objects that can be used to call persistent objects from the database. This interface allows the wrapping of JDBC connection and keeps the transactions at one place. It holds the persistent objects in the cache for easy navigation and to increase the performance of the overall system. The interface is represented as:

Session session = sessionFactory.openSession();

33. What is the role played by SessionFactory interface in Hibernate?

The session instance is being obtained by the application from SessionFactory. It keeps the session instances at one place for easy access and dynamic allocation of the resources. There is always a single SessionFactory created for the complete application. This is created during the application initialization. It creates the cache that is used to generate the SQL statements and metadata information about the mapping of the Hibernate functions that gets used in runtime. It holds the data that has been cached and then read into it. It focuses on reusability of the work and the functions that are stored in the SessionFactory. This is represented as:
SessionFactory sessionFactory = configuration.buildSessionFactory();

34. What is the process of communication between Hibernate with RDBMS?

To create the communication between the Hibernate and RDBMS there are some steps that are involved in the process. These are as follows:
• To create the communication first loading of the Hibernate configuration file takes place. When this file is loaded then a configuration object gets created. This object loads the .hbm files used to map the objects automatically.
• A session gets created by taking the interface from the SessionFactory from the configuration object.
• A HQL query is being creation after taking the session from the session factory and starting the session for the user.
• In the end an execution of the query gets listed that contain the Java Objects of the file. This allows the communication being done between different objects of Hibernate and RDBMS.

35. What is the purpose of HQL in communication between Hibernate and RDBMS?

HQL stands for Hibernate Query language and is used to set the communication between the Hibernate and RDBMS. It is a powerful language that uses flexible mechanism for query, store, and update to take the objects from the database. It uses the objects for making a connection between the Hibernate and the database. It is an extension to the SQL that uses an Object oriented paradigm to communicate and retrieve the data from the database. It uses inheritance, polymorphism and abstraction features to handle the request and respond to the queries coming from the user.

36. Write the code that maps the Java Object with the database tables?

To map the Java Object with the database tables there is a need to write the code of Java domain objects. Java domain objects use the methods setter and getter to retrieve the Java objects and maps it accordingly. The file that is used to be written to map java class or object to the database table is hbm.xml. This file also maps the database columns to Java class variables. The code that is being written to perform the above mentioned operation is given below:

<class name=”com.test.User” table=”user”>
<property column=”USER_NAME” length=”255″
name=”userName” not-null=”true” type=”java.lang.String”/>
<property column=”USER_PASSWORD” length=”255″
name=”userPassword” not-null=”true” type=”java.lang.String”/>

37. What is the purpose of using HibernateTemplate?

HibernateTemplate is a spring template that is used as a class to simplify the interaction with the Hibernate Session. HibernatTemplate includes simplified single method calls that are used to close the sessions automatically. It includes the exception handler that catches the exception automatically and converted it in runtime. There are classes used in Hibernate that provides different methods for query and to retrieve the data from the database. The helper class that is provided is org.springframework.orm.hibernate. HibernatTemplat is used to check and convert the HibernateExceptions into unchecked DataAccessExceptions.

38. How components are used in Hibernate?

Components allow the object to be saved as a value and not as a reference. It is used to be saved directly without the need to declare the properties of the interfaces or identifier in the application. Components in Hibernate define the empty constructor in which the references that are shared are not supported. The components class will be defined as:

public class hello
{ private String a;
private int b;
private string c;
//write your own code here

39. Write a code to do the component mapping in Hibernate

To do the component mapping there is a requirement for two component classes that has to be made to establish the connection between them. So, the first component class will be like this:

public class hello
{ private String a;
private int b;
private string c;
//write your own code here

Another class will be written like this:
public class comp
{ // properties
private String a;
//write get and set methods
//write your own code here

The class that will be used to map the two components are written as:
<class name= “no.uio.inf.model.table=hello”>
<!—other properties–>
<component name= “comp”>
<property name = “a”/>
<property name = “b”/>
<property name = “c”/>

40. Why Hibernate is preferred over JDBC?

The preference of Hibernate is more due to the transparency it provides to the programmer for writing their code. It doesn’t allow the programmer to write explicit code to map the database tables to the application objects that are used during the interaction with RDBMS. It provides an advanced ORM solution to map the Java class files to the database tables for easy access and retrieval of the data. Hibernate uses Hibernate Query Language that is independent of the type of database used. It allows polymorphic queries to be retrieved and selects the way to perform the database manipulation tasks. Hibernate allow the storing of large amount of data in small files that can be easily accessed and the performance can be faster. It also provides the actually mapping to be performed between the tables and objects in the XML files.

41. What is the use of Hibernate proxy in Hibernate?

The proxies are easy to create and it is created dynamically by sub-classing the objects at runtime. This sub-class consists of all the parent methods and allows easy accessing of them. The proxy allows the loading of this object in real time from the database and calls the methods from there. Proxy is used as a mechanism in Hibernate allowing breaking of the objects in the database in smaller parts that can easily be accessed and use the memory efficiently. It is easy for a class to be mapped to a proxy than to a table. When there is a call load on a sessioin then the value that is returned is the proxy. The proxy consists of the methods to load the data. The sample code to call the proxy is given as:

<class name=”a”

42. What is the difference between managed and non-managed environment in Hibernate?

It is important to configure the Hibernate file properly so that it will be easy to manage and access the database. The difference that has to be known for the Hibernate is between Managed and non-managed environment:

• Managed environment allows the pooled resources of database connections to be loaded on run time. It also allows the transaction to be taken place smoothly in the specified boundaries, whereas non-managed environment provides the basic concurrency management using the method of thread pooling.
• Managed environment allows automatic transaction of the resources, whereas non-managed environment doesn’t provide any automatic transaction of the resources.
• Managed environment provides automatic management of security infrastructure, whereas non-managed environment doesn’t provide this.

43. What are the different types of interfaces present in Hibernate?

Hibernate consists of many interfaces to keep everything dynamic and up-to-date. The interfaces are as follows:
• Configuration interface: this interface includes the configuration object that is used to configure and bootstrap the Hibernate applications. It allows the need to map the documents and other related properties. It also allows the creation of the SessionFactory.

• Transaction interface: is an optional interface API that is used to manage the transaction of the infrastructure code. It allows the portability of the application that is executed in different environments and containers.

• Query and Criteria interfaces: it allows the performance of different queries that is against the database and it controls the execution of the queries as well. The queries are written either in HQL or SQL that depends on the database being used.

44. Why are callback interfaces useful in Hibernate?

Callback interfaces are useful as it allows the application to receive important notification about the objects that are in execution phase. It includes the objects that are loaded, saved or deleted from the Hibernate. Callback interfaces are very important to implement the general functionality like audit records, etc. It sends a notification when any object even occurs. It allows the programmer to get the error information or exception handling can be done in a better way to notify the user on run time in case of any problem in the programming code.

45. What are the different types of extension interface that is present in Hibernate?

Extension interface allows easy implementation of other interfaces according to the user’s requirements. It allows different functionality to be provided when the built in functionality is not sufficient for the users. The extensions that are provided for the use is as follows:
• ProxyFactory interface – it is used to create proxies to help in maintaining the mapping of the objects.
• ConnectionProvider interface: is used to provide the JDBC connection management for easy mapping of the object with the database.
• TransactionFactory interface: is used to provide the transaction management.
• TransactionManagementLookup interface: is used to provide the way to look up the transactions that is being managed by transaction management interface.
• Cahce interface: is used to provide the caching techniques and strategies for the objects to speed up the process.
• IdentifierGenerator interface: is used to provide a way to generate the keys like primary key to uniquely identify the objects.

46. What is the importance of Lifecycle and validatable interface in Hibernate?

Lifecycle and validatable interface allows the object that is persistent to react to certain events that occurs during their own persistence lifecycle. The lifecycle is managed by the CRUD operations which handles the object lifecycle as well. Hibernate uses ORM solution that are similar in functionality of the callback interface. It allows easy portable code for the transaction to be saved and persistent classes and objects can be validated and sent over for implementation and use.

Struts Interview Questions and Answers

Q1. Explain Struts.

Struts is open source software used to develop java based web page.

  • Struts uses Jakarta Packages, Java Servlets, JavaBeans, ResourceBundles, and XML
  • Struts takes the help of Model View Controller (MVC) architecture. Where Model is referring to business or database, View is referring to the Page Design Code, and Controller is referring to navigational code.

Q2. What is Action Class?

An Action class in the struts application is used to handle the request.

  • It acts as interface or communication medium between the HTTP request coming to it and business logic used to develop the application.
  • Action class consists of RequestProcessor which act as controller. This controller will choose the best action for each incoming request, generate the instance of that action and execute that action.
  • This should be in thread-safe manner, because RequestProcessor uses the same instance for no. of requests at same time.

Q3. What is Struts Validator Framework?

Struts Validator Framework enables us to validate the data of both client side and server side.

  • When some data validation is not present in the Validator framework, then programmer can generate own validation logic, this User Defined Validation logic can be bind with Validation Framework.
  • Validation Framework consist of two XML configuration Files:
    o Validator-Rules.xml file
    o Validation.xml file

Q4. What is the need of Struts?

We need Struts in Java because of following reasons:

  • Helps in creation and maintenance of the application.
  • Make use of Model View Controller (MVC) architecture. Where Model is referring to business or database, View is referring to the Page Design Code, and Controller is referring to navigational code.
  • Enables developer to make use of Jakarta Packages, Java Servlets, JavaBeans, ResourceBundles, and XML

Q5. What are the classes used in Struts?

Struts Framework consists of following classes:

  • Action Servlets: used to control the response for each incoming request.
  • Action Class: used to handle the request.
  • Action Form: it is java bean, used to referred to forms and associated with action mapping
  • Action Mapping: used for mapping between object and action.
  • Action Forward: used to forward the result from controller to destination.

Q6. How exceptions are handled in Struts application?

Exceptions are handled in struts by using any one of the following two ways:

  • Programmatically handling: In this exception are handled by using try and catch block in program. Using this programmer can define how to handle the situation when exception arises.
  • Declarative handling: In this exception handling is done by using the XML file. Programmer defines the exception handling logic in the XML file. There are two ways of defining the exception handling logic in the XML file:
    -Global Action Specific Exception Handler Definition.
    -Local Action Specific Exception Handler Definition.

Q7. What is MVC?

Model View Controller (MVC) is a design pattern used to perform changes in the application.

  • Model: Model is referring to business or database. It stores the state of the application. Model has no knowledge of the View and Controller components.
  • View: View is referring to the Page Design Code. It is responsible for the showing the result of the user’s query. View modifies itself when any changes in the model happen.
  • Controller: Controller is referring to navigational code. Controller will chose the best action for each incoming request, generate the instance of that action and execute that action.

Q8. Describe Validate() and reset() methods.

Validate() Method: this method is used to validate the properties after they are explored by the application.

  • Validate method is Called before FormBean is handed to Action.
  • This method returns a collection of ActionError.
  • Syntax of Validate() Method:
    public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

Reset() Method: this method is called by the Struts Framework with each request that uses the defined ActionForm.

  • Used to reset all the data from the ActionForm
  • Syntax of Reset() Method:
    public void reset() {}

Q9. What design patterns are used in Struts?

There are following types of design patterns are used in Struts:

  • Service to Worker
  • Dispatcher View
  • Composite View (Struts Tiles)
  • Front Controller
  • View Helper
  • Synchronizer Token

Q10.What is the difference between session scope and request scope when saving FormBean?

The difference between session scope and request scope when saving FormBean are following:

  • In Request Scope, values of FormBean are available to current request but in Session Scope, values of FormBean are available throughout the session.

Q11.What is the different actions available in Struts?

The different kinds of actions in Struts are:

  • ForwardAction
  • IncludeAction
  • DispatchAction
  • LookupDispatchAction
  • SwitchAction

Q12.What is DispatchAction?

The DispatchAction enable the programmer to combine together related function or class.

  • Using Dispatch Action programmer can combine the user related action into a single UserAction. like add user, delete user and update user
  • DispatchAction execute the action based on the parameter value it receives from the user.

Q13. How to use DispatchAction?

We can use the Dispatch Action we executing following steps:

  • Create a class that extends DispatchAction.
  • In a new class, add a method: method has the same signature as the execute() method of an Action class.
  • Do not override execute() method.
  • Add an entry to struts-config.xml

Q14. .What is the difference between ForwardAction and IncludeAction?

The difference between ForwardAction and InculdeAction are:

  • IncludeAction is used when any other action is going to intake that action whereas ForwardAction is used move the request from one resource to another resource.

Q15.What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction are given below:

  • LookupDispatchAction is the subclass of the DispatchAction
  • Actual method that gets called in LookupDispatchAction whereas DispatchAction dispatches the action based on the parameter value.

Q16.What is LookupDispatchAction?

The LookupDispatchAction class is a subclass of DispatchAction

  • The LookupDispatchAction is used to call the actual method.
  • For using LookupDispatchAction, first we should generate a subclass with a set of methods.
  • It control the forwarding of the request to the best resource in its subclass
  • It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

Q18. What is the use of ForwardAction?

The ForwardAction is used when we want to combine Struts with existing application.

  • Used when we want to transfer the control form JSP to local server.
  • Used to integrate with struts in order to take benefit of struts functionality, without writing the Servlets again.
  • Use to forward a request to another resource in your application

Q19.What is IncludeAction?

The IncludeAction is used to integrate the one action file in another action file.

  • It is same as ForwardAction but the only difference is that the resource is present in HTTP response.
  • Is used to combine the Struts functionality and control into an application that uses Servlets.
  • Use the IncludeAction class to include another resource in the response to the request being processed.

Q20. What are the various Struts tag libraries?

The various Struts tag libraries are:

  • HTML Tags: used to create the struts input forms and GUI of web page.
  • Bean Tags: used to access bean and their properties.
  • Logic Tags: used to perform the logical operation like comparison
  • Template Tags: used to changes the layout and view.
  • Nested Tags: used to perform the nested functionality
  • Tiles Tags: used to manages the tiles of the application

Q21. What is the life cycle of ActionForm?

The lifecycle of ActionForm is as follows:

  • Retrieve or Create Form Bean associated with Action
  • “Store” FormBean in appropriate scope (request or session)
  • Reset the properties of the FormBean
  • Populate the properties of the FormBean
  • Validate the properties of the FormBean
  • Pass FormBean to Action

Q22. What are the loop holes of Struts?

The drawbacks of Struts are following:

  • Absence of backward flow mechanism.
  • Only one single controller Servlets is used.
  • Bigger learning curve
  • Worst documentation
  • No exception present in this framework
  • Less transparent
  • Rigid approach.
  • With struts 1, embedding application into JSP can’t be prevented.
  • Non-XML compliance of JSP syntax

Q23. Difference between Html tags and Struts specific HTML Tags

Difference between HTML tag and Struts specific HTLM tags are:

  • HTML tags are static in nature but Struts specific HTML tags are dynamic in nature.
  • HTML tags are not User Defined whereas Struts tags can be user defined.
  • HTML tags provide the different templates and themes to the programmer whereas Struts specific HTML tag provides the integrating the property value with the Formbean properties.
  • HTML tags are integral part of Struts whereas Struts have HTML tag libraries.

Q24. What is the difference between session scope and request scope when saving FormBean?

The difference between session scope and request scope when saving FormBean are following:

  • In Request Scope, values of FormBean are available to current request but in Session Scope, values of FormBean are available throughout the session.

Q25. How to display validation errors on JSP page?

Validation error: Validation error are those error which arises when user or client enters the invalid format data into the form. For this validation of data struts enables the programmer with the Validator() method which validates both the data from client side and the server side.

We can display all error in the JSP page by using the following syntax in the code.

SYNTAX: <html:error/>

Q26. How to use forward action to restrict a strut application to MVC?

We can use the ForwarAction to restrict the Struts application to Model View Controller by following coding:

<forward name=”CitizenDetailsPage”
path=”/” />

<action path=”/gotoCitizenDetails”
type=”org.apache.struts.actions.ForwardAction” />

Q27. What is ActionMapping?

In action mapping is the mapping of the action performed by the user or client on the application.

-We specify the action class for a specific user’s action. Like we provide the path or URL and different view based on user event.
-We can also define where control of the page deviate in case of validation error in the form.
-We can include ActionMapping in code like this:
<action path=”/a” type=myclasse.A name=”myForm”>
<forward name=”Login” path=”/login.jsp”/>
<forward name=”error” path=”/error.jsp”/>

Q28. What is role of Action Class?

An Action class in the struts application is used to handle the request.

  • It acts as interface or communication medium between the HTTP request coming to it and business logic used to develop the application.
  • Action class consists of RequestProcessor which act as controller. This controller will choose the best action for each incoming request, generate the instance of that action and execute that action.
  • This should be in thread-safe manner, because RequestProcessor uses the same instance for no. of requests at same time.

Q29. How to combine the Struts with Velocity Template?

We can combine Struts and Velocity template by performing following steps:

1. Set classpath to Velocity JARs
2. Make web.xml file to identify the Velocity servlet.
3. Select Velocity toolbox.xml in WEB-INF directory.
4. Modify struts-config to point its views to Velocity templates instead of JSPs.
5. Create a Velocity template for each page you want to render.

Q31. In how many ways duplicate form submission can occurs?

The submission form can be duplicated by the any of the following ways:

  • Using refresh button.
  • By clicking submit button more than once before the server sent back the response.
  • By clicking back navigation button present in browser.
  • The browser is restores to submit the form again.
  • By clicking multiple times on a transaction that is delayed than usual.

Q32. What is the difference between Struts 1 and struts2?

The difference between struts1 and struts2 are below:

  • Struts1 uses ActionServlet as Controller where as Struts2 uses Filter as a controller.
  • Struts1 uses the ActionForm for mapping the JSP forms but in struts2 there no such ActionForm.
  • Struts1 uses Validation() method to validate the data in the page forms where as struts 2 validation of data is ensure by Validator Framework.
  • In Struts 1 the bean and logic tag libraries are often replaced by JSTL, but Struts 2 has such tag libraries that we don’t need to use JSTL.

Q33. What are the steps used to setup dispatch action?

To setup the dispatch action the following steps are used:

  • Create a subclass for DispatchAction.
  • Create method for logical action and their related actions.
  • Request Parameter is created for each action.
  • Define ActionMapping.
  • The JSP takes on the subclass defined for dispatch action method names as their values

Q34. What is difference between Interceptors and Filters?

The difference between Interceptors and filter are below:

  • Filters are based on Servlet Specification whereas Interceptors are based on Struts2.
  • Filters are executed only when patter matches whereas Interceptors executes for all request qualifies for a front controller.
  • Filters are not Configurable method calls whereas Interceptors methods can be configured.

Q35. What are the Custom tags?

Custom Tags are User Defined Tags, which means that user can create those tags depending upon their need in the application.

  • When a JSP page consisting of user- defined or custom tag is translated into a Servlet, the custom is also get translated into operation
  • Help in fast development of the application due to custom tag reusability.

Q36. What is the difference between empty default namespace and root namespace?

The difference between the empty default namespace and root name space are:

  • When namespace attribute is not defined then it is referred to as Empty Default Namespace whereas when name space attribute is assign with forward slash(/) then it is referred to as Root Name Space.
  • The root namespace must be matched.

Q37. What is the difference between RequestAware and ServletRequestAware interface?

The difference between RequestAware and ServletRequestAware are:

  • RequestAware enables programmer with the attributes in the Servlet Request as a map whereas ServletRequestAware enables programmer with HttpServletRequest object.
  • ServletRequestAware are more flexible than RequestAware.
  • ServletRequestAware makes action class highly coupled with Servlet environment which is not possible in RequestAware.

Q38. What are inner class and anonymous class?

Inner class: classes that are defined within other classes.

  • The nesting is a relationship performed between two different classes.
  • An inner class can access private members and data.
  • Inner classes have clearly two benefits:
    o Name control
    o Access control.
    Anonymous class: Anonymous class is a class defined inside a method without a name.
  • It is instantiated and declared in the same method.
  • It does not have explicit constructors.

Q39. What is struts.devMode?

The struts.devMode is used to make sure that framework is running in development mode or production mode by setting true or false. struts.devMode is set to false in production phase to reduce impact of performance. By default it is “false”. It is used because of the following reasons:

  • Resource Reloading: Resource bundle reload on every request
  • Modification: struts.xml can be modified without restarting or redeploying the application
  • Error Handling: The error occurs in the application will be reported, as oppose to production mode.

Q40. What are action errors?

Action error: when user or client submits the incorrect or invalid data in the application, then these errors are known as Action error.

  • Action errors are generated by the clients.
  • Action error should be determined as soon as possible.

The impacts of such Action Error are:

  • Wastage of server time and resources.
  • Negative impact on code quality.
    1. Can annotation-based and XML based configuration of actions coexists ?
    2. What is struts.devMode and why it is used ?
      struts.devMode is a key used in file (Can also be configured in struts.xml file as <constant name=”struts.devMode” value=”true” />) , to represent whether the framework is running in development mode or production mode by setting true or false. If set to development mode, it gives the following benefits : -
      > Resource bundle reload on every request; i.e. all localization properties file can be modified and the change will be reflected without restarting the server.
      > struts.xml or any configuration  files can be modified without restarting or redeploying the application
      > The error occurs in the application will be reported, as oppose to production mode.
      Also remember that struts.devMode should be marked as false in production environment to reduce impact of performance. By default it is “false”.
    3. How do you configure the annotation based action mapping ?
    4. What is the difference between empty default namespace and root name space ?
      If the namespace attribute is not defined in the package tag or assigned “” value then it is called empty default namespace.While if “/” is assigned as value to the namespace attribute then it is called as root namespace.
      The root namespace is treated as all other explicit namespaces and must be matched. It’s important to distinguish between the empty default namespace, which can catch all request patterns as long as the action name matches, and the root namespace, which is an actual namespace that must be matched.
    5. Which interceptor is responsible for setting action’s JavaBean properties ?
      com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action’s JavaBean properties from request.
    6. What is the difference between Action and ActionSupport ?
      Action is interface defines some string like SUCCESS,ERROR etc  and an execute() method. For convenience Developer implement this interface to have access to String field in action methods. ActionSupport on other hand implements Action and some other interfaces and provides some feature like data validation and localized error messaging  when extended in the action classes by developers.
    7. How do you get the HttpServletRequest object in an interceptor ?
      Here is the intercept method

      public String intercept(ActionInvocation invoke) throws Exception {
        ActionContext action=invoke.getInvocationContext();
        HttpServletRequest req=(HttpServletRequest)action.get(StrutsStatics.HTTP_REQUEST);
        return null;

      In the similar way you can get the response, by using StrutsStatics.HTTP_RESPONSE in get() method as above.

    8.  What is execute and wait interceptor ? 
      The ExecuteAndWaitInterceptor is great interceptor provided out of box in Struts2 for running long-lived actions in the background while showing the user a nice progress meter or a progress bar. For example while uploading a large file to the server we can use this interceptor to display a nice running progress bar instead of leaving the user in confusion that the application is not responding.This also prevents the HTTP request from timing out when the action takes more than 5 or 10 minutes.
    9.  Does the order in which interceptors execute matters ? If yes then why ?
      Well, the answer is yes and no.Some Interceptors are designed to be independent so the order doesn’t matter,but some interceptors are totally dependent on the previous interceptors execution.For example the validation and workflow interceptors,the validation interceptors checks if there is any error in the form being submitted to the action, then comes the workflow interceptor who checks if validation ( occured in the last) has any error,in presence of error it will not let the rest of the interceptors ( if any ) in the stack to execute.So this is very important that the validation interceptors execute first before the workflow. On the other hand lets say you wrote an interceptors who is doing the authentication and you have the user credential provided ( by the time this executes) it doesn’t matter where this interceptors is placed( It is a different fact that you would like to keep it in the top ).
    10. Who loads the struts.xml file ? Which Struts2 API loads the struts.xml file?
      In Struts2 FilterServlet is the responsible class for loading struts.xml file as we deploy the application on the container.Unlike Servlet (as with Struts1) needs the load-on-startup tag to load the front controller,a filter doesn’t need to have load on startup tag to be loaded as the application is deployed. As with servlet specification a filter is loaded/executed as the application  starts up.

      1. What is the DispatchAction (Struts1) equivalent in Strtus2 ?  
        Struts1 provided the facility of having related action methods in a Single Action class,depending on the method parameter, the mapped methods were executed.To achieve this we have to extend the DispatchAction class in Struts1.But this comes as default in Struts2, We need to provide the qualified methods in the action class( no need to inherit any class), and provide the mapping of action path/name to the method attribute in action tag(struts.xml) and proper code in view layer.
      2. What is the difference between DispatchAction and dynamic method invocation in Struts2 ?
      3. How many different ways can you retrive the request parameters from within interceptor ?
        Two ways.
        In the first way retrieve the HttpServletRequest from the ActionContext object and retrieve the parameters the usual way. Code

        ActionContext context=(ActionContext)invocation.getInvocationContext();
        HttpServletRequest request=(HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
        String username=(String)request.getParameter("user");

        The second way is pretty much the Struts2, by invoking the getParameters method on context object. Code

        ActionContext context=(ActionContext)invocation.getInvocationContext();   
        Map requestParameters=context.getParameters();
        String usernames=((String[])m.get("user"))[0];

        As you can see the map doesn’t return the parameter as String unlike the Servlet specification, but an array of String  (can be convinient for multivalued UI controls check box,single value UI controls data can be retrived as in above code ).

      4. What is abstract package in Struts2, and what is its use ?
        An abstract package usually defines inheritable components such as intercetpor,different interceptor stacks,result types etc.But doesn’t contain any actions.The way we declare a package as abstract is through the package elements attribute as abstract and setting the value to “true”. By default ( if abstract attribute is not mentioned) it is false.Struts-default.xml is an example of abstract package.
      5. Does Struts2 mandates of implementing the Action interface in action classes to have the default Action method (execute)?
        Struts2 doesn’t mind if the action classes doesn’t implement the Action interface, to have the execute method executed on default action method selection.Even though it appears that Action interfaces has the execute method declaration and one must implement it to have the execute method overriden in the action classes,Struts2 takes it as an informal contract with the developer by letting the developer to have an execute method conforming to the signature of execute method.Whenever Struts2 finds any voilation to the declaration of the method in unimplemented action class it throws the exeception.