Big Data Notes

[root@localhost training]# hadoop
Usage: hadoop [–config confdir] COMMAND
where COMMAND is one of:
namenode -format     format the DFS filesystem
secondarynamenode    run the DFS secondary namenode
namenode             run the DFS namenode
datanode             run a DFS datanode
dfsadmin             run a DFS admin client
mradmin              run a Map-Reduce admin client
fsck                 run a DFS filesystem checking utility
fs                   run a generic filesystem user client
balancer             run a cluster balancing utility
fetchdt              fetch a delegation token from the NameNode
jobtracker           run the MapReduce job Tracker node
pipes                run a Pipes job
tasktracker          run a MapReduce task Tracker node
job                  manipulate MapReduce jobs
queue                get information regarding JobQueues
version              print the version
jar <jar>            run a jar file
distcp <srcurl> <desturl> copy file or directories recursively
archive -archiveName NAME -p <parent path> <src>* <dest> create a hadoop archive
oiv                  apply the offline fsimage viewer to an fsimage
classpath            prints the class path needed to get the
dfsgroups            get the groups which users belong to on the Name Node
mrgroups             get the groups which users belong to on the Job Tracker
Hadoop jar and the required libraries
daemonlog            get/set the log level for each daemon
CLASSNAME            run the class named CLASSNAME
Most commands print help when invoked w/o parameters.
[root@localhost training]#


Venkat FAQ

Jboss 7
Jar files location : modules/wicore/main/ and module.xml
<module xmlns=”urn:jboss:module:1.1″ name=”wicore”>
<resource-root path=”axiom-api-1.2.2.jar”/>
<resource-root path=”axiom-dom-1.2.2.jar”/>
<resource-root path=”axiom-impl-1.2.2.jar”/>
Properties file : server/settings/ propertie.ini / properties.cfg

Deployment : standalone/deployment

Standalone.xml : standalone/configuration /standalone.xml

<datasource jndi-name=”java:/cms” pool-name=”MySqlDS” enabled=”true” use-java-context=”true”>

Legacy collection frame works are Synchronized:

New collection framework Not synchronized:
Comparator (ordering based on name of Employee)

Employee emp1 = new Employee(1, “One”);
Employee emp2 = new Employee(5, “Five”);
Employee emp3 = new Employee(3, “Three”);
Employee emp4 = new Employee(4, “Seven”);
Employee emp5 = new Employee(2, “Two”);

List<Employee> empList = new ArrayList<Employee>();

Collections.sort(empList, new Comparator<Employee>(){
public int compare(Employee o1, Employee o2){
return o1.getEmpNo()-o2.getEmpNo();

Main difference between transient vs volatile variable is that transient variables are not serialized during Serialization process in Java while volatile variables are used to provide alternative synchronization in Java.
Important points on Volatile keyword in Java
volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread’s local cache.
Using Volatile keyword in Java on variables reduces the risk of memory consistency errors.
Java volatile variable that is an object reference may be null.

What is autoboxing and unboxing in Java

When Java automatically converts a primitive type like int into corresponding wrapper class object e.g. Integer than its called autoboxing  because primitive is boxed into wrapper class while in opposite case is called unboxing, where an Integer object is converted into primitive int.

What is Enum in Java

Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc.

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

Enum is a keyword in java and on more detail term Java Enum is type like class and interface and can be used to define a set of Enum constants.
Enum has its own name-space.

public enum Currency {
private int value;

private Currency(int value) {
this.value = value;
Constructor of enum in java must be private .
Enum in java can be used as an argument on switch statement

Currency usCoin = Currency.DIME;
switch (usCoin) {
case PENNY:
System.out.println(“Penny coin”);
case NICKLE:
System.out.println(“Nickle coin”);
case DIME:
System.out.println(“Dime coin”);
System.out.println(“Quarter coin”);

Since constants defined inside Enum in Java are final you can safely compare them using “==” equality operator as shown in following example of  Java Enum:
Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
System.out.println(“enum in java can be compared using ==”);

Comparator interface which is used to implement custom sorting order.

compareTo() method is defined in interface java.lang.Comparable and it is used to implement natural sorting on java classes..

You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
Enum in Java can implement the interface and override any method like normal class It’s also
Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum
for(Currency coin: Currency.values())
System.out.println(“coin: ” + coin);

You may have noticed that the new keyword isn’t used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it’s possible to assign a literal to a variable of a primitive type:
boolean result = true;
char capitalC = ‘C’;
byte b = 100;
short s = 10000;
int i = 100000;

Read only List, Set and Map Example – Java
Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List.
contents = Collections.unmodifiableList(contents);
readOnlySet = Collections.unmodifiableSet(readOnlySet);
Map readOnlyMap = Collections.unmodifiableMap(countries);

Generics :
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at runtime which was quite frequent error

Wrting a custome defined exception in Java
public class MyException extends Exception
public MyException(String message)

Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization.

1) Explain about your project?
2) How many Modules are there in your project?
3) What’s your Role and Responsibilities?
4) How big is your Team Size?
5) Tell me Some Exceptions you faced in your project?
6) Which type of Complexity code you written in your project
7) Which Version Controller you used?
8) Which type of validations you done in your Project?

Event and Listener in Servlet :
Changing the state of an object is known as an event.
We can perform some important tasks at the occurrence of these exceptions, such as counting total and current logged-in users, creating tables of the database at time of deploying the project, creating database connection object etc.

Event classes
The event classes are as follows:
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
Event interfaces
The event interfaces are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener

Servlet Filter
A filter is an object that is invoked at the preprocessing and post processing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.

Usage of Filter
recording all incoming requests
logs the IP addresses of the computers from which the requests originate
data compression
encryption and decryption
input validation etc.

Advantage of Filter
1. Filter is pluggable.
2. One filter don’t have dependency onto another resource.
3. Less Maintenance

jsp implicit objects:
1. request
2. response
3. page
4. session
5. pageContext
6. out
7. application
8. config
9. excepiton

JSP Directives :
page directive
include directive
taglib directive

Attributes of JSP page directive

Sleep() causes the currently executing thread to sleep (temporarily cease execution).
Yield() causes the currently executing thread object to temporarily pause and allow other threads to execute.

Expression Language (EL) in JSP
The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and other objects like request, session, application etc.
There are many implicit objects, operators and reserve words in EL.
It is the newly added feature in JSP technology version 2.0.
${ expression }

Implicit Objects

it maps the given attribute name with the value set in the page scope

it maps the given attribute name with the value set in the request scope

it maps the given attribute name with the value set in the session scope

it maps the given attribute name with the value set in the application scope

it maps the request parameter to the single value

it maps the request parameter to an array of values

it maps the request header name to the single value

it maps the request header name to an array of values

it maps the given cookie name to the cookie value

it maps the initialization parameter

it provides access to many objects request, session etc.

Value is ${ sessionScope.user }

Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence are as follows:
[] .
-(unary) not ! empty
* / div % mod
+ – (binary)
< <= > >= lt le gt ge
== != eq ne
&& and
|| or

Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:

What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.

What is blank final variable?
A final variable, not initialized at the time of declaration, is known as blank final variable.
Can we initialize blank final variable?
Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized only in the static block

Can you declare the main method as final?
Yes, such as, public static final void main(String[] args){}.

Is there any case when finally will not be executed?
finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort)

What is static synchronization?
If you make any static method as synchronized, the lock will be on the class not on object.

What is reflection?
Reflection is the process of examining or modifying the runtime behaviour of a class at runtime.It is used in:
IDE (Integrated Development Environment) e.g. Eclipse,MyEclipse,NetBeans.
Test Tools etc

Can you access the private method from outside the class?
Yes, by changing the runtime behaviour of a class if the class is not secured.

What is difference between HashMap and Hashtable?
1) HashMap is not synchronized.
1) Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values.
2) Hashtable cannot contain any null key nor value.
What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.

What is difference between HashMap and TreeMap?
1) HashMap is can contain one null key.
1) TreeMap connot contain any null key.
2) HashMap maintains no order.
2) TreeMap maintains ascending order.

List can contain duplicate elements whereas Set contains only unique elements.

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.

Collections class provides methods to make List,Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

Iterator vs Enumeration
1) Iterator can traverse legacy and non-legacy elements.
1) Enumeration can traverse only legacy elements.
2) Iterator is fail-fast.
2) Enumeration is not fail-fast.
3) Iterator is slower than Enumeration.
3) Enumeration is faster than Iterator.

Comparable vs Comparator
1) Comparable provides only one sort of sequence.
1) Comparator provides multiple sort of sequences.
2) It provides one method named compareTo().
2) It provides one method named compare().
3) It is found in java.lang package.
3) it is found in java.util package.
4) If we implement Comparable interface, actual class is modified.
4) Actual class is not modified.

What is a native method?
A native method is a method that is implemented in a language other than Java

System class is to provide access to system resources.

The peerless components are called light weight components.

A Locale object represents a specific geographical, political, or cultural region.

How will you load a specific locale?
By ResourceBundle.getBundle(?) method.

What is a JavaBean?
are reusable software components written in the Java programming language

JDBC Driver is a software component that enables java application to interact with the database.
4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)  use used

Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.
By using Callable statement interface, we can execute procedures and funtions

What is the life-cycle of a servlet?
1. Servlet is loaded
2. servlet is instantiated
3. servlet is initialized
4. service the request
5. servlet is destroyed

What are the life-cycle methods for a servlet?

1. public void init(ServletConfig config): It is invoked only once when first request comes for the servlet. It is used to initialize the servlet.
2. public void service(ServletRequest request,ServletResponse)throws ServletException,IOException: It is invoked at each request.The service() method is used to service the request.
3. public void destroy():It is invoked only once when servlet is unloaded.
web container is responsible to create the object of servlet.

PrintWriter is a character-stream class where as ServletOutputStream is a byte-stream class.The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information

The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol specific.HttpServlet provides additional functionalities such as state management etc.

forward() method vs sendRedirect() method
1) forward() sends the same request to another resource.
1) sendRedirect() method sends new request always because it uses the URL bar of the browser.
2) forward() method works at server side.
2) sendRedirect() method works at client side.
3) forward() method works within the server only.
3) sendRedirect() method works within and outside the server.
The container creates an object of ServletConfig for each servlet whereas an object of ServletContext is created for each web application.

What is Session Tracking?
Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user.Http protocol is a stateless protocol.Each time user requests to the server, server treats the request as the new request.So we need to maintain the state of an user to recognize to particular user.

How can we perform any action at the time of deploying the project?
With the help of ServletContextListener interface.

What are the life-cycle methods for a jsp?
1. public void jspInit(): It is invoked only once, same as init method of servlet.
2. public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOException: It is invoked at each request, same as service() method of servlet.
3. public void jspDestroy():It is invoked only once, same as destroy() method of servlet.

Can we use the exception implicit object in any jsp page ?
No. The exception implicit object can only be used in the error page which defines it with the isErrorPage attribute of page directive.

What is the difference between ServletContext and PageContext?-
ServletContext gives the information about the container whereas PageContext gives the information about the Request.

The Expression Language(EL) is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session etc.

Can an interface be implemented in the jsp file ?  No.

What are the subsets of SQL?
1. Data definition language (DDL) – create, alter, drop
2. Data manipulation language (DML)  – insert, update, delete, retrieve/select
3. Data control language (DCL) – grant , revoke
GRANT: to grant specific user to perform specific task.
REVOKE: to cancel previously denied or granted permissions.

What is the difference between clustered and non clustered index in SQL?
There are mainly two type of indexes in SQL, Clustered index and non clustered index. The differences between these two indexes is very important from SQL performance perspective.
1) One table can have only one clustered index but it can have many non clustered index. (approximately 250).
2) clustered index determines how data is stored physically in table. Actually clustered index stores data in cluster, related data is stored together so it makes simple to retrieve data.
3) reading from a clustered index is much faster than reading from non clustered index from the same table.
4) clustered index sort and store data rows in the table or view based on their key value, while non cluster have a structure separate from the data row.

Which types of join is used in SQL widely?
The knowledge of JOIN is very necessary for an interviewee. Mostly used join is INNER JOIN and (left/right) OUTER JOIN.

What are set operators in SQL?
Union, intersect or minus operators are called set operators.
DELETE is a DML command.
TRUNCATE is a DDL command.
We can use WHERE clause in DELETE command.
We cannot use WHERE clause with TRUNCATE
DELETE statement is used to delete a row from a table
TRUNCATE statement is used to remove all the rows from a table.
DELETE is slower than TRUNCATE statement.
TRUNCATE statement is faster than DELETE statement.
You can rollback data after using DELETE statement.
It is not possible to rollback after using TRUNCATE statement.

ACID is an acronym for Atomicity, Consistency, Isolation, Durability.
Atomicity: it requires that each transaction is all or nothing. It means if one part of the transaction fails, the entire transaction fails and the database state is left unchanged.
Consistency: the consistency property ensure that the data must meet all validation rules. In simple words you can say that your transaction never leaves your database without completing its state.

The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. This does not guarantee correctness of the transaction in all ways the application programmer might have wanted (that is the responsibility of application-level code) but merely that any programming errors do not violate any defined rules.

Isolation: this property ensure that the concurrent property of execution should not be met. The main goal of providing isolation is concurrency control.

Durability: durability simply means that once a transaction has been committed, it will remain so, come what may even power loss, crashes or errors.

PL/SQL stands for procedural language extension to SQL
PL/SQL block contains 3 sections.
1. The Declaration Section (optional)
2. The Execution Section (mandatory)
3. The Exception handling Section (optional)

Function: The main purpose of a PL/SQL function is generally to compute and return a single value. A function has a return type in its specification and must return a value specified in that type.
Procedure: A procedure does not have a return type and should not return any value but it can have a return statement that simply stops its execution and returns to the caller. A procedure is used to return multiple values otherwise it is generally similar to a function.

Exception is an error handling part of PL/SQL. There are two type of exceptions: pre_defined exception and user_defined exception.

What are PL/SQL exceptions? Tell me any three.
1. Too_many_rows
2. No_Data_Found
3. Value_error
4. Zero_error etc.

What is the maximum number of triggers, you can apply on a single table?
12 triggers.

There are 12 types of triggers in PL/SQL that contains the combination of BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL keywords.

How to execute a stored procedure : EXECUTE or [EXEC] procedure_name;

What are the advantages of stored procedure?
Modularity, extensibility, reusability, Maintainability and one time compilation.

A cursor is a temporary work area created in a system memory when an SQL statement is executed.
There are two types of cursors in PL/SQL.
1. Implicit cursor, and
2. explicit cursor

Singleton Design Pattern: Ensure that only one instance of a class is created; Provide a global point of access to the object.

The join method allows one thread to wait for the completion of another.

Q:12 What is the use of volatile in Java?
Threads are allowed to hold the values of variables in local memory (e.g. in a machine register).
If a variable is marked as volatile, every time when the variable is used, it must be read from the main memory, similarly every time the variable is written, the value must be stored in main memory.

Q: 20 What is Covariant Return Type?
The Covariant return type were introduced in java-5. Before Java 5, it was not possible to override method whose return type is different from the super class method. But with java 5 you can override method by changing the return type to subclass type and this rule is applicable for the methods whose return types are non-primitive.

Static Nested Classes
Non-static Nested Classes (Inner Classes)
Local Classes
Anonymous Classes

Static Nested Classes :

Nested classes in Java are classes that are defined inside another class.
two classes are to be used together
– In order to create an instance of Nested you must reference it by prefixing it with the Outer class name
Outer.Inner inner = new Outer.inner();
Inner classes are associated with an instance of the enclosing class. Thus, you must first create an instance of the enclosing class to create an instance of an inner class
Outer outer = new Outer();
Outer.Inner inner = Inner();
Non-static nested classes have access to the fields of the enclosing class, even if they are declared private
If an inner class declares fields or methods with the same names as field or methods in its enclosing class, the inner fields or methods are said to shadow over the outer fields or methods.
public class Outer {
private String text = “I am Outer private!”;
public class Inner {
private String text = “I am Inner private”;
public void printText() {
Local Classes
Local classes are like inner (non-static nested) classes that are defined inside a method or scope block ({ … })
Local classes can also be declared inside static methods.
In that case the local class only has access to the static parts of the enclosing class
Anonymous classes are classed without a class name
public class SuperClass {

public void doIt() {
System.out.println(“SuperClass doIt()”);

SuperClass instance = new SuperClass() {

public void doIt() {
System.out.println(“Anonymous class doIt()”);


1 What are the different ways of using thread?

The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, ’cause when you are going for multiple inheritance..the only interface can help.

You can look for words “either by implementing Runnable interface or by extending Thread class”.

2) What is the parent class of all exceptions
Ans: Throwable

3)How do you sort a collection
Ans) using sort method in Collections class

4)What is the difference between function and procedure in database programming
Ans: a function returns a value where as procedure doesn’t

5)What are the Core interfaces are of Hibernate framework ?

Ans) look for any of the following words
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces

6)What is HibernateTemplate?
Ans: HibernateTemplate is a spring helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

7)How do you configure hibernate SessionFactory using spring framework
Ans) using LocalSessionFactoryBean class providing by spring framework (look for LocalSessionFactoryBean)


1What is serializable, how what is externalizable?

2. we have a list of 1000 employee, I have a method List getEmp(Listofthousandemp String prop){}
what will be the implementation of the method above to find the the employees belong to same depart, of same lastname etc.
the prop is Dept. last. etc. user defined exception handled in java.can we have throw in catch block.
4.if I have Two classes Class A and class B , class A is dependent on Class B and Class B is dependent on A, if I configure these classes in spring configuration’s beans, will it give any error ?
5.what is compostion and how can we achieve it.which one is better to use inheritance or composition.
6. I class A there is a public static method void m(){}, in subclass we define a method private void m(){}, will it give any error ?
7.what is generics?
8.differnce between hashtable and hashMap and how hashtable internally implemented ?
9.what is factorybean ? not bean factory.10. what is aspect ?
11. in hibernate how you call the procedure ?

Core Java Questions
1. Difference between Abstraction & Encapsulation?
2. write Syntax of class which cannot be instantiate & Overridden?
3. We have arrayList of Person class which have name & Age? Write code
to sort person arrayList based on Person Age? Basically It is indirect
question for Comparator IF And Comparable IF.
4. How you achieve connection pooling in a. JDBC b. Weblogic c. Tomcat
5. What technology you used in current project & what purpose.(
Technology used in UI, Business Layer,  Persitents Layer etc)
6. Different Type of Design Patterns used in your project?
7.. What is DAO? And Write the code for it?
8. Write code for Singleton Pattern?
9. What is Serialization in Java?

1. Advantage of Hibernate Over JDBC
2. How to configure Hibernate in Spring?
3. Connection port & Context setting in Tomcat?
4. IOC & DI in Spring
5. Different type of Application Context in Spring.
6. Difference between BeanFactory & ApplicationContext
7. How to define a bean is sigleton/prototype,session,request or
global session in Spring?
8. How to configure a singleton bean & factory method in spring?
9.Describe  Different type of Interfaces provided by
etc )
10. Describe caching in Hibernate(First Level Cache & Second Level
Cache) & which is fast & efficient.
11. Did you used any cache Provider in Hibernate for
caching?(EHCache,OSCache,SwameCache,TreeCache etc)
12. Different Types of Bean wiring in Spring?
13. How to configure Struts in Spring?(ContextLoader Plug-In and Listeners)

Struts :
1. What is ActionSevlet in Struts & flow of it?
2. Can we extends Actionservlet? If Yes Then How?
3. Different type of Action Form in Struts.
4. Different type of Action in Struts
5. How to validate form data in Struts(Validator Framwork)
6. Purpose of DynaActionForm & ValidatorActionForm in Struts
7. How to handle exception in Struts(Global Exception Handling,
Exception mapping in Struts)
8. How to capture error in Struts forms(jsp pages)…<html:errors>
9. Error classes in Struts (ActionError & ActionMessages)

1) what are the methods of objects class.
2) Why wait,notify,notify all are in object class instead of thread class.
3) Suppose we have two methods public void a(String str){} and public void a(Object obj), if I Instantiate the class and call instance.a(null) which method will call.
4)IN JDBC  I open the connection and execute the query to get resultSet and if I
close the connection and than read the resultset will it throw any exception or not.

1)      How to Integrate Spring with Hibernate.

2)      What is difference between update() and merge() method

3)      What are the cache techniques in Hibernate.

4)      What is the difference between HQL and Criteria.

5)      What is HibernateTemplate?

6)      How to configure applicatincontext.xml file in your application

7)      How to write a HQL Query to fetch the data from multiple
tables like one to many relationship.

8)      What is lazy loading in hibernate
Core Java

1)      We have arrayList of Person class which have name & Age? Write
code to sort person arrayList based on Person Age? Basically It is
indirect question for Comparator IF And Comparable IF.

2)       What is Serialization in Java?

3)      In HashMap can we add duplicate values

4)      How to write a code for not allowing duplicate values in HashMap.

Thanks & Regards,

Spring Complete Notes :

1. Spring Modules

The Spring framework is a layered architecture consisting of seven well-defined modules. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in following figure.

Each of the modules or components that consist of the Spring framework can stand on its own or be implemented jointly with one or more of the other modules or components. The description of each component is as follows:
1. The core container:
The core container provides the fundamental functionality of the Spring framework. In this module primary component is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.
2. Spring context module :
The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as e-mail, JNDI, EJB, internalization, validation, scheduling and applications lifecycle events. Also included is support for the integration with templating frameworks such as velocity.

3. Spring AOP module:
The Spring AOP module allows a software component to be decorated with additional behavior, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

4. Spring DAO module:
The Spring DAO module provides a JDBC-abstraction layer that reduces the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects).

5. Spring ORM module:
Spring provides integration with OR mapping tools like Hibernate, JDO and iBATIS. Spring transaction management supports each of these ORM frameworks as well as JDBC.
6. Spring Web module:
The Web context module provides basic web-oriented integration features builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
7. Spring MVC framework module:
Spring provides a pluggable MVC architecture. The users have a choice to use the web framework or continue to use their existing web framework. Spring separates the roles of the controller; the model object, the dispatcher and the handler object which makes it easier to customize them. Spring web framework is view agnostic and does not push the user to use only JSPs for the view. The user has the flexibility to use JSPs, XSLT, velocity templates etc to provide the view.
2.Basic Bean Writing:
Ø       Spring based applications objects will live within the spring container.
Ø       The container will create the objects, wire them together, configure them, and manage their complete lifecycle from cradle to grave(means new to finalize())
Ø       Container is the place the objects are hanging out.
Ø       Spring’s container uses dependency injection to manage the components that make up an application. This includes creating associations between collaborating components.
Ø       These Spring Objects are cleaner and easy to understand, support reuse, and are easy to unit-test.
Ø       Spring comes with Several Container implementations (means is not having only one container, it is more than one). That can be categorized into two distinct types.
a.     Bean factories are the simplest container, providing basic support for Dependency Injection.
b.     Application Contexts build on notion of a bean factory by providing application framework services, such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
2.1 BeanFactory Type Containers
Ø       Bean factory is an implementation of the Factory Design Pattern. It is a class whose responsibility is to create and dispense beans of many types.
Ø       Bean factory takes part in the lifecycle of a bean, making calls to custom initialization and destruction methods, if those methods are defined.
Ø       BeanFactory implementation containers must implement the interface org.springframework.beans.factory.BeanFactory
Ø       There are several implementations of BeanFactory in spring. But the one most commonly used is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file.
Ø       To create XmlBeanFactory, we must pass an instance of to the Constructor.
Resource resource=new FileSystemResource (“c:/mybeans.xml”);
XmlBeanFactory xbf=new XmlBeanFactory (resource);
Ø       Beans are “lazily” loaded into bean factories, meaning that beans are instantiated when they are required.(useful in mobile applications)
Ø       To retrive a bean from a BeanFactory, simply call the getBean () method, passing the ID of the bean you want to retrive.
MyBean myBean =(MyBean) xbf.getBean(“myBean”);
Ø       There are total Eight resources available in the spring which implements interface. In this six are in*  package and other two are in org.springframework.web.portlet.context.PortletContextResource ,
Ø       Six resources are defined below as;;;;;;
2.2 Application Context Type Containers
Ø       This is spring’s more advanced container, which offers more services such as
i.            Resolving and loading text messages from properties file.
ii.            Supports for internationalization (i18n) of above messages.
iii.            It provides generic way to load file resources, such as images.
iv.            It can able to publish events to beans that are registered as listeners.
Ø       Among the many implementations of ApplicationContext are three that are commonly used:
§         ClassPathXmlApplicationContext- Loads a Context definition from an xml file located in the classpath, treating context definition files as classpath resources.
§         FileSystemXmlApplicationContext-Loads a context definition from an XML files in the file system.
§         XmlWebApplicationContext-Loads context definitions from an XML file contained within a web application.
Ø       Major difference between ApplicationContext and BeanFactory is how singleton beans are loaded. A BeanFactory lazily loads all beans, deferring (postpone, suspend) bean creation until the getBean () method is called.
ApplicationContext is a bit smarter and preloads all singleton beans upon context startup.
Ø       ApplicationContext interface extends BeanFactory interface

2.3 Bean’s Life Cycle
Ø       BeanFactory containers beans life cycle methods
1.      Instantiate
2.      Populates properties
3.      Set beanName
4.      Set BeanFactory
5.      PostProcess
6.      Initialize beans
7.      Postprocess
8.      Bean ready to use
9.      Destroy bean
Ø       ApplicationContext container beans life cycle methods
1.      Instantiate
2.      Populates properties
3.      Set beanName
4.      Set BeanFactory
5.      Set ApplicationContext
6.      PostProcess
7.      Initialize beans
8.      Postprocess
9.      Bean ready to use
10.  Destroy bean

2.4 Creating Beans
ü       Injecting through the constructor
i)   <bean id=”one” class=””>
<constructor-arg value=”SomeText….”/>

ii)   <bean id=”one” class=””>
<bean class=”com.Test”/>

ü       Injecting through the property
i) <bean id=”one” class=””>
<property name=”name” value=”injecting through Property”/>

ii) <bean id=”one” class=””>
<property name=”test” ref=”test” />
ü        Wiring Collections
i)    <bean id=”one” class=””>
<property name=”colleges”>
ii)    <bean id=”one” class=””>
<property name=”colleges”>
iii)    <bean id=”one” class=””>
<property name=”colleges”>
<entry key=”” value=””/>
<entry key-ref=”” value-ref=””/>
iv)  <bean id=”one” class=””>
<property name=”colleges”>
<prop key=”one”>One</prop>
<prop key=”one” value=”dd”/> is wrong
v) <bean id=”one” class=””>
<property name=”colleges”><null/></property>
2.5 Auto Wiring
v      Spring’s another feature which enable automatically figure out how to wire beans together by setting the autowire property on each bean that we want.
v      Spring supports four types of autowiring
o        ByName
<bean id=”one” class=”” autowire=”byName”>
o        ByType
<bean id=”one” class=”” autowire=”byType”>
o        Constructor
<bean id=”one” class=”” autowire=”constructor”>
o        Autodetect
<bean id=”one” class=”” autowire=”autodetect”>
v      If bean has been configured to autowire by autodetect, spring will attempt to autowire by constructor first, if no such constructor-bean found it will attempt to autowire by type.
v      Instead of writing autowire on each bean we can set default-autowire=”” on beans element as explicit wiring
<beans default-autowire=”autodetect|constructor|byType|byName”>
v      Autowire dominates the default-autowire wiring
v      Drawbacks of auto-wiring (work: list out based on above criteria)

2.6 Controlling Bean Creation
Ø       Controlling how many instances of a specific bean are created, whether it is one instance for the entire application(singleton), one instance per user request(request), or a brand-new instance each time the bean is used(prototype).
Ø       Create beans from static factory methods instead of public constructors.
Ø       Initialize bean after it is created and clean up just before it is destroyed.
Ø       Spring is five different types of scopes
o        singleton: single instance per container
o        prototype: new instance every time
o        request: valid in Spring MVC
o        session: valid in Spring MVC
o        global-session :valid in a portlet context
Ø       Initialization on demand holder (design pattern): it is a lazy loaded singleton.the idiom can be implemented in both single-threaded/serial and concurrent environments, but care must be taken to correctly implement this.
public class Stage {
private Stage() {
private static class StageSingletonHolder {
static Stage INSTANCE = new Stage();
public static Stage getInstance() {
return StageSingletonHolder.INSTANCE;

Ø       Calling static methods using factory method
<bean id=”stage” class=”com.Stage” factory-method=”getInstance”>
2.7 Initializing and destroying beans
This can be possible in three ways
1) By writing our own custom initializing and destroy methods that we need to mention below as follows.
<bean id=”test” class=”com.Test”
2) By declaring  globally for all beans common init and destroy methods
<beans default-init-method=”myInit” default-destroy-method=”myDestroy”>
3)By implementing the interfaces
spring container automatically identifies and calls afterPropertiesSet() and  destroy() methods.

2.8 Working with session and request scopes
a)If you are accessing scoped beans within Spring Web MVC, i.e. within a request that is processed by the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.
b) When using a Servlet 2.4+ web container, with requests processed outside of Spring’s DispatcherServlet (e.g. when using JSF or Struts), you need to add the following javax.servlet.ServletRequestListener to the declarations in your web application’s ‘web.xml’ file.

c) If you are using an older web container (Servlet 2.3), you will need to use the provided javax.servlet.Filter implementation. Find below a snippet of XML configuration that has to be included in the ‘web.xml’ file of your web application if you want to have access to web-scoped beans in requests outside of Spring’s DispatcherServlet on a Servlet 2.3 container. (The filter mapping depends on the surrounding web application configuration and so you will have to change it as appropriate.)


d) we can use like this also
Here we need to tell the location of the Spring Configuration files also. By default it will look for file at /WEB-INF/applicationContext.xml .  but we can change this by mentioning like below.
c)  Some web container do not initialize servlet listeners before servlets . this case we need to use ContextLoaderServlet.

3.Advance Bean Wiring

3.1 Declaring Parent and Child beans

Inorder to reduce the redundancy in the spring configuration files <bean> element provides two special attributes
1. parent : it is similar to extends in java Class
2. abstract : this never instantiated by the Spring
3.1.1 Abstracting base bean type
<bean id=”one” class=”com.One” abstract=”true”/>
<bean id=”two” parent=”one”/>
<bean id=”three” parent=”one”/>
3.1.2 Abstracting common properties
<bean id=”myproperty”  abstract=”true”>
<property name=”song” value=”sssssssss”/>
<bean id=”two” parent=”myproperty”/>
<bean id=”three” parent=” myproperty”/>

3.2 Applyting method injection
Setter injection allows to inject values into a bean’s properties.method injection allows to inject entire method definitions into a bean.
Spring supports two forms of method injection
1. Method replacement
2. Getter Injection

3.2.1 Basic method replacement
3.2.2 Using getter injection
3.3 Injecting non-spring beans
3.4 Registering custom property editors
3.5 Working with Spring Special beans
3.5.1 Postprocessing the Beans
3.5.2 PostProcessing the BeanFactory
3.5.3 Externalize configuration properties
3.5.4 Resolving text messages
3.5.5 Decoupling with application events
3.5.6 Making Bean Aware
3.6 Scripting Beans With Groovy

4. Advising Beans
In software development,functions that span multiple points of an application are called cross-cutting concerns. Typically these cross-cutting concerns are conceptually separated from the application’s business logic. Separating these cross-cutting concerns from business logic is where AOP goes to work.
ü       DI docuples application objects from each other.
ü       AOP docuples cross-cutting concerns from the objects that they affect.
Any Object-Oriented technique is mainly focuses on re-using functionality that can be achieved by following ways
1)     Inheritance
2)     Delegation
3)     Aspects
4.1 AOP terminology:
a)     cross-cutting concerns: any functionality that affects multiple points of an application.
b)     Adive
c)     JointPoint
d)     PointCut
e)     Aspect
f)      Introduction
g)     Target
h)     Proxy
i)       Weaving

Spring’s support for AOP comes in four flavors:
1)     Classic Spring proxy-based AOP
2)     @AspectJ annotation-driven aspects
3)     Pure-POJO aspects
4)     Injected AspectJ aspects
ü       Spring advice are written in Standard Java Class and pointcuts are written in xml configuration files.
ü       Spring advices objects at runtime: aspects are woven into spring-managed beans at runtime by wrapping them with a proxy class.
ü       Spring generates proxy classes in two ways.
o        using java.lang.reflect.Proxy
o        using CGLIB(Code Generation Library) to generate subclass to the target class at runtime.
ü       Methods marked as final cannot be advised because CGLIB can’t generate subclass to it.
ü       AOP frameworks supports three types of jointpoints
o        Field jointpoints
o        Constructor jointpoints
o        Method jointpoints
ü       Spring supports only method jointpoints, we cannot apply advice when bean is instantiated because sping doesn’t supports constructor jointpoints. We can’t apply advice when field is updated in a object because Spring doesn’t support field jointpoints.
ü       In spring five types of Advice implementation and two types of Pointcut implementations available.
ü       AOP Alliance is an open source project whose goal is to facilitate and standardize AOP.
ü       Except MethodInterceptor  all interfaces are comes with Springframework.

4.2 Defining Advice

Advice Type

ü       Before advice need to implement MethodBeforeAdice interface and implement  before() method
public void before(Method method,Object[] args,Object target) throws Throwable;
method takes three parametes
a)      java.lang.reflect.Method : this represents method to which the advice is being applied.
b)      Object[]: arguments to the method
c)       Object : object on which the method was called.
ü       After-returning advice need to implement AfterReturningAdvice interface and implement afterReturning() method
public void afterReturning(Object returnValue,Method method,Object[],Object obj) throws Throwable;

ü       After-throwing advice need to implement ThrowsAdvice interface
public void afterThrowing([method],[args],[target],throwable);
all parameters are optional except throwable one
(ThrowsAdvice is marker interface but it checks for afterThrowing signature method)

ü       Around Advice need to implement MethodInterceptor interface and works before and after returning and afterthrowing cases.
public Object invoke(MethodInvocation invocation) throws Throwable;
ü       sample implementation how it satisfies above three Conditions
public Object invoke(MethodInvocation invocation) throws Throwable{
————–executed MethodBeforeAdvice—————
————–executed AfterReturningAdvice—————
}catch(Exception e){
————–executed   throwsAdvice—————
ü       Failure to call proceed() will result in the advice being applied but the target method never being executed.

4.3 Defining Pointcuts
ü       Spring comes with several different types of Pointcuts to choose from,but two are the most useful pointcuts.

Pointcut Type
Java Class

ü       Spring comes with two classes that implement RegularExpressionPointcuts
1)– useful when application will be running in a pre-java1.4 environment.(it Required Jakarta ORO).
2) choice if we run jdk1.4 or higher.

ü       AspectJExpressionPointcuts are defined by using the  below class

4.4 Defining Advisors
ü       After defining Advice and pointcuts  we need to associate this pointcut with advice. Spring will do this  with Three types of Advisors
3)          org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor
ü      All above Advisors extends   one  abstract class
4.5 Example to use Aspects
Example  to Create Advice
<bean id=”myAdvice” class=”com.MyAdvice”></bean>
Example to Create RegularExpress Pointcut
<bean id=”regexPointcut” class=””>       <property name=”pattern” value=”.*perform” ”/>
Example to Create AspectJ Pointcut
<bean id=”aspectJPointcut” class=” org.springframework.aop.aspectj.AspectJExpressionPointcut”>
<property name=”expression” value=”execution(*  *.perform”/>
Example to Use DefaultPointcutAdvisor
<bean id=”defaultAdvisor” class=””>
<property name=”advice” ref=” myAdvice”/>
<property name=”pointcut” ref=” regexPointcut”/>
<property name=”pointcut” ref=” aspectJPointcut”/>  <!–   any one à
Example to Use RegexpMethodPointcutAdvisor
<bean id=”regexAdvisor” class=””>
<property name=”advice” ref=” myAdvice”/>
<property name=”pattern”  value=”.*perform”/>
Example to Use AspectJExpressionPointcutAdvisor
<bean id=”aAdvisor” class=” org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor”>
<property name=”advice” ref=” myAdvice”/>
<property name=”expression”  value=”execution(* .*perform (..))”/>
4.6 Using Proxy Factory Beans
In Spring AOP, advisors completely define as aspect by asscociating advice with a pointcut. But Aspects in Spring are proxied. Whether you use Regular expression pointcuts or AspectJ pointcuts,you still need to proxy your target beans for the advisors to take effect. For that we need to declare one or more ProxyFactoryBeans.
<bean id=”duke” class=”org.springframework.aop.framework.ProxyFactoryBean”>
<property name=”target” ref=”dukeTarget”/>
<property name=”interceptorNames” value=”someAdvisor”/>
<property name=”proxyInterfaces” value=”com.SomeInterFace”/>
But it requires to write more xml in the configuration file hence I’m not going into deep into this.

4.7 AutoProxying
There are two ways to autoproxy beans
Basic autoproxying of beans based on advisor beans declared in the Spring context-The Advisor’s pointcut expression is used to determine which beans and which methods will be proxied.
Autoproxying based on @AspectJ annotation-driven aspects-The pointcuts specified on the advice contained within the aspect will be used to choose which beans and methods will be proxied.
àFirst Method Implementation (Creating autoproxies for Spring Aspects): After creating Advisor as shown in the Example to Use AspectJExpressionPointcutAdvisor part . we need to add some bean configuration into the xml file.
<bean class=”org.springframework.aop,framework,autoproxy.DefaultAdvisorAutoProxyCreator”/>

NOTE: DefaultAdvisorAutoProxyCreator is the implementation of BeanPostProcessor interface ,which recognized by Spring Container and creates proxies runtime.
àSecond Method Implementation(Autoproxying @AspectJ aspects): using this we need to add some annotations to the class as shown below.
ü       Annotation Around advice implementation will have only one method watchPerformance() which takes ProceedingJointPoint as argument
public void watchPerformance(ProceedJointPoint jointpoint){
}catch(Exception e){

Add <aop:aspectj-autoproxy/> to the configuration file inorder to work below code.
public class Audience{
@Pointcut(“execution(* *.perform(..))”)
public void performance(){}

public void takeSeats(){
System.out.println(“do something ”);
public void appalaud(){
System.out.println(“do something ”);
public void demandRefund(){
System.out.println(“do something ”);

4.8 Declaring Pure-POJO aspects
Using This we need not required Source code on which we apply Aspects. Declaration of this kind of aspects as shown below.
<bean id=”audience” class=”com.Audience”/>
<aop:aspect ref=”audience”>
<aop:pointcut id=”performance” expression=”execution(* *.perform(..))”/>
<aop:before method=”takeSeats”  pointcut-ref=”performance”/>

4.9 Injecting AspectJ aspects
This is totally AspectJ Framework through which we can Advice Constructor and fields also ,this is not part of spring framework hence I’m not discussing here. J


Definition : Transaction is a series of sql statements that either succeeds or fails as a unit to prevent inconsistent data.
Transaction should pass ACID Test.
Atomic: It ensures that all the operations in the transaction happen or that none of them happen.
Consistent: Once the transaction ends (success or fail) the system is left in a state that is consistent.
Isolated: transaction should be isolated from each other,preventing concurrent reads and writes to the same data (involves locking rows and tables in database).
Durable: once the transaction completed the results should be permanent.

Callback Mechanism
Proxing Beans, XML-Declared, annotation-driven transactions.

Spring doesn’t directly manage transactions. Instead ,it comes with a selection of transaction managers that delegates responsibilities for transaction management to a platform-specific transaction implementation provided by either JTA or the persistent mechanism.

1. JDBC transactions
<bean id=”transactionManager”         class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
<property name=”dataSource” ref=”dataSource”/>
2. Hibernate transactions
<bean id=”transactionManager”         class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property name=”sessionFactory” ref=” sessionFactory”/>

6.3 Programmatic Transactions in Spring
Step 1: Inject transactionTemplate into the Service/Dao Class.
<bean id=”testService” class=”com.trx.TestServiceImpl”>
<property name=”transactionTemplate”>
<bean class=””>
<property name=”transactionManager” ref=”transactionManager”/>
Step2 :  write code as shown below in the java class
public void addBook(Book book) {
transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus ts) {
try {

} catch (Exception e) {
return null;

6.4             Declarative Transactions
Spring offers declarative transactions to POJOs. Spring declarative transaction management is implemented through Spring’s AOP framework.
Spring Three ways Supports Declarative Transactions :
1)     By Proxying beans using Spring AOP.
2)     XML-Declared transactions.
3)     Annotation-driven transactions.

Transaction Attributes :  Transaction attribute is a description of how transaction policies should be applied to a method.
I.      propagation
II.      isolation
III.      rollback rules
IV.      timeout
V.      read-only?
Propagation Behaviour : Propagation behaviour defines the boundaries of transaction with respect to the client and to the method being called.
Note : org.springframework.transaction.TransactionDefinition is an interface which defines the below constants.

Propagation Behavior
Method must run with in transaction . otherwise an exception will be thrown.
Method should run within anested transaction if an existing transaction is in progress.
Method should not run within transaction. otherwise an exception will be thrown.
Method should not run within a transaction. If there transaction exists that suspended.
Method must run within transaction . if no transaction exists it will create.
Method must run within its own transaction. A new transaction is started and if existing one is in progress.
Method doesnot requires transactional context, but may run within a transaction if one is already in progress.

Isolation Levels : it defines how much a transaction may be impacted by the activities of other concurrent transactions. In a typical application, multiple transactions run concurrently,often working with the same data to get their job done. It leads to the following problems.
ü       Dirty read:it occurs one transaction reads the data that has been written (but not committed ) by  the another transaction. If the changes are rolled back by the second transaction , the data obtained by the first transaction will be invalid.
ü       Nonrepeatable read: if the same transaction performs read query two or more times and each time the data is different , this is because another concurrent transaction updating the data between the queries.
ü       Phantom reads: similar to the nonrepeatable read. (??)

In the ideal case ,transactions would be completely isolated from each other. Perfect isolation can affect  performance because it often involves locking rows in the data store.

Isolation Level





Read-only :
Transaction timeout:
Rollback rules:


Spring Web MVC framework is designed around a DispatchServlet that dispatches requests to handlers,with configurable handler mappings,view resolution,locale and theme resolution as well as support for upload files.
Note: it is not possible to add advice to final methods using Spring MVC. For example we can’t add advice to AbstractController.handleRequest() method.

ü       Each DispatchServlet has its own WebApplicationContext,which inherits all the beans already defined in the root WebApplicationContext.
ü       The framework will, on initialization of a DispatcherServlet, look for a file named  [servlet-name]-servlet.xml in the WEB-INF directory of your web application and  create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).
ü       Special beans in the WebApplicationContext
a.      Controllers
b.      HandlerMappings
c.      View Resolvers
d.      Locale Resolver
e.      Theme Resolver
f.       Multipart file Resolver
g.      Handler Exception Resolver

Complete process for a request which goes is handled by the DispatchServlet.
Step 1: The WebApplicationContext is searched and bound to under key
Step 2: locale resolver is bound to the request to let elements in the process resolve the locale to use when processing the request.
Step 3: Theme Resolver is bound to the request to let elements such as views determine which theme to use.
Step 4: if a multipart resolver is specified ,the request is inspected for multiparts,if multiparts are found,the request is wrapped to MultipartHttpServletRequest.
Step 5: An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) will be executed in order to prepare a model (for rendering).
Step 6: If a model is returned, the view is rendered. If no model is returned (which could be due to a pre- or postprocessor intercepting the request, for example, for security reasons), no view is rendered, since the request could already have been fulfilled.

Note 1: Exceptions that are thrown during processing of the request get picked up by any of the handler exception resolvers that are declared in the WebApplicationContext.
Note 2: Spring DispatchServlet also has support for returning the last-modification-date. The DispatcherServlet will first lookup an appropriate handler mapping and test if the handler that is found implements the interface LastModified interface. If so, the value of the long getLastModified(request) method of the LastModified interface is returned to the client.

DispatchServlet initialization parameters

Class that implements WebApplicationContext, which will be used to instantiate the context used by this servlet. If this parameter isn’t specified, the
XmlWebApplicationContext will be used.
String which is passed to the context instance(specified by contextClass) to indicate where context(s) can be found. The string is potentially split up into multiple strings(using a comma as delimiter) to support multiple contexts( in case of multiple context locations,of beans that are defined twice,the latest takes precendence.
The namespace of the WebApplicationContext.Defaults to [servlet-name]-servlet.

Spring Controllers

1. Controller interface :Spring’s basis for the controller architecture is the org.springframework.web.servlet.mvc.Controller which is having one method.

public class SimpleOneController implements Controller{
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
return new ModelAndView(“index”);

2. AbstractController and WebContentGenerator:
All of Spring’s various Controllers inherit from AbstractController .
This class offering caching support.

public class SimpleTwoController extends AbstractController{
protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1)  throws Exception {
return new ModelAndView(“index”);

Features offered by the AbstractController

Indicates what methods this controller should accept.
indicates whether or not this controller requires a HTTP session to do its work
use this if you want handling by this controller to be synchronized on the user’s HTTP session.
when you want a controller to generate a caching directive in the HTTP response, specify a positive integer here. By default the value of this property is set to -1 so no caching directives will be included in the generated response.

tweaks your controllers to specify the HTTP 1.0 compatible “Expires” header in the generated response. By default the value of this property is true.

tweaks your controllers to specify the HTTP 1.1 compatible “Cache-Control”
header in the generated response. By default the value of this property is true.

3.  The ParameterizableViewController is basically the same as the example above, except for the fact that you can specify the view name that it will return in the web application context (and thus remove the need to hard-code the viewname in the Java class).

<bean name=”indexController”
p:viewName=”index”  />

4.The UrlFilenameViewController inspects the URL and retrieves the filename of the file request and uses that as a viewname. For example, the filename of request is index. (how use it?)

5. MultiActionController Spring offers a MultiActionController class that supports the aggregation of multiple request-handling methods into one controller, which then allows you to group related functionality together.

There are two usage-styles for the MultiActionController.
Ø       subclass the MultiActionController and specify the methods that will be resolved by the MethodNameResolver on your subclass
Ø       delegate object, on which methods resolved by the MethodNameResolver will be invoked.

Method signature which supports multiAction controller.

public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response);

1) if the method return type is Map it looks for a view which is same url name.
Any type of MethodNameResolver à /vtr.htm?method=testmap will looks for vtr.jsp
But the testmap will executed successfully.
public Map testmap(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
return new HashMap();

2) if the method name void response directly written to response Object.
public void testvoid(HttpServletRequest arg0, HttpServletResponse res,User user) throws Exception {
PrintWriter out= res.getWriter();
out.write(“<ONE>This is multiAction void return type</ONE>”);

3) if the method name String then ?????
public String teststr(HttpServletRequest arg0, HttpServletResponse res) throws Exception {
return “index”;

4) normal signature similar to other controllers third parameter is optional to any of the above method also
public ModelAndView testmap(HttpServletRequest arg0, HttpServletResponse arg1, [command| ExceptionClass] ) throws Exception {
return new ModelAndView(“index”);

MethodNameResolver is responsible for resolving method names based on the specifics of the incoming HttpServletRequest.

interprets the final filename from the request path and uses that as the method name/ For example, ‘; will result in the method testing(HttpServletRequest, HttpServletResponse) being invoked.
interprets a request parameter as the name of the method that is to be invoked.For example, ‘; will result in the method testIt(HttpServletRequest, HttpServletResponse) being invoked. The ‘paramName’ property specifies the name of the request parameter that is to be used. Example to use paramName property shown below example

uses a user-defined Properties object with request URLs mapped to
method names. For example, when the Properties contain ‘/index/welcome.html=doIt’ and a request to
/index/welcome.html comes in, the doIt(HttpServletRequest, HttpServletResponse) method will be

Ø       Example to use ParameterMethodNameResolver
<bean id=”paramMultiController”
<property name=”methodNameResolver”>
<bean class=”org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver”>
<property name=”paramName” value=”method”/>
<property name=”delegate”>
<bean class=”samples.SampleDelegate”/>

Ø       Example to use  PropertiesMethodNameResolver
<bean id=”multiController” class=”com.myapp.spring.controller.MyMultiController”>
<property name=”methodNameResolver”>
<bean class=”org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver”>
<property name=”mappings”>

Ø       Using MultiActionController as a Delegate Object method.
<bean id=”multiController” class=”org.springframework.web.servlet.mvc.multiaction.MultiActionController”>
<property name=”methodNameResolver”>
<bean class=”org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver”>
<property name=”paramName” value=”vtr”/>
<property name=”delegate”>
<bean class=”com.myapp.spring.controller.DelegateObject”/>

Ø       CommandControllers

Command Controller

a command controller you can use to create your own command controller, capable of binding request parameters to a data object you specify. This class does not offer form functionality; it does however offer validation features and lets you specify in the controller itself what to do with the command object that has been populated with request parameter values.
an abstract controller offering form submission support. Using this controller you can model forms and populate them using a command object you retrieve in the controller. After a user has filled the form, the AbstractFormController binds the fields, validates the command object, and hands the object back to the controller to take the appropriate action. Supported features are: invalid form submission (resubmission), validation, and normal form workflow. You implement methods to determine which views are used for form presentation and success. Use this controller if you need forms, but don’t want to specify what views you’re going to show the user in the application context
a form controller that provides even more support when creating a form with a corresponding command object. The SimpleFormController let’s you specify a command object, a
viewname for the form, a viewname for page you want to show the user when form submission has succeeded, and more.
as the class name suggests, this is an abstract class – your wizard
controller should extend it. This means you have to implement the validatePage(), processFinish() and processCancel() methods.
This class having two subclasses
1) AbstractCommandController
2) AbstractFormController

6. BaseCommandController Controller implementation which creates an object (the command object) on receipt of a request and attempts to populate this object with request parameters.This controller is the base for all controllers wishing to populate JavaBeans based on request parameters, validate the content of such JavaBeans using Validators and use custom editors (in the form of PropertyEditors) to transform objects into strings and vice versa.
Properties supported by the BaseCommandController
the name to use when binding the instantiated command class to the request
the class to use upon receiving a request and which to fill using the request parameters. What object is used and whether or not it should be created is defined by extending classes and their configuration properties and methods.
Array of Validator beans. The validator will be called at appropriate places in the workflow of subclasses (have a look at those for more info) to validate the command object.
Short-form property for setting only one Validator bean (usually passed in using a <ref bean=”beanId”/> property.
Indicates whether or not to validate the command object after the object has been populated with request parameters.

7. AbstractCommandController is required to set command class assetCommandClass() method or set commandClass property in xml file.
<bean class=”com.myapp.spring.controller.CommandTwoController”>
<property name=”commandClass” value=”com.User”/>
public class CommandTwoController extends AbstractCommandController{
protected ModelAndView handle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, BindException arg3) throws Exception {
return new ModelAndView(“index”,”name”,((User)arg2).getName());
8. AbstractFormController : Form controller that auto-populates a form bean from the request. This, either using a new bean instance per request, or using the same bean when the sessionForm property has been set to true.

This class is the base class for both framework subclasses such as SimpleFormController and AbstractWizardFormController and custom form controllers that you may provide yourself.
public class FormOneController extends AbstractFormController {
protected ModelAndView showForm(HttpServletRequest arg0, HttpServletResponse arg1, BindException arg2) throws Exception {
return new ModelAndView(“index”, “name”, “showForm”);
protected ModelAndView processFormSubmission(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, BindException arg3) throws Exception {
System.out.println( ” This is  “+  getCommandName());
return new ModelAndView(“index”, “name”, “processFormSubmission”+arg2 +”: ” +   ((User)arg2).getName());

Steps involved in the processing this request
1.       The controller receives a request for a new form (typically a GET).
2.       Call to formBackingObject() which by default, returns an instance of the commandClass that has been configured (see the properties the superclass exposes), but can also be overridden to e.g. retrieve an object from the database (that needs to be modified using the form).
3.       Call to initBinder() which allows you to register custom editors for certain fields (often properties of non-primitive or non-String types) of the command class. This will render appropriate Strings for those property values, e.g. locale-specific date strings.
4.       Only if bindOnNewForm is set to true, then ServletRequestDataBinder gets applied to populate the new form object with initial request parameters and the onBindOnNewForm(HttpServletRequest, Object, BindException) callback method is called. Note: any defined Validators are not applied at this point, to allow partial binding. However be aware that any Binder customizations applied via initBinder() (such as DataBinder.setRequiredFields(String[]) will still apply. As such, if using bindOnNewForm=true and initBinder() customizations are used to validate fields instead of using Validators, in the case that only some fields will be populated for the new form, there will potentially be some bind errors for missing fields in the errors object. Any view (JSP, etc.) that displays binder errors needs to be intelligent and for this case take into account whether it is displaying the initial form view or subsequent post results, skipping error display for the former.
5.       Call to showForm() to return a View that should be rendered (typically the view that renders the form). This method has to be implemented in subclasses.
6.       The showForm() implementation will call referenceData(), which you can implement to provide any relevant reference data you might need when editing a form (e.g. a List of Locale objects you’re going to let the user select one from).
7.       Model gets exposed and view gets rendered, to let the user fill in the form.
8.       The controller receives a form submission (typically a POST). To use a different way of detecting a form submission, override the isFormSubmission method.
9.       If sessionForm is not set, formBackingObject() is called to retrieve a form object. Otherwise, the controller tries to find the command object which is already bound in the session. If it cannot find the object, it does a call to handleInvalidSubmit which – by default – tries to create a new form object and resubmit the form.
10.   The ServletRequestDataBinder gets applied to populate the form object with current request parameters.
11.   Call to onBind(HttpServletRequest, Object, Errors) which allows you to do custom processing after binding but before validation (e.g. to manually bind request parameters to bean properties, to be seen by the Validator).
12.   If validateOnBinding is set, a registered Validator will be invoked. The Validator will check the form object properties, and register corresponding errors via the given Errors object.
13.   Call to onBindAndValidate() which allows you to do custom processing after binding and validation (e.g. to manually bind request parameters, and to validate them outside a Validator).
14.   Call processFormSubmission() to process the submission, with or without binding errors. This method has to be implemented in subclasses.
In session form mode, a submission without an existing form object in the session is considered invalid, like in case of a resubmit/reload by the browser. The handleInvalidSubmit method is invoked then, by default trying to resubmit. It can be overridden in subclasses to show corresponding messages or to redirect to a new form, in order to avoid duplicate submissions. The form object in the session can be considered a transaction token in that case.

Configuration Properties


Indicates whether to bind servlet request parameters when creating a new form. Otherwise, the parameters will only be bound on form submission attempts.
Indicates whether the form object should be kept in the session when a user asks for a new form. This allows you e.g. to retrieve an object from the database, let the user edit it, and then persist it again. Otherwise, a new command object will be created for each request (even when showing the form again after validation errors).

9. SimpleFormController It is similar to  AbstractFormController. But there are some main difference I found are described here
Ø       we no need to  implement showForm and processFormSubmission:
Ø       A form view and a success view can be configured declaratively.
Ø       It supports three difference onSubmit overloaded methods. The preference order they called shown below.
I.      protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception;
II.      protected ModelAndView onSubmit(Object command, BindException errors) throws Exception;
III.      protected ModelAndView onSubmit(Object command) throws Exception;

Steps Involved in the processing requests

I.      Call to processFormSubmission which inspects the Errors object to see if any errors have occurred during binding and validation.
II.      If errors occured, the controller will return the configured formView, showing the form again (possibly rendering according error messages).
III.      If isFormChangeRequest is overridden and returns true for the given request, the controller will return the formView too. In that case, the controller will also suppress validation. Before returning the formView, the controller will invoke onFormChange(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException), giving sub-classes a chance to make modification to the command object. This is intended for requests that change the structure of the form, which should not cause validation and show the form in any case.
IV.      If no errors occurred, the controller will call onSubmit using all parameters, which in case of the default implementation delegates to onSubmit with just the command object. The default implementation of the latter method will return the configured successView. Consider implementing doSubmitAction(java.lang.Object) doSubmitAction for simply performing a submit action and rendering the success view.
Properties that needs to be configured

Indicates what view to use when the user asks for a new form or when validation errors have occurred on form submission.
Indicates what view to use when successful form submissions have occurred. Such a success view could e.g. display a submission summary. More sophisticated actions can be implemented by overriding one of the onSubmit() methods.

10. AbstractWizardFormController – as the class name suggests, this is an abstract class – your wizard controller should extend it. This means you have to implement the validatePage(), processFinish() and processCancel() methods.
<bean class=”com.myapp.spring.controller.WizardController”>
<property name=”commandClass” value=”com.User”/>
<property name=”pages”>

11. ThrowawayController(interface) : it is specifically intended for controllers that are not aware of the Servlet API at all.
public class ThrowAwayController implements  ThrowawayController {
public ModelAndView execute() throws Exception {
return new ModelAndView(“index”);

Ø       When a request comes in, the DispatcherServlet will hand it over to the handler mapping to let it inspect the request and come up with an appropriate HandlerExecutionChain. Then the DispatcherServlet will execute the handler and interceptors in the chain (if any).
Ø       The concept of configurable handler mappings that can optionally contain interceptors (executed before or after the actual handler was executed, or both) is extremely powerful. A lot of supporting functionality can be built into custom HandlerMappings. Think of a custom handler mapping that chooses a handler not only based on the URL of the request coming in, but also on a specific state of the session associated with the request.
There are two Spring’s most commonly used handler mappings.They both extend the org.springframework.web.servlet.handler.AbstractHandlerMapping and share the following properties.

the list of interceptors to use.
the default handler to use, when this handler mapping does not result in a matching handler.
order( see example 5)
based on the value of the order property (see the org.springframework.core.Ordered interface), Spring will sort all handler mappings available in the context and apply the first matching handler.
if this property is set to true, Spring will use the full path within the current servlet context to find an appropriate handler. If this property is set to false (the default), the path within the current servlet mapping will be used. For example, if a servlet is mapped using /testing/* and the alwaysUseFullPath property is set to true, /testing/viewPage.html would be used, whereas if the property is set to false, /viewPage.html would be used.
the default value for this property is true, as of Spring 2.5. If you prefer to compare encoded paths, switch this flag to false. However, note that the HttpServletRequest always exposes the servlet path in decoded form. Be aware that the servlet path will not match when compared with encoded paths.
allows for lazy initialization of singleton handlers (prototype handlers are always lazily initialized). Default value is false

Handler Mappings

Handler Mapping
It maps Controller to URLs that are based on the Controller’s bean name
Maps Controllers to URLs using a property collection defined in the spring application context.
It maps Controller to URLs by using the controller’s class name as the basis for the URL.
Map controllers to URLs using source-level metadata placed in the controller code.The metadata is defined using Jakarta commons attributes

Examples to use Handler Mappings
1)                Using SimpleUrlHandlerMapping
<bean id=”simpleUrlMapping” class=”org.sf.web.servlet.handler.SimpleUrlHandlerMapping”>
<property name=”mappings”>
<prop key=”/home.htm”>homeController</prop>
<prop key=”/index.htm”>indexController</prop>

2)                Using BeanNameUrlHandlerMapping
<bean id=”urlMapping” class=”org.sf.web.servlet.handler. BeanNameUrlHandlerMapping”/>
<bean name=”/index.htm” class=”com.IndexController”/>
3)                Using ControllerClassNameHandlerMapping
<bean id=”urlMapping” class=””/>
<bean class=”com.IndexController”/>
4)                Using CommonsPathMapHandlerMapping
<bean id=”urlMapping” class=”org org.springframework.web.servlet.handler.metadata.CommonsPathMapHandlerMapping”/>
Public class HomePageController extends AbstractController{
//  implement handleRequestInternal method

5)                Working with multiple HandlerMapping
<bean id=”beanNameUrlMapping” class=”org.sf.web.servlet.handler. BeanNameUrlHandlerMapping”>
<property name=”order”><value>1</value></property>

<bean id=”simpleUrlMapping” class=”org.sf.web.servlet.handler.SimpleUrlHandlerMapping”>
<property name=”order”><value>0</value></property>
<property name=”mappings”>
<prop key=”/home.htm”>homeController</prop>
<prop key=”/index.htm”>indexController</prop>

We’ve all been there – you wake up early in the morning, feel sluggish, pound a cup of coffee, feel a bit better… but then before you know it your energy levels have dropped and you’re feeling fatigued. All that and it’s not even noon. 

If that sounds like a typical day for you, read on for some great ways to keep your energy level on the up and up. There’s no reason you should have to feel tired all the time. 

10 Ways to Stay Energetic All Day

1. Exercise. If you do only one thing to keep your energy levels up, it should be exercise. Take a mid-morning and mid-afternoon walk to energize your entire day. Vary your routine to keep your mind engaged.

2. Listen to music. If you’re feeling tired or thinking about skipping your workout, grab your iPod and listen to your favorite tunes to help you forget your sleepiness and get moving. Music is a powerful motivator.

3. Get enough sleep. This is obvious but not always easy. If insomnia is the reason you’re tired during the day, try reading a book before bed, drinking tea with Valerian root, and abstaining from caffeine after 4pm. If your insomnia lingers, see your physician.

4. Eat a healthy breakfast and lunch.
 Eating lean protein, fruits and vegetables in lieu of carbohydrates will help sustain your energy levels. Aim for only 3-4 servings of whole grain carbs a day – skip the white bread all together.

5. Wake up at the same time every day. Getting into a regular sleep-wake rhythm will do wonders for you as far as energy is concerned. Your body likes to be on a set schedule and will reward you for it.

6. Don’t stress out. Stress and anxiety are major energy suckers. Stay relaxed and focused by taking short “mental health” breaks throughout the day. Meditate and/or think of positive things and breathe deeply.

7. Afternoon caffeine boost. Most people drink caffeine in the morning but drinking a cup of tea or coffee in the afternoon can help your body and mind fight afternoon fatigue.

8. Get some fresh air. Nothing drains energy faster than sitting in a stuffy room with stale air. Get outside a few times a day – or at the very least, open a window and inhale the breeze.

9. Keep fresh flowers or a plant on your desk. Psychologists have noted that accenting a room with fresh flowers or a colorful plant (or two) can boost energy and mood levels. 

10. Don’t snooze. As hard as it may be, waking up when your alarm goes off the first time is essential to staying energized for the rest of the day. Hitting the snooze button over and over does nothing but make you feel groggy – a feeling that tends to linger.

5 Ways to stay energetic throughout the day

Don’t you notice that when you are happy and optimistic, you are likely to be energetic? Do you sometimes wonder how you can stay energetic throughout your day?

Studies show that the more fit one’s body is, the more one’s brain seems to benefit. Correct breathing, healthy eating and drinking habits, healthy body, and sports affect your success as the Roman proverb says, “A sound mind in a sound body.” Therefore, it is crucial that you take care of your body and understand the benefits of health.

Follow the below steps on how to stay energetic throughout the day:

1. Breathing

You might know that breathing is indispensable for everyone, but do you know that the majority of people do not breathe correctly? Start from today to work on your breathing skills for around 15 minutes a day. Start by taking deep breaths slowly, hold the breath for 10 seconds, then release.

2. Morning exercises

Spend around 20-30 minutes of your morning moving your body. You could do aerobics, yoga, walking, running, stretching, push ups, or anything that you like doing. The important thing is to move, relax, and strengthen your body and muscles.

3. Watch your eating habits

You have to make sure that you eat healthy food that is right for you as there is no health system that is good for everyone. People who are diabetic have to avoid eating lots of sweets and people who have high cholesterol must avoid eating red meat. Consult your doctor to find what kind of food is suitable for you.

You can start your day eating fruit and avoid eating fat and oily food. Make sure that you eat salad with your meals as salad provides the body with a lot of fiber which means you could lower your cholesterol, reduce your calories among other benefits.

4. Drink lots of water and liquids

Keep a bottle of water close to you all the time and drink water as much as possible to avoid dehydration. Drinking different kinds of juices is helpful as well. Drinking lots of water and drinking liquids are the key to stay dehydrated.

5. Positive thoughts

During the day, take a few minutes to clear your head from all the negative thoughts and focus only on positive thoughts and your future goals. Taking a few a minutes every day to relax and clear you head from all the negativity can do wonders.

Always remember what Mark Twain said, “And what is a man without energy? Nothing – nothing at all.”

Tag Cloud