Tuesday, November 5, 2013

Hibernate Questions

1.  What is Hibernate?
--------------------------
Hibernate is an object-relational mapping tool, a persistence framework.

2. What is ORM
---------------
Object-relational mapping of database tables to domain object classes. ORM resolve Object-Relational Impedance Mismatch sometime called paradigm mismatch viz

Inheritance:  RDBMSs do not define anything regarding this,  some databases do have subtype support but it is completely non-standardized.

Identity : RDBMS defines exactly one notion of 'sameness' the primary key, but oop defines both object identity (a==b) and object equality (a.equals(b)).

Associations : Associations can be represented as unidirectional/bidirectional in OOP whereas RDBMSs use the notion of foreign keys.

Data navigation : navigate from one association to an other walking the object network.RDBMS use JOINs.

3. Advantage Of ORM
--------------------
1. Productivity : Developers more concentrate on the business logic and increase the project’s productivity by  rid of writing complex and tedious SQL statement,

2. Maintainability :  helps to reduce the lines of code as a result more easier to refactor.

3. Portability : witching to other SQL database requires few changes in Hibernate configuration file.

4  Caching : Caching  feature  reduced round trips between an application and the database

4. What are the core interfaces of Hibernate framework?
--------------------------------------------------------
1. Session Interface:  Light weight and a non-threadsafe object that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and
closed when all work is complete.

2. SessionFactory interface: SessionFactory is threadsafe responsible for creating session on request from the application.  Usually an application has a single
SessionFactory instance

3. Configuration Interface: Allows the application to specify properties and mapping documents to be used when creating a SessionFactory.

4. Transaction Interface: provide support for JDBC transaction, JTA transaction.

Query and Criteria Interface : This interface allows the user to perform queries and also control the flow of the query execution.


5. Explain hibernate object states? Explain hibernate objects life cycle?
-------------------------------------------------------------------------
Transient : An object instantiated using the "new" operator which is not associated with any session in hibernate is said to be in Transient state.

Persistent : A persistent instance has a representation in the database and an identifier value. associated with any session.

Detached :  A detached instance is an object that has been persistent, but its Session has been closed hence no longer associated with a session.

life cycle:

When we create an object of our pojo class ,we can say it is in Transient state. At the time of Transient state any modification does not affect database table. If no longer referenced by any other object, it refer to garbage collection.

When you save transient object it enter into persistent state. Persistent instance has valid database table row with a primary key identifier .

The persistent object is still exist after closure of the active session is detached object. It is still represents to the valid row in the database. Can reattach detached

Removed State :
When the persistent object is deleted from the database. At this state java instance exist but any changes made to the object are not saved to the database.



6. When does an object become detached?
---------------------------------------------------
Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId);      //”myCar” is a persistent object at this stage.
session1.close();   

 it can be reattached to another session as shown below:

Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
session2.update(myCar);            //detached object ”myCar” gets re-attached
tx.commit();                       //change is synchronized with the database.
session2.close()



7. How does Hibernate distinguish between transient and detached objects?
-------------------------------------------------------------------------------------------
Hibernate uses the "version" property, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Write own strategy with Interceptor.isUnsaved().



8. What are the benefits of detached objects?
-----------------------------------------------------
Detached objects can be reattached to another session. need to make sure that the dependent objects are reattached as well.


9. What is the difference between sorted and ordered collection in hibernate?
-----------------------------------------------------------------------------
Sorted Collection is sorting a collection by utilizing the sorting  features provided by the Java collections framework using java comparator.

Order Collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.



10. What are the Collection types in Hibernate ?
----------------------------------------------------
Bag
Set
List
Array
Map


11. What is the difference between the session.get() method and the session.load() method?
---------------------------------------------------------------------------------------
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.


12.What is the difference between the session.update() method and the session.lock() method?
-----------------------------------------------------------------------------------------
Both update() and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database.Use session.lock() only if you are absolutely sure that the detached object is in sync.



13. How would you reattach detached objects to a session when the same object has already been loaded into the session?
-------------------------------------------------------------------------------------------------------------------
use the session.merge() method call.

14. What are different of caches in Hibernate
------------------------------------------------------
Hibernate uses two different caches

First-Level cache : Associated with the Session object. Hibernate uses this cache by default on per-transaction basis to reduce the  number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction.


Second-level cache : Associates with the Session Factory as result available to whole application rather than any particular session. Improve performance by saving few database round trip.By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.


 Hibernate configuration:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

15. How does the hibernate second-level cache work?
------------------------------------------------------------------
Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database.

16. What is query cache in Hibernate ?
----------------------------------------------
Query Cache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries.

Example:
final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);
       
 Hibernate configuration:
<property name="hibernate.cache.use_query_cache">true</property>       

17. What are the different  cache concurrency strategy:
---------------------------------------------------------------
Read-only : This strategy is useful for data that is read frequently but  never updated.

Read-write : appropriate if your  data needs to be updated. They carry more overhead than read-only  caches.

Nonstrict-read-write:  This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes

Transactional : This is a fully transactional cache that may be used only in a JTA environment.

18. What are the different fetching strategy in Hibernate :
---------------------------------------------------------------------

Join Fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select Fetching:  A second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy=”false”, this second select will only be executed when you access the association.

Subselect fetching: A second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifyinglazy=”false”, this second select will only be executed when you access the association.

Batch fetching: Using primary or foreign keys hibernate retrieves a batch of entity instances or collections in a single SELECT.

19. What do you understand by automatic dirty checking in Hibernate?
-----------------------------------------------------------------------------------
Dirty checking concept :
Dirty checking is a concept to avoid time consuming database write actions. By this concept, all necessary updating and changes are done without affecting the other fields.Only the changed fields of database are updated and the remaining unchanged fields are left untouched.

Hibernate Dirty Checking :

Hibernate allows dirty checking feature. It saves developer's time and effort in updating of database when states of objects are modified inside a transaction.Hibernate automatically detects the object states whenever changed and synchronized with the database in order to update.

20. What session.flush() do
------------------------------------
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database.By default, Hibernate will flush changes automatically

21. What is version checking in Hibernate ?
-----------------------------------------------------
Version checking used in hibernate when more then one thread trying to access same data.Optimistic locking using the version attribute

22. Optimistic vs. Pessimistic Locking
-------------------------------------------

Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check
reveals conflicting modifications, the committing transaction rolls back.

Pessimistic locking assumes that concurrent transactions will conflict with each other, and requires resources to be locked after they are read and only unlocked after the application has finished using the data.

23. Why it's important to provide no argument constructor in Hibernate Entities?
----------------------------------------------------------------------------
Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API,

24. Can we make an Hibernate Entity Class final?
--------------------------------------------------
Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy



25. What is HQL ?
----------------------
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database

26. What is lazy fetching in hibernate ? 
------------------------------------------
Lazy fetching is associated with child objects loading for its parents.  While loading the parent, the selection of loading a child object is to  be specified / mentioned in the hbm.xml file. Hibernate does not load  the whole child objects by default. Lazy=true means not to load the child objects.


27. What are derived properties?
--------------------------------------------
The properties that are not mapped to a column, but calculated and evaluated at runtime called derived properties.JPA doesn't offer any support for derived property

example
    @Formula("PRICE*1.155")
    private float finalPrice;
    @Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
    private Date firstOrderDate;
    or
   
    <property name="finalPrice"   formula="PRICE*1.155"   type="date" />
    <property name="firstOrderDate"   formula="select min(o.creation_date) from Orders o where o.customer_id = id"   type="date" />
   
   
28.  What are the ways to express joins in HQL?
--------------------------------------------------------
HQL provides four ways of  expressing (inner and outer) joins:-

An implicit association join : from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten

join in the FROM  clause : from Cat as cat  inner join fetch cat.mate  left join fetch cat.kittens child  left join fetch child.kittens

theta-style join in the WHERE clause.
    
29. What are the types of inheritance models  in Hibernate?
---------------------------------------------------------------------
There are three types of inheritance models in Hibernate:

Table per class hierarchy
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(    name=""discriminator"",    discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value=""P"")    

Table per subclass 
@Inheritance(strategy=InheritanceType.JOINED)     

Table per concrete class
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

EJB Most Wanted Questions

1. What is EJB?
-------------------
Enterprise JavaBeans (EJB) is the server-side component which runs on application server developed for the purpose of distributed and enterprise level application. Container/Server will provide support for system level services like Transaction Management, security which make developer task easy and he can focus on business logic.

2. What are the different types of EJB?
----------------------------------------------
There are 3 types of enterprise beans, namely: Session bean, Entity beans and Message driven beans.

Session bean :
A session bean represents a single client inside the Application Server. To access an application that is deployed on the server, the client invokes the session bean’s methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.

Two type of session bean:

 Stateless : A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s  instance variables may contain a state specific to that client, but only for the duration of the invocation. 

 Stateful: The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a   unique client-bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.The state is retained for  the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends there is no need to retain the state

 Message Driven Beans: these beans are work as a listener for messaging services like JMS .


 3. How EJB Invocation happens?
 ----------------------------------------
 Step 1: Retrieve Home Object reference from Naming Service via JNDI.
 step 2: Return Home Object reference to the client.
 step 3: Create me a new EJB Object through Home Object interface.
 step 4: Create EJB Object from the Ejb Object
 step 5: Return EJB Object reference to the client.
 step 6: Invoke business method using EJB Object reference.
 step 7: Delegate request to Bean (Enterprise Bean

 
 4. session bean life cycle callbacks  methods
 ------------------------------------------
 The EJB session bean life cycle methods are called by the EJB container to notify a session bean instance when specific life cycle events occur.

 ejbCreate():  Called just after the session bean instance is created. in response to a client calling create() on the bean's home interface.
 
 ejbRemove() : Called just before a session bean instance is permanently destroyed, in response to a client calling remove() on the bean's remote interface or on the bean's home interface
              
ejbPassivate() : Called just before the container passivated the bean by storing the bean data (typically serializing the bean) and removing the bean instance from memory. The container passivated a bean in order to conserve memory and other resources. The container is prepared, however, to reactivate the bean automatically as soon as it is needed again. 

ejbActivate() : Called just after the container has reactivated a bean that was previously passivated.
 
 5. EJB Entity Bean Life Cycle callbacks Methods
 -----------------------------------------------------------
  The EJB entity bean life cycle methods are called by the EJB container to notify an entity bean instance when specific life cycle events occur
 
ejbCreate() : Called just after the entity bean instance is created, in response to a client calling create on the bean's home interface. The return  PrimaryKeyType depends on the kind of persistence that is used:             
                Container-Managed Persistence -- returns null
                Bean-Managed Persistence -- returns the primary key for this bean instance.
 
ejbPostCreate() : Called after the entity bean is fully initialized. At this stage both the bean data and the primary key are initialized irrespective of whether container-managed or bean-managed persistence is used.
  
ejbRemove() :  Called just before an entity bean instance is permanently destroyed, in response to a client calling remove() on the bean's remote interface or on the bean's home interface.   
  
ejbPassivate()  : Called just before the container passivates the bean by storing the bean data (typically serializing the bean) and removing the bean instance from memory.   
 
ejbActivate() :  Called just after the container has reactivated a bean that was previously passivated.
 
ejbLoad()  :  Load the entity bean state from the database. Typically, the container calls this method at the start of a transaction to ensure that the state of the bean in memory is synchronized with the state in the database.

ejbStore() :   Store the entity bean state in the database. Typically, the container calls this method at the end of a transaction to update the  bean state in the database.    

ejbFind() :  The ejbFind() methods need only be defined on the entity bean class.

setEntityContext : particularly for BMP
 
unsetEntityContext : particularly for BMP

   
6. Life Cycle of a Stateless Session Bean
--------------------------------------------------- 
Does not exist: In this state, the bean instance simply does not exist.

Ready state: When Server is first started, several bean instances are created and placed in the Ready pool. More instances might be created by the container as needed by the EJB container.

Brief :
Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb container create the instance of stateless session bean and call setSessionContext () and ejbCreate() method.Now the bean is ready to invoke business method on this.it will not maintain the state so remove () method is been called after completion of business method which in turns  call ejbRemove  and now its ready for  garbage collection.

              
7. Life Cycle of a Stateful Session Bean
----------------------------------------------
 Does not exist: In this state, the bean instance simply does not exist.

 Ready state: A bean instance in the ready state is tied to particular client and engaged in a conversation.

 Passive state: A bean instance in the passive state is passivated to conserve resource.

Brief :
Stateful session beans life cycle starts when  client call create() method.The container create the instance of session bean and call setSessionContext() and ejbCreate() method. Now the stateful session bean is ready to serve the client request after serving the request if it is not used after a long time container can move this bean to passive stage by calling the ejbPassivate() method. similarly when bean is in passive stage and client invoke the business method the container call ejbActivate() method to move bean from passive stage to active or ready stage. At the end of life cycle client call remove() method and container will call ejbRemove() method and bean is ready for


8. Life Cycle of an Entity Bean
-----------------------------------
Does not exist: In this state, the bean instance simply does not exist.

Pooled state : When WebLogic server is first started, several bean instances are created and placed in the pool. A bean instance in the pooled state is not tied to particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set.

Ready state: A bean instance in the ready state is tied to particular data, that is, it represents an instance of an actual business object.              
 
Brief :
First stage is Does Not Exist Stage then Container creates the instance of EJB and  call SetEntityContext() method  which will set all entity context to bean and now it will become available on pool,to get a particular identity of an EJB object it has to move from Pooled stage to ready stage which is done by calling the create () method which in turns call ejbCreate() and ejbPostCreate() method .There is another way by which directly entity bean can move to pooled stage to
ready stage that’s is call ejbActivate() method. now we are ready to invoke method of entity bean .After completion of method if we want to move again in pooled stage from ready stage we can call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method. At the end container remove the instance from pool and call unSetEntityContext().



9.  Message-Driven Bean Life Cycle callbacks Methods
---------------------------------------------------------------------
PostConstruct : The PostConstruct callback occurs after the container creates a new instance of MDB and before the first message listener method invocation on the bean

PreDestroy : The PreDestroy callback occurs before the bean is removed from the pool or destroyed.               

Brief :
A message-driven bean instance’s life starts when the container invokes newInstance on the message-driven bean class to create a new instance.Next, the container injects the bean’s MessageDrivenContext, if applicable, and performs any other dependency injection as specified by meta-data annotations on the bean class or by the deployment descriptor.The container then calls the bean’s PostConstruct lifecycle callback methods, if any.The message-driven bean instance is now ready to be delivered a message sent to its associated destination or endpoint by any client or a call from the container to a timeout callback method.When the container no longer needs the instance (which usually happens when the container wants to reduce the number of instances in the method-ready pool), the container invokes the PreDestroy lifecycle callback methods for it, if any. This ends the life of the message-driven bean instance.
 
 
10. What happens if remove( ) is never invoked on a session bean?
--------------------------------------------------------------------------------
In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.

11.  can we have static initializer Block in EJB.
--------------------------------------------------------
From Technical point view of java its correct but violation of specification. In EJB if we use static initializer block to initialize static field then EJB components are used in distributed environment mean run on different JVM then it will be a problem coz if we change or update the value in on environment then only the instance running on same JVM have new value. that’s why static blocks are avoided and also all static field should be final. and same thing we can
achieve in ejbCreate(), setSessionContext() or setEntityContext() methods.


12.Threading is possible in EJB?
----------------------------------------
 Not possible because EJBs are created and managed by container and if in ejbs we allow threading containers life cycle methods will be interrupted by us.

13. What about connection pooling feature of EJB container?
-------------------------------------------------------------------------
Connection pooling is one of the Advance feature of container which enhanced our application performance .Using connection pooling mechanism client are not required to create every time connection object to interact with database.Whenever a client request for a database connection then an instance is picked from the connection pool to get an access to database and when user complete with his work instance is returned to connection pool.

14. What are the transaction Attribute ?
------------------------------------------------
A transaction attribute controls the scope of a transaction. Transaction is group of operation should be performed either completely or none. transaction must  have ACID property(atomicity , consistency, integrity,durability) so transaction can be said completed if we commit on successful execution and rollback on  unsuccessful execution.

A transaction attribute can have one of the following values

Required : the container starts a new transaction before running the method.

RequiresNew : If the client is not associated with a transaction, the container starts a new transaction before running the method or if associated Suspends transaction and Starts a new transaction. After Delegates the call to the method Resumes the client’s transaction.

Mandatory :  If the client is running within a transaction then method executes within the client’s transaction. If the client is not associated with a transaction, the container throws the TransactionRequiredException.

NotSupported : If the client is running within a transaction then container suspends the client’s transaction

Supports : If the client is running within a transaction then method executes within the client’s transaction. If the client is not associated with a  transaction, then container does not start a new transaction before running the method.

Never : If the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException.



15.Difference Between ejbStore() and ejbLoad()?
------------------------------------------------------------
 ejbLoad method load or refresh the instance variable from the database. This method is called when it is necessary to synchronize the bean with data from the database

 ejbStore method writes the variables to the database.This method is called when it is necessary to synchronize the bean data with the database.


16 .Difference between JNDI , Initial , Session , Entity and Ejb Context.
----------------------------------------------------------------------------------------
JNDI context: provides mechanism to lookup resources on network.

Initial Context: it provides initial context to resources.

Session Context: is an EJBContext object provided by the EJB container. it has all the information available which is required to session bean

Entity Context :  is an EJBContext object provided by the EJB container. it has all the information available which is required to entiry bean


17. Transaction Management for EJBs
------------------------------------------------------
Container Managed Transactions - In this type, container manages the transaction states.

Bean Managed Transactions - In this type, developer manages the life cycle of transaction states.


18. Home ,Remote , Local interface
-------------------------------------------
Home Interface : home interface specifies how the server will create the bean, using the EJBCreate() method of the bean implementation.
Local Interface :  Allow clients to access bean if reside in same JVM,  pass parameter by reference
Remote Interface : Allow clients to access bean if reside in different JVM,  pass parameter by value

19. What Stubs and Skeletons
------------------------------------
 A stub is a proxy for a remote object that runs on the client computer. Stubs forward a client's remote method invocations and their associated arguments  to skeletons. he purpose of stub is marshalling the data. converting the java code in network oriented stream. stub classes needed by EJB applications are  generated dynamically at runtime when an EJB client needs them.

 A skeleton is a proxy for a remote object that runs on the server. converting the network oriented stream into java code.

 20 For session beans, we can use the SessionSynchronization interface. For entity beans, how do we have control over a transaction?
 ---------------------------------------------------------------------------------------------------------------------------------------
 SessionSynchronization interface is used by the Session beans to Synchronize the Instance variables after a rollback or after a commit operation,  because container does not have any other way to inform the bean of these operations.

 For Entity beans Container automatically calls the ejbLoad method that refreshed the values from the database.
 
21. Why is ejbFindByPrimaryKey mandatory?
------------------------------------------------------------
ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container.Purpose is to reduce duplication of bean.

22. Why do we have a remove method in both EJBHome and EJBObject?
----------------------------------------------------------------------------------------------
EJBHome version of the remove allow us to delete an entity bean without instantiating it
Remote interface version works on an entity bean that you have already instantiated.

23. What restrictions are imposed on an EJB?
---------------------------------------------------------------
1. An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed.
2. An enterprise Bean must not use thread synchronization.
3. An enterprise Bean must not use the AWT
4. An enterprise bean must not use the java.io package
5. An enterprise bean must not attempt to listen on a socket
6. The enterprise bean must not attempt to load a native library.
7. The enterprise bean must not attempt to manage threads.

24. Is it possible to share an HttpSession between a JSP and EJB?
-----------------------------------------------------------------------------------
 we can pass the HttpSession as parameter to an EJB method

Monday, November 4, 2013

Servlet JSP Interview Questions

1. What is a servlets?
Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.


2. What are the types of Servlet?There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of  GenericServlet and provides http protocol specific functionality.

3. Servlet life cycle 
There are four phases of servlet life cycle.
 

Servlet Class Loading – When container receives request for a servlet, it first loads the class into memory.

Servlet Class Initialization – Once the servlet class is loaded, container initializes the ServletContext object for the servlet and then invoke it’s init  method by passing servlet config object.
  
Request Handling – Once servlet is initialized, its ready to handle the client requests. For every client request, servlet container initiate a new thread and invokes the service() method by passing the request and response object reference.
  
Removal from Service – When container stops or we stop the application, servlet container destroys the servlet class by invoking it’s destroy() method.


4. What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:

public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()

5. What is meant by Pre-Initialization of Servlet?
When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify 1 in between the tag in the Web.xml file in order to pre-initialize your servlet

6. Servlet constructor?
We can put one but. But I don’t think its of any use because we won’t be initialize it.

7. What are the differences between HttpServlet and Generic Servlets?
GenericServlet is protocol independent implementation of Servlet interface. HttpServlet is HTTP protocol specific implementation.

8. What is ServletConfig object?
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

9. What is ServletContext object?
javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application,

We can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

10. What is difference between ServletConfig and ServletContext?
Some of the differences between ServletConfig and ServletContext are:

ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.

ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.

We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.

11. What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

There are two methods defined in this interface:
    void forward(ServletRequest request, ServletResponse response) – forwards the request from a
    servlet to another resource (servlet, JSP file, or HTML file) on the server.
   
    void include(ServletRequest request, ServletResponse response) – includes the content of a
    resource (servlet, JSP page, HTML file) in the response.

We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.


12. What is difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.

We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

13. What is Servlet Chaining?
Servlet Chaining is a method where the output of one servlet is piped or passed onto a second servlet. The output of the second servlet could be passed on to a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

14. What is servlet lazy loading?
Lazy servlet loading means – the container does not initialize the servlets as soon as it starts up. Instead it initializes servlets when they receive their first ever request. This is the standard or default behavior. If you want the container to load your servlet at start-up then use pre-initialization using the load-on-startup element in the deployment descriptor.




15. What is the use of servlet wrapper classes?
Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper and HttpServletResponseWrapper.These wrapper classes are provided to help developers
with custom implementation of servlet request and response.

16. What is SingleThreadModel interface?
SingleThreadModel interface was provided for thread safety and it guarantees that not more then one threads will execute concurrently in the servlets service method. However SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time.

17. How to achieve thread safety in servlets?
HttpServlet init() method and destroy() method are called only once in servlet life cycle, so we don’t need to worry about their synchronization. But service  methods such as doGet() or doPost() are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.

If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread but if we have a  shared resource then we can use synchronization to achieve thread safety

18 . Diff between ServletResponse sendRedirect() and RequestDispatcher forward() method?

RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a   completely new request hence have to use session or url param for message passing.
  
forward() is handled internally by the container whereas sednRedirect() is handled by browser.

We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.

In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.
  
forward() can’t be used to invoke a servlet in other context, we can only use sendRedirect() in this case.

19. What is servlet filter?
Servlet Filters are pluggable java components use to intercept and process requests before they are sent to servlets and response before container sends back to the client.

Some common tasks that we can do with filters are:
1. Logging request parameters to log files.
2. Authentication and authorization of request for resources.
3. Formatting of request body or header before sending it to servlet.
4. Compressing the response data sent to the client.

20. what is servlet listener?
Servlet API provides Listener interfaces that we can implement and configure to listen for an event and do certain operations. Servlet API provides different types of Listener interfaces for Context, Session and Request that we can implement and configure in web.xml

21. What are different methods of session management in servlets?
Session is a conversational state between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

 Session management techniques available in servlets are:
1. HTML Hidden Field
2. Cookies
3. URL Rewriting

22. What are different ways for servlet authentication?
Servlet Container provides different ways of login based servlet authentication:

    HTTP Basic Authentication
    HTTP Digest Authentication
    HTTPS Authentication
    Form Based Login:

23. How to invoke servlets in a different application?
 We can’t use RequestDispatcher to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse sendRedirect()

24. What are the different methods present in a HttpServlet?
The methods of HttpServlet class are :
doGet() - To handle the GET, conditional GET, and HEAD requests
doPost() - To handle POST requests
doPut() - To handle PUT requests
doDelete() - To handle DELETE requests
doOptions() - To handle the OPTIONS requests and
doTrace() - To handle the TRACE requests

Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively.


25. What are the advantages of Servlets over CGI programs?
Java Servlets have a number of advantages over CGI and other API's. Some are:

Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets.

Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs.

Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.

Also, in terms of Safety & Security Servlets are superior when compared to CGI.

26. Which HTTP method is non-idempotent?
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

27. What is the difference between GET and POST method?

GET is a safe method (idempotent) where POST is non-idempotent method.

We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.

GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.

GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.

28 What is MIME Type?
The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

29. What is URL Encoding?
URL Encoding is the process of converting data into CGI form so that it can travel across the network.URL Encoding strip the white spaces and replace special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String unicode) to encode a String.

30. What is different between web server and application server?
A web server responsibility is to handler HTTP request and response. Application Servers is web server with additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc.

31. What are common tasks performed by Servlet Container
Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of  container, we don’t need to build a server socket to listen for any request from web client, parse the request and generate response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.
                             
Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. Container also provides utility like JNDI for resource pooling and management

Multi-threading Support: Container creates new thread for every request to the servlet and provide them request and response objects to process. So servlets are not initialized for each request and saves time and memory.       
   
JSP Support: JSP compiled by container and converted to Servlet and then  container manages them like other servlets.

Deployment and Other : provides security configurations,support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.

32. How can we achieve transport layer security for our web application?
We can configure our servlet container to use SSL for message communication over the network..

33. What are the differences between a Servlet and an Applet?
Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser.

Applets have GUI interface but there is no GUI interface in case of Servlets.

Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations

34. What are important features of Servlet 3?
Servlet Annotations : java annotations to define a servlet, filter and listener servlets and init parameters

Web Fragments : we can have multiple modules in a single web application, all these modules should have web-fragment.xml file in META-INF directory.

Adding Web Components dynamically:  We can use ServletContext object to add servlets, filters and listeners programmatically.

Asynchronous Processing: Delegate the request processing to another thread rather than keeping the servlet thread busy.

35. What is JSP
Java Server Pages are an extension to the Java servlet technology. A JSP is translated into Java servlet before being run, and it processes HTTP requests and generates responses like any servlet.

A JSP page can have two types of data one is Template Data it is the static part of a jsp page other one is JSP Elements it is the dynamic part of a jsp page translated and executed by the server.

36. what is JSPF
JSP Fragments can be compared to server side includes. These fragments are not compiled on their own, They're designed to be statically included in another JSP file,

37. What is JSP Element :

There are three type of element Scripting,Directive,Standard Action.

Scripting Elements:
    JSP declaration tag: Define variables and Method. Statements should end with semi-colon
            Syntax:
             <%!  statement;  %>   or <jsp:declaration> statement; </jsp:declaration>    

    JSP Scriptlet tag : Declare or define any java code into jsp.
                Syntax:
                <% statement; %>  or <jsp:scriptlet>  Java code; </jsp:scriptlet>

    JSP expression tag : Use to display java values to the browser.
                  Syntax:
                  <%= statement %> or <jsp:expression> statement < /jsp:expression>

     Comment : Hidden comment <%-- --%>or HTML comment <!-- -->

Directive Element:
    Page Directive : used to specify attributes for the JSP page. Some attributes are language, import,
     session, pageEncoding.
     Syntax:
       <%@ page import="java.util.*" %> or <jsp:directive.page import="java.util.*" />

     Include Directive :   It allows to include source code (static resource) of a file inside a jsp file at
     the specified place at a translation time.Typically include files are used for headers, footers, tables
     and navigation that are common to multiple pages
                            Syntax:
                                    <%@ include file="/folder_name/file_name"%>
    TagLib directive : The taglib directive makes custom actions available in the page through the use
    of tag library.
Standard Action :
Actions are create, modify or use other objects. Unlike directives and scripting elements, JSP actions are coded using strict XML syntax form.
The standard action types are:

                (1)<jsp:param>

                (2)<jsp:include>

                (3)<jsp:forward>

                (4)<jsp:fallback>

                (5)<jsp:plugin>

                (6) <jsp:useBean>

                (7)<jsp:setProperty>

                (8)<jsp:getProperty>

38. What is the difference between < jsp : include page = ... > and < % @ include file = ... >? 

The jsp:include element is processed when a JSP page is executed.
The include directive is a static include is processed at compile time,no support for parameter pasing.

39.What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are injected by web container and contain information related to a particular request, page, and application.

The JSP implicit objects are:

application
config
exception
out
page
pageContext
request
response and
session

40. What are all the different scope values for the < jsp : useBean > tag?

Scopes are following:
a) page
b) request
c) session and
d) application

41. What are the life-cycle phases of a JSP?

Page translation: -  Page is parsed, and a java file which is a servlet is created.
Page compilation:  Page is compiled into a class file
Page loading :       This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.



42. What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.

c) jspDestroy(): The container calls this when its instance is about to destroyed.

The jspInit() and jspDestroy() methods can be overridden within a JSP page.



43. What do you understand by JSP translation?

JSP translation is an action that refers to the conversion of the JSP page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.


44. What is EL ?
expression language systax ${}

45. how does EL search for an attribute ?
EL parser searches the attribute in following order:
Page
Request
Session (if it exists)
Application
If no match is found for then it displays empty string.

46. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. every time you click on any link in the website URL rewriting require data transfer from and to the
server

47. What is session hijacking?
Session hijacking refers to the act of taking control of a user session with authentication. to prevent this use SSL/HTTPS or regeneration of session token or  session regenerate technique.

48. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. we can achieve this by
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

Friday, April 19, 2013

HOW CALL JAVA METHOD FROM ORACLE / Java Stored Procedure



Step-1: Create Java Project in eclipse. I use jdk  1.5 for oracle 11g.

Step-2: Form oracle we can call static method.  for the supported data type check this link . This link will be helpful to define parameter and return type. For the User Defined Data type we have  implement either the SQLData or CustomDatum interface.  

package com.abb.functions;

import java.sql.Array;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Dictionary;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
import com.abb.functions.out.model.BranchOpenDateOut;


public class BranchWrapper {
    public synchronized static String isValidBranch(String branchCode) {
        return "CBS";
    }

    public static Array parseToArray(String str, String delim) throws SQLException {
        OracleDriver ora = new oracle.jdbc.OracleDriver();
        Connection conn = ora.defaultConnection();
        OracleConnection oraConn = (OracleConnection) conn;
        Array arr = oraConn.createARRAY("STRINGARRAY", str.split(delim));
        return arr;
    }
   
    public synchronized static BranchOpenDateOut isBranchOpenDate(String branchCode) throws SQLException {

        BranchOpenDateOut e = new BranchOpenDateOut("BRANCHOPENDATEOUT", "KAMAL HOSSAIN");       
        return e;
    }   


}
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;

import oracle.jdbc.driver.OracleConnection;
import oracle.jpub.runtime.MutableStruct;
import oracle.sql.CustomDatum;
import oracle.sql.CustomDatumFactory;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
public BranchOpenDateOut  implements CustomDatum, CustomDatumFactory {
    public static final String _SQL_NAME = "
BranchOpenDateOut";
    public static final int _SQL_TYPECODE = oracle.jdbc.OracleTypes.STRUCT;

    MutableStruct _struct;

    static int[] _sqlType = {java.sql.Types.VARCHAR };

    static CustomDatumFactory[] _factory = new CustomDatumFactory[_sqlType.length];

    static final TRANSACTIONOUT _
BranchOpenDateOutFactory = new TRANSACTIONOUT();

    public static CustomDatumFactory getFactory() {
        return _
BranchOpenDateOutFactory ;
    }

    /* constructor */
    public TRANSACTIONOUT() {
        _struct = new MutableStruct(new Object[_sqlType.length], _sqlType,
                _factory);
    }

    /* CustomDatum interface */
    public Datum toDatum(OracleConnection c) throws SQLException {
        return _struct.toDatum(c, _SQL_NAME);
    }

    /* CustomDatumFactory interface */
    public CustomDatum create(Datum d, int sqlType) throws SQLException {
        if (d == null) {
            return null;
        }
        TRANSACTIONOUT o = new TRANSACTIONOUT();
        o._struct = new MutableStruct((STRUCT) d, _sqlType, _factory);
        return o;
    }

    /* accessor methods */
    public String getmResBrDt() throws SQLException {
        return (String) _struct.getAttribute(0);
    }

    public void setmResBrDt(String mResBrDt) throws SQLException {
        _struct.setAttribute(0, mResBrDt);
    }
  
         
}


Step-3: after compiling this project export it as jar.


Step-4 use following loadjava command
Loadjava –user schema xyz jar-location


Step-5: in oracle create a Wrapper based on the static method want to call from oracle.


CREATE or REPLACE
FUNCTION ISVALIDBRANCH(brCode VARCHAR2) RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'com.abb.functions.BranchWrapper.isValidBranch(java.lang.String) return java.lang.String';


CREATE or REPLACE
FUNCTION PARSETOARRAY (str IN VARCHAR2, delim IN VARCHAR2)
RETURN STRINGARRAY AS
LANGUAGE JAVA NAME 'com.abb.functions.BranchWrapper.parseToArray (java.lang.String, java.lang.String) return java.sql.Array';



CREATE or REPLACE
FUNCTION ISBRANCHOPENDATE(brCode VARCHAR2) RETURN BranchOpenDateOut AS
LANGUAGE JAVA NAME 'com.abb.functions.BranchWrapper.isBranchOpenDate2(java.lang.String) return com.abb.functions.out.model.BranchOpenDateOut';

We have to map BranchOpenDateOutin and  STRINGARRAY  oracle as Object


CREATE or REPLACE  TYPE BranchOpenDateOut AS OBJECT (
   mResBrDt VARCHAR2 (100)
)

CREATE or REPLACE type STRINGARRAY is table of varchar2(4000);

That it we have done now we are going to call JAVA METHODS from oracle.

DECLARE
  STR VARCHAR2(200);
  DELIM VARCHAR2(200);
  v_Return STRINGARRAY;
  v_Return2 ABBTEST.BRANCHOPENDATEOUT;
v_Return3 VARCHAR2(200);
BEGIN
 
-- call to  parseToArray method
  STR := 'A,B';
  DELIM := ',';

  v_Return := PARSETOARRAY(STR => STR, DELIM => DELIM );

FOR i IN v_Return.first .. v_Return.last LOOP
     DBMS_OUTPUT.PUT_LINE(v_Return(i));
END LOOP;

-- call to  isBranchOpenDate method
v_Return2 := ISBRANCHOPENDATE(BRCODE => BRCODE);
DBMS_OUTPUT.PUT_LINE(v_Return2.mResBrDt);
-- call to  isValidBranch method
v_Return3 := ISVALIDBRANCH(BRCODE => BRCODE);
DBMS_OUTPUT.PUT_LINE(v_Return3);

  
END;






Wednesday, April 25, 2012

Spring Annotations


Context Configuration Annotations :
These annotations are used by Spring to guide creation and injection of beans

@Required indicates that the affected bean property must be populated at configuration time Method
@Autowired Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. Constructor, Field,
Method
@Inject can be used in place of Spring's @Autowired. does not have a required property

@Qualifier @Qualifier which takes a string property to discriminate among multiple injection candidates and can be placed on annotations as well as types, fields, methods,
constructors, and parameters.
Field, Parameter,
Type,
Annotation Type
@Configurable Marks a class as eligible for Spring-driven configuration Type
@Order Annotation that defines ordering Type, Method,
Field
@Scope Specifies the scope of a bean, either singleton, prototype, request, session,or some custom scope. Type







Spring Java Configuration :

@Configuration Indicates that a class declares one or more Bean methods and may be processed by the Spring container to generate bean definitions Type
@Bean Indicates that a method produces a bean to be managed by the Spring container. Method
@Import allows for loading @Bean definitions from another configuration class: Type
@ExternalValue same as @Value annotation and use of Spring EL. Method,
Field
@ImportXml allows for loading bean definitions from another xml Type
@AnnotationDrivenConfig enable the @Autowired annotation Type
@ComponentScan Spring's @Service and @Repository stereotype annotations are each meta-annotated with Type
@AnnotationDrivenTx Like Spring XML's <tx:annotation-driven> element, @AnnotationDrivenTx expects the presence of a bean named transactionManager Type
@AspectJAutoProxy detects any@Aspect beans and generates proxies as appropriate to weave the advice methods in those aspectsagainst other beans in the containe Type
@MBeanExport equivalent to Spring XML's <context:mbean-export/> element, JavaConfig provides the @MBeanExport annotation. Type
@DependsOn Beans on which the current bean depends. Type
@Primary indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. methods
annotated with Bean.
@Lazy Indicates whether a bean is to be lazily initialized. Type
@ImportResource Like @Import Type,
Method
@Async Annotation that marks a method as a candidate for asynchronous execution. Can also be used at the type level, in which case all of the type's methods are considered as asynchronous. Type

Stereotyping Annotations :

These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration.

@Component Generic stereotype annotation for any Spring-managed component. Type
@Controller Stereotypes a component as a Spring MVC controller Type
@Repository Stereotypes a component as a repository. Also indicates that SQLExceptions thrown from the component’s methods should be translated into Spring DataAccessExceptions. Type
@Service Stereotypes a component as a service Type


Spring MVC Annotations:

These annotations were introduced in Spring 2.5 to make it easier to create Spring MVC applications,<context:component-scan> is required

@PathVariable Annotation which indicates that a method parameter should be bound to a URItemplate variable. Supported for RequestMapping annotated handler methods in Servlet environments. Parameter
@InitBinder Annotation that identifies methods which initialize the WebDataBinder which will be used for populating command and form object arguments of annotated handler methods. Method
@ModelAttribute @ModelAttribute is a Spring-MVC specific annotation used for preparing the model data. It is also used to define the command object that would be bound with the HTTP request data. The annotation works only if the class is a Controller class. ModelAttribute can be applied on both methods as well as method-parameters. It accepts an optional "value", which indicates the name of the attribute. If no value is supplied to the annotation, then the value would be defaulted to the return type name in case of methods and parameter type name in case of
method-parameters.

The way Spring processes this annotation is, Before invoking the handler method, Spring invokes all the methods that have @ModelAttribute annotation. It adds the data returned by these methods to a temporary Map object. The data from this Map would be added to the final Model after the execution of the handler method.Then it prepares to invoke the the handler method. To invoke this method, it has to resolve the arguments. If the method has a parameter with @ModelAttribute, then it would search in the temporary Map object with the value of @ModelAttribute. If it finds, then the value from the Map is used for the handler method parameter.It it doesn't find it in the Map, then it checks if there is a SessionAttributes annotation applied on the controller with the given value. If the annotation is present, then the object is retrieved from the session and used for the handler method parameter. If the session doesn't contain the object despite of the @SessionAttributes, then an error is raised.If the object is not resolved through Map or @SessionAttribute, then it creates an instance of the parameter-type and passes it as the handler method parameter. Therefore, for it to create the instance, the parameter type should be a concrete-class-type (interfaces or abstract class types would again raise an error).Once the handler is executed, the parameters marked with @ModelAttributes are added to the Model.
Parameter
Method
@RequestMapping Maps a URL pattern and/or HTTP method to a method or controller . Method, Type
@RequestParam Binds a request parameter to a method parameter. Parameter,
Method
@SessionAttributes Specifies that a model attribute should be stored in the session. Type
@RequestHeader Allows a method parameter to be bound to a request header Parameter
@CookieValue Allows a method parameter to be bound to the value of an HTTP cookie Parameter
@ExceptionHandler

Method


Spring Validation Annotation :

@NumberFormat This annotation allows either a number style or pattern to be specified Field
@DateTimeFormat format a java.util.Date as required Field
@NotNull

Field
@Size

Field
@Min

Field
@Valid The Validator instance invoked when a @Valid method argument is encountered may be configured Parameter


Spring Expression Language (SpEL) :

@Value
Declares transactional boundaries and rules on a bean and/or its methods.
Method, Type

Transaction Annotations :
require <tx:annotation-driven>

@Transactional
Declares transactional boundaries and rules on a bean and/or its methods.
Method, Type

Aspect Annotations :
<aop:aspectj-autoproxy> required

@Aspect Declares a class to be an aspect. Type
@After Declares a method to be called after a pointcut completes. Method
@AfterReturning Declares a method to be called after a pointcut returns successfully. Method
@AfterThrowing Declares a method to be called after a pointcut throws an exception. Method
@Around Declares a method that will wrap the pointcut. Method
@Before Declares a method to be called before proceeding to the pointcut. Method
@DeclareParents Declares that matching types should be given new parents,that is, it introduces new functionality into matching types. Static Field
@Pointcut the method serving as the pointcut signature must have a void return type. method must have an empty method body and must not have any throws clause .
upported Pointcut Designators are execution,within,this, target, args, @target, @args,@within,@annotation
Method


JMX Annotations :
<context:mbean-export/> required

@ManagedAttribute Used on a setter or getter method to indicate that the bean's property should be exposed as a MBean attribute Method
@ManagedNotification Indicates a JMX notification emitted by a bean. Type
@ManagedNotifications Indicates a JMX notifications emitted by a bean. Type
@ManagedOperation Specifies that a method should be exposed as a MBean operation. Method
@ManagedOperationParameter Used to provide a description for an operation parameter. Method
@ManagedOperationParameters Used to provide a descriptions for an operation parameter. Method
@ManagedResource Specifies that all instances of a class should be exposed a MBeans. Type


JSR-250 ANOTATION :

@Resource Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods Method,Field
@PostConstruct indicates a method to be invoked after a bean has been created and dependency injection is complete. Used to perform any initialization work necessary. Method
@PreDestroy Indicates a method to be invoked just before a bean is removed from the Spring context. Used to perform any cleanup work necessary. Method


Testing Annotations :

@AfterTransaction Used to identify a method to be invoked after a transaction has completed. Method
@BeforeTransaction Used to identify a method to be invoked before a transaction starts. Method
@ContextConfiguration Configures a Spring application context for a test. Type
@DirtiesContext Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes. Method
@ExpectedException Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown. Method
@IfProfileValue Indicates that the test class or method is enabled for a specific profile configuration. Type, Method
@NotTransactional Indicates that a test method must not execute in a transactional context. Method
@ProfileValueSourceConfiguration Identifies an implementation of a profile value source. The absence of this annotation cause profile values to be loaded from system properties Method
@Repeat Indicates that the test method must be repeated a specific number of times. Method
@Rollback Specifies whether or not the transaction for the annotated method should be rolled back or not. Method
@TestExecutionListeners Identifies zero or more test execution listeners for a test class. Type
@Timed Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail. Method
@TransactionConfiguration Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class. Type
@RunWith specifies the Spring configuration to load for this test fixture Type
@Test Indicate test Method


AWS Services

      1.         Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources).                   1....