QnA

Can constructors be overridden?

Yes



In a method call,which objects are passed by value &which ones are passed by reference?

primitive by value &objects by reference.



What is association,aggregation and composition?

1) Association is a channel between classes through which messages can be sent. As sending messages translates to calling methods in Java,Associations are typically (but not necessarily) implemented by references.
2) An Aggregation is an Association which denotes an “is part of”relationship. Unfortunately,the definition of this relationship is quite lax,so basically everyone is using his own interpretation. The only definitive (?) property is that in an instance graph,aggregations are not allowed to be circular –that is,an object can not be “a part of itself”. (or) When building new classes from existing classes using aggregation,a composite object built from other constituent objects that are its parts.Java supports aggregation of objects by reference,since objects can’t contain other objects explicitly.
3) A Composition adds a lifetime responsibility to Aggregation. In a garbage collected language like Java it basically means that the whole has the responsibility of preventing the garbage collector to prematurely collect the part –for example by holding a reference to it. (In a language like C++,where you need to explicitely destroy objects,Composition is a much more important concept.) Only one whole at a time can have a composition relationship to a part,but that relationship doesn’t need to last for the whole lifetime of the objects –with other words,lifetime responsibility can be handed around.



Are static methods inherited
Yes


Can static methods be overriden

No. The method which gets called depends upon the type of reference &not on the object it points to.



Name different creational patterns in OO design?

1) Factory pattern

2) Single ton pattern

3) Prototype pattern

4) Abstract factory pattern

5) Builder pattern



Explain the different forms of Polymorphism.

1) Method overloading

2) Method overriding through inheritance

3) Method overriding through the Java interface



How to make an object completely encapsulated?

By making all instance variables private &defining getter setter methods.



Is it possible to define a class which extends an abstract class,yet provides no implementation for abstract methods of superclass?

Yes. define the subclass as abstract.


Can constructors be inherited?
No.


How are this &super keywords used in constructors?

this() is used to invoke other constructor of same class.
super() is used to invoke constructor of superclass.



Diff between ArrayList &Vector?

ArrayList is NOT synchronized by default.
Vector List is synchronized by default.


How do you decide when to use ArrayList and when to use LinkedList?

If you need to support random access,without inserting or removing elements from any place other than the end,then ArrayList offers the optimal collection.

If,however,you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially,then LinkedList offers the better implementation.



Which collection will you use if you wnat to store list of unique elements?
Set


When to use HashSet?
When you want a collection with no duplicates and you don’t care about order when you iterate through it. It uses the hashcode of the object being inserted


When to use TreeSet?

The elements are sorted according to the natural order of elements or by the comparator provided at creation time.



When to use TreeMap?

Data is sorted according to ascending order of keys according to the natural order for the key’s class,or by the comparator provided at creation time.



Difference between HashMap &HashTable

Hashmap Hashtable

Single null key &multiple null key &values are not allowed.

null values allowed.

Iterator is fail-safe Enumerator is not failsafe

Not synchronized. Synchronized.



Can abstract classes have constructors? if yes,why?

Yes. Constructors in concrete subclasses can call super().



What is autoboxing?

Automatic conversion between primitive data &their wrapper classes.



What is Generics? why should we use it?

Generics provides a way to communicate to the compiler,the kind of objects a particular collection will hold. This eliminates the need to do explicit casting whenever we are fetching elements from a collection. Since the type check is done at compile time,it guarentees that at runtime no class cast exceptions are thrown.



Explain String pooling.

Whenever a object of String class is created using ‘=’a object is created in String pool of the JVM but in case the object is created using ‘new’keyword,two objects get created,one goes to non-pooled memory i.e. normal memory and the other goes to String pool memory. Only one reference will be created in this case as well as in the prior case.

This concept arises from the ‘Immutability’of String class. Immutability of a string means that whenever a object of type String is created,it gets memory in String pool and will stay there forever (Until the JVM restarts). Any further String objects created with same string as value will refer to the same String from string pool. This is better explained in a example below:

String str1 = "abc"';
System.out.println(str1.hashcode());// Output 1

String str2 = “abc”;
System.out.println(str2.hashcode());// Output 2

This is worth noting that the ‘Output 1′and ‘Output 2′will be same justifying the immutability of Strings.



Explain diff between StringBuffer &StringBuilder.

StringBuffer is synchronized whereas builder isn’t.

StringBuilder offers better performance than buffer. we should use it when we dont want synchronization.



Difference between ClassNotFoundException &NoClassDefFoundError?

ClassNotFoundException –class not in classpath

NoClassDefFoundError –class definition could not be loaded. Main reason for this is,there is a static block in class definition and an exception was thrown from one of the statements in static block.



What are ternary operators?

int i = (flag==true)?1,0;

same as

 

if(flag == true)

i = 1;

else

i = 0;

 



What is externalization &localization?

Externalization is extracting the String displayed on UI into a properties file.

Localization is creating locale specific files,for storing display strings.



What are webservers &app servers?

Webservers are used to serve static content &offer no processing.

App servers can serve static as well as dynamic content &offer server side processing.



What are static imports?

With static import,you can import members of a class as well.

e.g. there is class say Math which has a constant like PI &method like cos().

Ideally we will import Math class &use Math.PI or Math.cos().

Using static import like below,

import java.lang.Math.*;

We can use PI or call cos() directly as if it were the memeber of executing class.



what isNaN function do?

It tells whether a given string is a valid number or not.

It returns true,if given string is NOT a valid number.



tell 2 ways arrays can be built &referenced?

Reference by index

 

var arr = new Array();

arr[0] = “test1″;

arr[1] = “test2″;

var result = arr[1];//Gets the object at index 1

Reference by name(key). This is similar to HashMap in Java.

var arr = new Array();

arr["alpha"] = “test1″;

arr["beta"] = “test2″;

arr["gamma"] = “test2″;

var result = arr["beta"];//Gets the object which was stored with key “beta”i.e. “test2″.



what is json?

JSON (JavaScript Object Notation) is a lightweight data-interchange format.



Is it possible to call a function automatically at regular intervals?

 

var timerId = window.setInterval(“foo()”,2000);//calls function foo(),at every 2 seconds,infinitely.

window.clearInterval(timerId);//Stops calling the function.

 



How can you call a function asynchronously OR how can you call a function after certain time?

window.setTimeout("foo()",2000);//calls function foo() once after 2 seconds.



How to generate random number?

 

//return a random integer between 0 and 10

var randomNum = Math.floor(Math.random()*11);

 



How to use Regular Expressions in JavaScript? OR How to do pattern matching?

 

var str=”The rain in SPAIN stays mainly in the plain”;

var regEx = /ain/gi;

 

‘ain’is matching string,‘g’means global means search all occurances,‘i’means case insensitive search.

 

alert(str.match(patt1));

 

Result –ain,AIN,ain,ain



How do you identify browser through JS?

 

var userAgent = navigator.userAgent;

alert(userAgent);

 

Following link has userAgent values for different browser+Operating system combinations.

http://www.zytrax.com/tech/web/browser_ids.htm

By doing userAgent.indexOf(),you can identify client’s browser type,version &OS.



What does escape() function do?

It encodes a given string.

 

var str = “Need tips? Visit W3Schools!”;

var escStr = escape(str);

alert(escStr);

// returns Need%20tips%3F%20Visit%20W3Schools%21

 



Whats the benefit of using AJAX?

Imagine there a very big page and you need to update only small part.

Using AJAX,you can achieve this without reloading entire page.

This saves time &bandwidth.

Application feels more responsive.



How do you create Ajax object?

All modern browsers have built-in AJAX function.


var ajax =new XMLHttpRequest();

Whereas for older versions of IE(5,6) you can do,

 

var ajax = new ActiveXObject(“Microsoft.XMLHTTP”);

 

Thus following code should work on all browsers,

 

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+,Firefox,Chrome,Opera,Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6,IE5

xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

 



How do you make Http GET &POST request through Ajax?

Create xmlhttp object.

 

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+,Firefox,Chrome,Opera,Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6,IE5

xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

 

GET request

 

var url = “getdata.jsp”;

var params = “language=en&country=us”;

xmlhttp.open(“GET”,url+”?”+params,true);

xmlhttp.onreadystatechange = function(){//Call a function when the state changes.

//readyState 4 means,the data is fetched &available in xmlHttp object.

if(xmlhttp.readyState == 4 &&xmlhttp.status == 200){

alert(xmlhttp.responseText);

}

}

http.send(null);

 

POST request

 

var url = “getdata.jsp”;

var params = “lorem=ipsum&name=binny”;

http.open(“POST”,url,true);

//Send the proper header information along with the request

xmlhttp.setRequestHeader(“Content-type”,“application/x-www-form-urlencoded”);

xmlhttp.setRequestHeader(“Content-length”,params.length);

xmlhttp.setRequestHeader(“Connection”,“close”);

xmlhttp.onreadystatechange = function(){//Call a function when the state changes.

if(xmlhttp.readyState == 4 &&xmlhttp.status == 200){

alert(xmlhttp.responseText);

}

}

xmlhttp.send(params);



What is event bubbling?

This is a mechanism,where a single event like mouse click,can “bubble”upwards to the parent elements up in hierarchy from the child element that was actually clicked.

Following page explains event bubbling in detail.

Event bubbling

Check below page to see how to cancel bubbling at a particular level of hierarchy.

Cancel bubbling



How do you disble right click on a page?

 

document.oncontextmenu = new Function(“return false;”)

 



How do you detect mouse &keyboard events?

 

document.onkeypress = handleKeyPress;

 

See below for list of supported events.

DOM Events



What is Cookie &How to set it?

A Cookie is like database on browser,which is only accessible to the website that sets it.
To set a cookie.


document.cookie = "language_preference=eng";

To read a cookie.


var cookieStr = document.cookie;



Whats the difference between Where and Having clause?

“Where”is a kind of restiriction statement. You use where clause to restrict all the data from DB.Where clause is using before result retrieving.
But Having clause is using after retrieving the data.Having clause is a kind of filtering command.


What are the tradeoffs with having indexes?

Faster select and slower updates.
Updates are slower because in addition to updating the table you have to update the index.


What is normalization &de-normalization? In what cases will you do de-normalization?

Normalization –eliminating redundant info from table.
De-normalization –Allowing redundancy. Benefits are faster performance due to less joins.


Why can a 'group by' or 'order by' clause be expensive to process?

These clauses often requires creation of temporary tables to process results of query.


What is SQL View?

An output of a query can be stored as a view. View acts like small table which meets our criterion.


Whats the diff between TRUNCATE &DELETE commands?

The DELETE command is used to remove rows from a table.TRUNCATE removes all rows from a table.
TRUNCATE does not fire any trigger &cannot be rolled back &hence faster than DELETE.


How can we get second highest salary from Employee database?


SELECT MAX(SALARY)
FROM EMPLOYEE
WHERE SALARY!=(SELECT MAX(SALARY) FROM EMPLOYEE);



Static &Dynamic SQL

Static SQL
==========
Pros:
1) Compile at bind time –Since the statement is compiled only once and before we run our workload,we have all the database resources in order to generate the most optimal query execution plan. In DB2,there are 9 levels of optimization,being 5 the default one. When we bing our application package,we can pick the highest optimization level – 9 – and get the most optimal execution plan. Using a higher optimization level requires more resources for the compile phase,but since our workload is not yet running,we can afford this high resources requirement.
2) Security –Security is probably the most common reason why people use static SQL instead of dynamic SQL. Static SQL allows the DBA to set authorization at the package level. For example,consider an application package app1,that provides SQL functionality to select employee’s name and address from the table employees. The DBA can five user JOHN execution privileges on package app1,even if user JOHN does not have SELECT authority on table employees. Static SQL provides a much finer layer of security.

Cons:
1) Need to bind before runtime –Although binding before runtime usually allows for more optimized access plans,doing this in a test or development environment can be cumbersome.
2) Lack of tooling support –most of current IDEs provide coding assistance with support for APIs like JDBC. The lack of support from development tools discourages the use of static SQL.

Dynamic SQL
===========
Pros:
1) IDEs and APIs –Using eclipse to develop Java code that interacts with the database using JDBC or JPA is much simpler than developing a SQLJ application.
2) Statement caching –Dynamic statement caching avoids the need to compile the same statement multiple times,increasing the performance to values close to static SQL. However,bear in mind that a cache miss will be extremely expensive.
better statistics. Because the statement is compiled at runtime,it uses the latest statistics available,contributing to a better execution plan.

Cons:
1) Compile at runtime. There are a few reasons why compile at runtime can be a bad thing:
i] Every time a statement is executed,it needs to be compiled,increasing the total statement execution time
ii] The compile time will account for the total execution time,so using higher optimization levels may slow down the overall performance instead of improving it.
iii] Because the statement is only compiled at runtime,errors in the SQL statement won’t be detected until runtime.



How self join works?

A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to compare values in a column with other values in the same column in the same table. One practical use for self-joins:obtaining running counts and running totals in an SQL query.

To write the query,select from the same table listed twice with different aliases,set up the comparison,and eliminate cases where a particular value would be equal to itself.

Example -
List down employee’s &their manager’s name in one row.

SELECT e.first_name AS 'Employee FN',e.last_name AS 'Employee LN',m.first_name AS 'Manager FN',m.last_name AS 'Manager LN'
FROM employees AS e LEFT OUTER JOIN employees AS m
ON e.manager =m.id



How to create a JDBC connection?


import java.sql.* ;

class JDBCQuery
{
public static void main( String args[] )
{
try
{
// Load the database driver
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver”) ;

// Get a connection to the database
Connection conn = DriverManager.getConnection( “jdbc:odbc:Database”) ;

// Print all warnings
for( SQLWarning warn = conn.getWarnings();warn != null;warn = warn.getNextWarning() )
{
System.out.println( “SQL Warning:”) ;
System.out.println( “State:”+ warn.getSQLState() ) ;
System.out.println( “Message:”+ warn.getMessage() ) ;
System.out.println( “Error:”+ warn.getErrorCode() ) ;
}

// Get a statement from the connection
Statement stmt = conn.createStatement() ;

// Execute the query
ResultSet rs = stmt.executeQuery( “SELECT * FROM Cust”) ;

// Loop through the result set
while( rs.next() )
System.out.println( rs.getString(1) ) ;

// Close the result set,statement and the connection
rs.close() ;
stmt.close() ;
conn.close() ;
}
catch( SQLException se )
{
System.out.println( “SQL Exception:”) ;

// Loop through the SQL Exceptions
while( se != null )
{
System.out.println( “State:”+ se.getSQLState() ) ;
System.out.println( “Message:”+ se.getMessage() ) ;
System.out.println( “Error:”+ se.getErrorCode() ) ;

se = se.getNextException() ;
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
}



Explain different types of statements

Regular statement (use createStatement method),
Prepared statement (use prepareStatement method)
Callable statement (use prepareCall)


How do you call a stored procedure from JDBC?


CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();



What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?

The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes.
Generally speaking,a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does.


How to Make Updates to Updatable Result Sets?

You need to create a ResultSet object that is updatable.
In order to do this,you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT COF_NAME,PRICE FROM COFFEES");



What are the different JDB drivers available?

JDBC Driver Type Comparison
CategoryType 1Type 2Type 3Type 4
Basic DescriptionJDBC to ODBC BridgeJDBC using Native MethodsMiddleware JDBC DriversPure Java Driver
Requires native install on clientYesYesNoNo
Cross platformNoMostlyYesYes
Supports specific DB features e.g. OracleBlobNoYesUsually NoYes
Requires additional serverNoNoYesNo

Type 4 is the fastest.



How do you handle transaction?

Connection Object has a method called setAutocommit ( boolean flag).
For handling our own transaction we can set the parameter to false and begin your transaction .
Finally commit the transaction by calling the commit method.

Note:In Spring,you can specify @Transactional annotation,to declare that this method is called in transaction. Rest of the stuff is handled by Spring.



Whats are static &dynamic cursors?

Static Cursor
=============
When you request a static cursor,you are requesting a snapshot of the data at the time the Recordset is created. Once the client has received all the rows,the cursor can scroll through all data without any further interaction with the server. The cursor position can be changed using both relative positioning (offsets from the current,top or bottom row) and absolute positioning (using the row number). The static cursors only shortcoming is that changes made to the database while the Recordset is open arent made available to a client using a static cursor.So,it’s less resource expensive.

Dynamic Cursor
==============
A dynamic cursor,on the other hand,makes database changes available as they happen. Because the dynamic cursor requires the database provider to reorder data in the Recordset as it changes on the server,it is much more expensive than the static cursor in terms of the processing it requires. Also,because the order of the underlying records could change,only relative positioning is available to dynamic cursors. Lastly,dynamic cursors dont support bookmarks. If you need bookmark support,use a keyset or static cursor.

The type of cursor you select changes the efficiency of your application,as well as reliability of the data.When you access some data that is not frequently changed use a static cursor and vice-versa.



What are different isolation levels in MSSQL 2008 R2?

Taken from Transactions in MSSQL 2008-R2.

SET TRANSACTION ISOLATION LEVEL
{READ UNCOMMITTED
| READ COMMITTED
| REPEATABLE READ
| SNAPSHOT
| SERIALIZABLE
}
[ ;]

1. READ UNCOMMITTED –Specifies that statements can read rows that have been modified by other transactions but not yet committed.
2. READ COMMITTED –Specifies that statements cannot read data that has been modified but not committed by other transactions. This prevents dirty reads. Data can be changed by other transactions between individual statements within the current transaction,resulting in nonrepeatable reads or phantom data. This option is the SQL Server default.
3. REPEATABLE READ –Specifies that statements cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by the current transaction until the current transaction completes.
4. SNAPSHOT –Specifies that data read by any statement in a transaction will be the transactionally consistent version of the data that existed at the start of the transaction. The transaction can only recognize data modifications that were committed before the start of the transaction. Data modifications made by other transactions after the start of the current transaction are not visible to statements executing in the current transaction. The effect is as if the statements in a transaction get a snapshot of the committed data as it existed at the start of the transaction.
5. SERIALIZABLE –Specifies the following:
i) Statements cannot read data that has been modified but not yet committed by other transactions.
ii) No other transactions can modify data that has been read by the current transaction until the current transaction completes.
iii) Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.


Whats the difference between thin &thick client?

Oracle has a thin client driver,which mean you can connect to a oracle database without the Oracle client installed on your machine.
Thick client would need the Oracle Client,database drivers,etc.. Drivers include JDBC-ODBC bridge drivers,JDBC drivers depending on tns resolution.


What is the difference between Resultset and RowSet?

A ResultSet maintains a connection to a database and because of that it can?t be serialized. Also we cant pass the Resultset object from one class to other class across the network.

RowSet is a disconnected,serializable version of a JDBC ResultSet and also the RowSet extends the ResultSet interface so it has all the methods of ResultSet. The RowSet can be serialized because it doesn?t have a connection to any database and also it can be sent from one class to another across the network.



What is Jakarta Struts Framework?

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications.


Explain struts flow


1. request comes.
2. corrosponding action class will be searched in the struts.xml
3. mapped form-bean will be populated with data.
4. execute method of mapped action servlet will be executed and result will be mapped in struts.xml with tag.
5. mapped jsp/html page with forward will be displayed.

———————————————————–

1) The request received by hte ActionServlet which is the default Controller in Struts…
2)ActionServlet then call RequestProcesser.preProcess method to find the formbean,populate the value to it,validate the values..
3)Once the validating has finished,the ActionServlet’s RequestProcesser.preProcess() method call Action class’s execute method where the original business processing begins….
4)The action class process the method and reurns the result to ActionServlet…..
5)In returning the Action class provides the key to the corresponding ActionServlet to determine the reult acqiured fromprocessing will be diplayed…
6)The ActionServlet then display results to client using the key provided by the action class.



What is ActionServlet?

In the the Jakarta Struts Framework this class plays the role of controller.


What is Action Class?

The Action Class is part of the Model and is a wrapper around the business logic.


What is ActionForm?

ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application.
ActionForm object is automatically populated on the server side with data entered from a form on the client side.


What is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data.
Validator framework is a part of Jakarta Commons project and it can be used with or without Struts.
Validator Questions


Give the Details of XML files used in Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml.
The validator-rules.xml defines the standard validation routines,these are reusable and used in validation.xml to define the form specific validations.
The validation.xml defines the validations applied to a form bean.


How you will display validation fail errors on jsp page?

Following tag displays all the errors:
<html:errors/>


Is struts threadsafe? Give an example.

Struts is not only thread-safe but thread-dependant.
The response to a request is handled by a light-weight Action object,rather than an individual servlet.
Struts instantiates each Action class once,and allows other requests to be threaded through the original object.
This core strategy conserves resources and provides the best possible throughput.


What are the various Struts tag libraries?

Bean tag library –Tags for accessing JavaBeans and their properties.
HTML tag library –Tags to output standard HTML,including forms,text boxes,checkboxes,radio buttons etc..
Logic tag library –Tags for generating conditional output,iteration capabilities and flow management
Tiles or Template tag library –For the application using tiles
Nested tag library –For using the nested beans in the application


What is Struts actions and action mappings?

A Struts action is an instance of a subclass of an Action class,which implements a portion of a Web application and whose perform or execute method returns a forward.
An action can perform tasks such as validating a user name and password.
An action mapping is a configuration file entry that,in general,associates an action name with an action.


What are the difference between <bean:message> and <bean:write>?

<bean:message>:This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.
<bean:write>:This tag is used to output property values from a bean.


What is DispatchAction?

The DispatchAction class is used to group related actions into one class.
Using this class,you can have a method for each logical action compared than a single execute method.


What is the use of ForwardAction?

The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions.
You can use this class to take advantage of the Struts controller and its functionality,without having to rewrite the existing Servlets.
Use ForwardAction to forward a request to another resource in your application,such as a Servlet that already does business logic processing or even another JSP page.
By using this predefined action,you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.


What is IncludeAction?

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets.
Use the IncludeAction class to include another resource in the response to the request being processed.


What is the difference between ForwardAction and IncludeAction?

The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp.
Use ForwardAction to forward a request to another resource in your application,such as a Servlet that already does business logic processing or even another JSP page.


What is DynaActionForm?

A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file),without requiring the developer to create a Java class for each type of form bean.


How the exceptions are handled in struts?

Programmatic exception handling using try catch blocks.
Declarative exception handling -


How can we make message resources definitions file available to the Struts framework environment?

We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.



What is the life cycle of ActionForm?

1. Retrieve or Create Form Bean associated with Action
2. “Store”FormBean in appropriate scope (request or session)
3. Reset the properties of the FormBean
4. Populate the properties of the FormBean
5. Validate the properties of the FormBean
6. Pass FormBean to Action


How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

You will need to set the appropriate HTTP header attributes to prevent the dynamic content
output by the JSP page from being cached by the browser.

<%
response.setHeader("Cache-Control","no-store");//HTTP 1.1
response.setHeader("Pragma","no-cache");//HTTP 1.0
response.setDateHeader ("Expires",0);//prevents caching at the proxy server
%>



'Response has already been commited.' error. What does it mean?

This error show only when you try to redirect a page after you already have written something in your page.


How do I use a scriptlet to initialize a newly instantiated bean?

A jsp:useBean action may optionally have a body.
If the body is specified,its contents will be automatically invoked when the specified bean is instantiated.


How can I declare methods within my JSP page?


<%!
public String someMethod(HttpServletRequest req){
}
%>



Go through all tags used in JSP

HTML Comment –Generates a comment that can be viewed in the HTML source file.
Hidden Comment –Documents the JSP page but is not sent to the client.
Declaration –Declares a variable or method valid in the scripting language used in the page.
Expression –Contains an expression valid in the scripting language used in the page.
Scriptlet –Contains a code fragment valid in the scripting language used in the page.
Include Directive –Includes a file of text or code when the JSP page is translated.
Page Directive –Defines attributes that apply to an entire JSP page.
Taglib Directive –Defines a tag library and prefix for the custom tags used in the JSP page.
<jsp:forward> –Forwards a client request to an HTML file,JSP file,or servlet for processing.
<jsp:getProperty> –Gets the value of a Bean property so that you can display it in a JSP page.
<jsp:include> –Sends a request to an object and includes the result in a JSP file.
<jsp:plugin> –Downloads a Java plugin to the client Web browser to execute an applet or Bean.
<jsp:setProperty> –Sets a property value or values in a Bean.
<jsp:useBean> –Locates or instantiates a Bean with a specific name and scope.


What are custom JSP tags?

A custom tag is a user-defined JSP language element.
When a JSP page containing a custom tag is translated into a servlet,the tag is converted to operations on an object called a tag handler.
The Web container then invokes those operations when the JSP page’s servlet is executed.


What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource.
But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.


Is JSP technology extensible?

Yes. JSP technology is extensible through the development of custom actions,or tags,which are encapsulated in tag libraries.


What will you do display large number of data objects/information on a web page?

Use pagination.


How to Upload a textfile from JSP to Servlet?

<input type="file" />
FORM tag must contain the following attribute,then only it will validate file upload.
enctype="multipart/form-data"


What is the diff between JSP session &servlet session

Nothing.


How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automatically forwarded to an error processing page.
<%@ page errorPage="error.jsp" %>

Within error.jsp,if you indicate that it is an error-processing page,via the directive:
<%@ page isErrorPage="true" %>



How to pass information from JSP to included JSP?

Using <%jsp:param> tag.


What are top down &bottom approaches in developing a web service?

In top-down approach (contract first),the WSDL is designed from a business point of view and is not driven by a service consumer or an existing application. The “WSDL to Java”tool generates java code according to JAX-RPC or JAX-WS. These classes can then adapt the existing business logic.

The bottom up approach does generate web services which design is driven from an application point of view (developer driven) and will not address the need for other consumers.



What is XML-RPC?

XML-RPC is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism.


What is SOAP?

SOAP,is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks.


What are the types of web service?

1. SOAP based
2. REST based


what makes spring applications more testable than EJB?

o Spring reduces tight coupling between dependent objects. Allowing each object to be tested independently.
o Spring mostly involves POJOs,so unlike EJBs there is no need to start J2EE container to do testing.


What is Inversion of Control(IoC) or Dependency Injection?

o Instead of object looking up dependencies from container,the container gives the dependencies to the object at instantiation,without being asked.
o An inversion of responsibility,with regard to how an object obtains the references to collaborating objects.


What is aspect oriented programming?

Separation of business logic from system services(such as logging,transaction management).
Spring comes with rich support for Aspect Oriented programming.


What are different modules in spring framework?

1. Core container -
Provides fundamental functionality of spring framework. Contains BeanFactory interface,that is used in applying IoC to our application.

2. Application context module -
Implements BeanFactory &extends it’s functionality,by adding support for I18n messages,application life cycle events &validation.
It also provides enterprise services like email,JNDI access,EJB integration etc.

3. AOP(Aspect oriented programming) module -
Serves as basis of developing our own aspects in spring enabled application.

4. JDBC &DAO -
Abstracts away boilerplate code related to Data Access like getting connection,executing statements etc form the developer.
All configuration is moved to xml definition of bean.
Uses AOP module for transaction support.

5. O-R Mapping module -
Spring does not have it’s own OR mapping implementation,but provides hooks for several popular ORM frameworks like Hibernate,JDO etc.

6. Web module -
Builds upon Application Context module.
Provides context that is appropriate for web-based applications. Integration support with Jakarta Struts.

7. MVC Framework -
Spring has it’s own MVC framework,but it can also be integrated with Struts.
Allows to declaratively bind request parameters to business objects.



What does a bare minimum spring application contain?

1. Service interface (not required,but recommended) -
Declares service method required by application.

2. Service implementation or the actual Bean
Implements above service interface,by providing concrete service methods.

3. Spring config file
Tells the container,how to configure the bean.

4. Application classe that uses services provided by bean.



What is a <bean>element?

This Element inside spring config xml,is used to tell the spring container about a class &how it should be configured.


What does a typical <bean%gt;element contain?

Here is a most simple bean declaration.


<bean id="dfOrder" class="com.att.yoda.dataInfo.DfOrder">
<property name="customerName">
<value>John Doe</value>
</property>
</bean>

o id –Name of the bean
o class –Bean’s fully qualified class name.
o <property>–Used to set property
o name –Name of the property in bean class. In example,this means we are asking spring to call setCustomerName() method.
o <value>–value of property “customerName”.



What is an alternative way to set property in a bean,apart from element?

Suppose class DfOrder has constructor which takes customerName as argument.
Then we can use it’s constructor to set the property “customerName”.

<bean id=”dfOrder”class=”com.att.yoda.dataInfo.DfOrder”>
<constructor-arg>
<value>John Doe</value>
</constructor-arg>
</bean>



Is J2EE container(app server) absolutely required for running a spring based application?

No.
Application class can be a simple Java class with main method.
Sample code inside main method will be,

BeanFactory factory = new XmlBeanFactory("spring-config.xml");
DFOrder dfOrder = (DFOrder) factory.getBean("dfOrder");
dfOrder.someMethod();



OFF TOPIC - What is ServiceLocator?

ServiceLocator is typically used in obtaining &caching remote resources.
It helps remove the need for lookup code everywhere in the application.
Remote resource can be an EJB,WebService endpoint,RMI’s remote reference etc.


What is a BeanFactory?

It is a root interface for accessing a Spring bean container.
It is an implementation of factory design pattern. But unlike other implementation it can create &deliver different types of beans.
Also because BeanFactory is aware of all beans within an application,it is able to create association between beans as beans are being instantiated.
This removes burden of configuration from the bean itself &it’s client.


How did you started spring container within your application?

Since ours was a web-based project,we used web.xml to start spring container.
We used ContextLoaderListener for starting spring container.
Specifically,
o Specified spring configuration xml file location through contextConfiguration context-param.
o Registered ContextLoaderListener as listener class.


What is ApplicationContext?

This is another interface in addition to BeanFactory,that provides configuration for a spring application.
It extends BeanFactory interface &provides several addition features.


What is advantage of using ApplicationContext container over BeanFactory container in spring?

o Application contexts provides support for i18n of text messages.
o Application contexts provides a generic way of loading file resources such as images.
o Application contexts can publish events to beans that are registered as listeners.


What are different implementations of ApplicationContext?

Implementations differ,based on from where they load context definition xml.
1 ClassPathXmlApplicationContext –From Xml file in classpath,means Xml can also reside in a jar file which is in classpath.

2 FileSystemXmlApplicationContext –From xml file on file system.

3 XmlWebApplicationContext –From an xml file contained within a web application



What is the difference in the way beans are initialized within BeanFactory &ApplicationContext?

o BeanFactory loads beans lazily i.e. it defers bean creation,until getBean() is called.
o ApplicationContext preloads all singleton beans upon context startup. Other beans are still loaded lazily.


Explain life cycle of bean within BeanFactory container.

1. Container finds beans definition &instantiates it.
2. Populates bean’s properties using dependency injection.
3. If bean class implements “BeanNameAware”interface,the factory calls bean’s setBeanName() method,passing beans ID.
4. If bean class implements “BeanFactoryAware”interface,the factory calls bean’s setBeanFactory() method,passing instance of factory itself.
5. If there are any “BeanPostProcessors”associated with bean,their postProcessBeforeInitialization() methods will be called.
6. If any “init-method”is specified in the bean,it will be called.
7. If there are any “BeanPostProcessors”associated with bean,their postProcessAfterInitialization() methods will be called.

Since this point,beans are ready to be used by the application. It will remain in bean factory till its no longer needed.



What is the difference between life cycle of a bean in BeanFactory container &ApplicationContext container?

Only difference for ApplicationContext container is,if bean implements “ApplicationContextAware”interface,container will call bean’s setApplicationContext() method.
Sequence-wise,this method is called between step 4 &5.


What will you do,if you want to perform cleanup on a bean,before its destroyed? e.g. releasing db connections,file handlers etc.

There are 2 ways in which we can call our cleanup code.
1. Implement DisposableBean interface. Container will call it’s destroy() method before removing bean.
2. Specify a custom “destroy-method”.