Friday, November 28, 2014

Monday, November 24, 2014

getoutputstream-has-already-been-called-for-this-response + Itext + PDF Writing

http://stackoverflow.com/questions/1776142/getoutputstream-has-already-been-called-for-this-response

Tuesday, November 18, 2014

Java Interview Questions

Object Oriented Programming (OOP)
Java is a computer programming language that is concurrent, class-based and object-oriented. The advantages of object oriented software development are shown below:
  • Modular development of code, which leads to easy maintenance and modification.
  • Reusability of code.
  • Improved reliability and flexibility of code.
  • Increased understanding of code.
Object-oriented programming contains many significant features, such as encapsulation, inheritance, polymorphism and abstraction. We analyze each feature separately in the following sections.
Encapsulation
Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:
  • The internal state of every objected is protected by hiding its attributes.
  • It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
  • It improves modularity by preventing objects to interact with each other, in an undesired way.
You can refer to our tutorial here for more details and examples on encapsulation.
Polymorphism
Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. A polymorphic type is a type whose operations can also be applied to values of some other type.
Inheritance
Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.
Abstraction
Abstraction is the process of separating ideas from specific instances and thus, develop classes in terms of their own functionality, instead of their implementation details. Java supports the creation and existence of abstract classes that expose interfaces, without including the actual implementation of all methods. The abstraction technique aims to separate the implementation details of a class from its behavior.
Differences between Abstraction and Encapsulation
Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object’s behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction.
Can you access non static variable in static context ? A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

What is Function Overriding and Overloading in Java ? Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

What is the difference between an Interface and an Abstract class ? Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common characteristics, but they differ in the following features:
  • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
  • A class may implement a number of Interfaces, but can extend only one abstract class.
  • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
  • Abstract classes can implement interfaces without even providing the implementation of interface methods.
  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
  • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
How HashMap works in Java ? A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.

What is the importance of hashCode() and equals() methods ? In Java, a HashMap uses the hashCode and equals methods to determine the index of the key-value pair and to detect duplicates. More specifically, the hashCode method is used in order to determine where the specified key will be stored. Since different keys may produce the same hash value, the equals method is used, in order to determine whether the specified key actually exists in the collection or not. Therefore, the implementation of both methods is crucial to the accuracy and efficiency of the HashMap.

What differences exist between HashMap and Hashtable ? Both the HashMap and Hashtable classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features:
  • A HashMap allows the existence of null keys and values, while a Hashtable doesn’t allow neither null keys, nor null values.
  • A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while a Hashtable is suitable for multi-threaded environments.
  • A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys.
  • The Hashtable class is considered to be a legacy class.
What is Comparable and Comparator interface ? List their differences. Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object. Java provides the Comparator interface, which contains two methods, called compare and equals. The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator

What is the difference between HashSet and TreeSet ? The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).

When is the finalize() called ? What is the purpose of finalization ? The finalize method is called by the garbage collector, just before releasing the object’s memory. It is normally advised to release resources held by the object inside the finalize method.
What is the difference between throw and throws ? The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.

What is meant by implicit objects and what are they ? JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.The following objects are considered implicit in a JSP page:
  • application
  • page
  • request
  • response
  • session
  • exception
  • out
  • config
  • pageContext

How is it possible for two String objects with identical values not to be equal under the == operator?

Answer:

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
What does it mean that a class or member is final?
Answer:
  • final – declare constant
  • finally – handles exception
  • finalize – helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the difference between the boolean & operator and the && operator?

Answer:

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

What do you understand by Synchronization?

Answer:

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption.
Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html
What is immutable object? Can you write immutable object?Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

What will happen if we put a key object in a HashMap which is already there ?
if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys
Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
*       Method overloading
*       Method overriding through inheritance
*       Method overriding through the Java interface

Difference between HashSet and TreeSet ?
HashSet
TreeSet
HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order.
TreeSet is under set i.e. it provides elements in a sorted order (acceding order).
We can add any type of elements to hash set.
We can add only similar types
of elements to tree set.
How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
Difference between HashMap and Hashtable ?
HashMap
Hashtable
HashMap lets you have null values as well as one null key.
HashTable does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).
The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized.
Hashtable is synchronized.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.
What is the Comparable interface ?
The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
       interface Comparable
where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the
compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
      int i = object1.compareTo(object2)
*       If object1 < object2: The value of i returned will be negative.
*       If object1 > object2: The value of i returned will be positive.
*       If object1 = object2: The value of i returned will be zero.

77.What are the differences between the Comparable and Comparator interfaces ?
Comparable
Comparato
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
t uses the compare() method.

int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going to be sorted.
A separate class can be created in order to sort the instances.
Only one sort sequence can be created.
Many sort sequences can be created.
It is frequently used by the API classes.
It used by third-party classes to sort instances.


Wednesday, November 12, 2014

Uncaught ReferenceError: $ is not defined error in jQuery or Query is not valid.

Change the order you're including your scripts (jQuery first): 






to 

Tuesday, November 11, 2014

JAVA INTERVIEW PREPARATION Links


  

http://programmerinterview.com/index.php/java-questions/java-introduction --> all java and db concepts basics explained well
  

  



  
  

  

  
  

http://www.javatpoint.com/java-tutorial --> basics of all…must read
  

  

  

http://javahungry.blogspot.com/2013/08/difference-between-comparable-and.html --> difference between comparable and comparator, equals method etc
  

  
  
  
  dy

  
  

  

  
  
  

  





 
 















  
  

  

















  

 




 




 


 


JAVA INTERVIEW QUESTIONS

http://www.javagyan.com/preparing-for-an-interview/hibernate-interview-questions
http://www.javalobby.org/java/forums/t104442.html
http://www.techfaq360.com/spring_interview_questions.jsp?qid=369


These are the following steps:

1)Load the driver
2)Define the Connection URL
3)Establish the Connection
4)Create a Statement Object
5)Execute a Query
6)Process the results
7)close the Connection

Before writing any code we need to import sql package by
import java.sql.*;
import javax.sql.*;

Load and register the driver by using class.forName()

Java provide 4 types of drivers
1.Jdbc-Odbc Bridge driver
2.native api driver
3.Intermediate database access server
4.Pure java dirver also called as thin driver .

Create a Connection by Connection interface.

Connection con=DriverManager.getConnection("jdbc:odbc:mydsn" "scott" "tiger");
jdbc is a protocol odbc is a sub protocol and mydsn is dsn name
scott is username and tiger is password

Create a Sql Statement by Statement interface.

there are 3 types of statements
We use all these statement in executing sql queries
1.statement -normal stmt
2.PreparedStatement-Precompiled Statement
3.callableStatement-call stored procedures.

Statement stmt=con.createStatement("query");

This is how data is retrieved from the Resultset
Resultset rs=stmt.executeQuery();

Statement has three methods by which we execute and update the data.
1.execute();insert
2.executeQuery();select
3.executeUpdate();update

at last we need to close all methods...
finally
{
try
{
con.close();
stmt.close();
rs.close();
}
catch(Exception e)
{
e.printStackTrace();
}


Garbage collection in java

1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static
   members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business
   logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of
   cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage
   collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of
   command line tuning.


Read more: http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html#ixzz33YCHwFfV


when to use Market interface

Marker Interface may or may not contain any methods. Usually, Marker interface doesnt have any methods. But its not always the case.
For eg, Comparable interface.. It is a Marker Interface but it do contain one method public abstract int compareTo(java.lang.Object);.

Marker interface is used to describe some ability for the Object.
Like when i mark some class as Serializable, it means that its instance can be serialised. Here, the object is getting ability to get serialised.
Same way for other Marker interfaces also.

Usually the name for Marker Interfaces end with able.. Like Serializable, Comparable, Throwable, etc..

When to use abstract class and interface in Java

Here are some guidelines on when to use an abstract class and when to use interfaces in Java:

An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.
If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface,
then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
Interfaces are a good choice when you think that the API will not change for a while.
Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.

diff between tomcat and websphere

Tomcat is not Web server, that is the difference   . It is servlet/JSP container. Roughly say: Tomcat doesn't suppurt EJB but websphere do.

Web SErver
A Web Server is software application that uses the HyperText Transfer Protocol. A Web Server is usually run on a computer that is connected to the Internet. There are many Web Server software applications, including public domain software from Apache, and commercial applications from Microsoft, Oracle, Netscape and others. A Web Server may host or provide access to Content and responds to requests received from Web browsers. Every Web Server has an IP address and usually a domain name

Example of Web Server
- Apache WebServer
- Apache Jakarta Tomcat

Application Server

An application server is a server program in a computer within a distributed network that provides the business logic for an application program.
The application server is frequently viewed as part of a three-tier application, consisting of a graphical user interface (GUI) server,
an application (business logic) server, and a database and transaction server.

Example of Application Server
- JBoss Application Server
- WebSphere Application Server
- WebLogic Application Server


how to build an jav appl

validation in struts

flow of struts and hibernate



It was more of an maintenance project with lots of enhancements coming by. But lately I had the oppurtunity
to work on an admin application from scratch which involved intergration of struts frameworks with
spring and hibernate. We used the best of the features of struts, spring and hibernate


http://stackoverflow.com/questions/3295496/what-is-a-java-bean-exactly


NOTES :-


If you've got a good grasp of HTML, CSS, and JavaScript, you have a leg up on many people who end up doing web development. The concepts behind JSP are very
similar to PHP. The quirks are different. A servlet is the name for a chunk of Java code that serves a request. That's it really. The whole original Struts
framework was a single servlet.

I would add Tomcat to your list of technologies to learn. It's the original Java Servlet Container implementation and happens to also be a fully featured
and rather popular web server. GlassFish is built on top of it. You can make a little web site with Tomcat and JSP (tutorial here or JSF) knowing just what
you know and spending a few hours going through tutorials. That way you can start where you are comfortable before stretching out. Then make a javax.servlet
.http.HttpServlet that writes "Hi

Hello World

" to the response object, list it in your Tomcat
web.xml and send an HTTP request it from a web browser. It's not rocket science. All Java web frameworks are variations on those two basic activities.

Keep in mind that the strength of Java for web applications is its reliability, maintainability, and performance. For the simple little site, PHP or
Ruby/Rails is simpler, but Java will scale as much as you want to go. I am not bowled over by any of the Java web frameworks. When you have a team of people
 working on a large web application, then a framework like Spring really shines. Spring is the most popular. When you have some familiarity with servlets
and JSP/JSF, then learn how Spring ties those together with a data model.

If you are making a blog or a content management system, maybe you can get away with a NoSQL "database." But I would make the case that NoSQL "databases"
are replacing the file system, rather than replacing traditional databases.

Contrary to what others have said, I think that JPA (Java Persistence API) which is based on Hibernate is a critical part of any large web application.
Hibernate/JPA is tricky and weird, but eventually worth the struggle. I would recommend you get a basic familiarity with SQL and JDBC (Java Database
Connectivity) before you tackle Hibernate/JPA. After you are comfortable with the world of Java objects, and the world of relational databases and SQL,
then you can learn JPA/Hibernate/ORM (Object to Relational Mapping) which connects the object world to the relational world.

I learned Hibernate with the printed book Hibernate In Action. This is a very helpful book, but difficult because each detail must be understood. There is
a newer book Java Persistence with Hibernate. The people who made Hibernate are brilliant and it is a great tool. JPA is actually based on it, though
Hibernate also implements JPA.

Though I only know Hibernate, I recommend you start with the JPA that ships with Java EE 5 and later (which is completely usable with Java SE 5 or
later - just add the necessary JAR files to your project). The people making JPA had the advantage that Hibernate had gone before, and people had struggled
with explaining Hibernate before, so the JPA folks were sowing in previously plowed fields. If you need a feature or performance that JPA does not have,
then switch to Hibernate, which may have a few extra bells/whistles. At least you'll understand all the concepts that way before getting bogged down in
Hibernate's details.

You have some of the most important skills already. Take the others one at a time and try not to get overwhelmed.


POJO --> Plain old java objects

http://www.java-tv.com/2013/05/28/annotation-based-dependency-injection-in-spring-3-and-hibernate-3-framework/
http://krams915.blogspot.in/2011/01/spring-mvc-3-hibernate-annotations.html
http://javapostsforlearning.blogspot.in/2012/09/struts-2-spring-3-integration-example.html
http://www.pressinganswer.com/2409668/why-do-we-always-put-hibernate-spring-and-strut-in-one-app
http://amit.softcaretech.in/blog/spring-interview-questions/ --> spring interview questions

***********http://subodh1287.blogspot.in/***** -- very important 3 years interview questions




Spring hibernate main points :-

Struts and Spring both are Model View Controller (MVC) based web application development framework. However Spring framework have much
more feature than struts for example IOC (inversion of Control) and moduler based, you can add only the required modules for your
application, this makes your application light. Hibernate is a Object Relational Mapping(ORM) framework for persisting your java objects
into a Database, hibernate makes CRUD operation much easier than the traditional way independent of the Database vendortruts is a framework for
implementing business based MVC architecture that simplifies the project maintenance. Similarly Spring is also a framework to implement the J2EE
applications with loose coupling.
Hibernate is an ORM tool to query database and it maps object oriented architecture with the database. It can work with spring, struts
and the other frameworks.

The thing to watch out for is the Spring integration. If you have been using Spring with Hibernate before, you will be using the
LocalSessionFactoryBean (or AnnotationSessionFactoryBean) for creating the SessionFactory. For hibernate 4
there is a separate one in its own package: org.springframework.orm. hibernate4 instead of org.springframework.orm. hibernate3.
The LocalSessionFactoryBean from the hibernate 4 package will do for both mapping files as well as annotated entities, so you only
need one for both flavors.


Spring is both Spring - the IOC container and Spring MVC - the web action framework. Struts is only a web action framework.
So if you prefer Struts over Spring MVC, but also want an IOC container, you will use Struts with Spring.

Additionally, Spring also provides declarative transaction management, a security framework, a set of JDBC helper classes, etc.,
that you might want to use in a Struts/Hibernate application.

people choose Hibernate for persistence and Spring IoC for dependency injection purpose.

For the View and Controller part of web application, a well known web mvc framework is Struts and Spring MVC. Spring itself is consists of many components, Spring IoC and Spring MVC is two of them. Spring MVC is an equivalent with Struts so you don't use them together. But it is ok to combine Struts and Spring IoC.


--------------------------------------------------------------------------------------------------------------------------------


Core Interfaces in Hibernate Framework.

1.Session interface
2.SessionFactory interface
3.Configuration interface
4.Transaction interface
5.Query and Criteria interfaces

1.Session interface:It is a single-threaded, short-lived object representing a conversation between the application and the persistent
store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
2.SessionFactory interface :The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory
for the whole application reated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that
Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
3.Configuration interface : This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the
application in order to specify the location of hibernate specific mapping documents.
4.Transaction interface : This is an optional interface but the above three interfaces are mandatory in each and every application. This
interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
5.Query and Criteria interfaces:  This interface allows the user to perform queries and also control the flow of the query execution.

----------------------------------------------------------------------------
http://spring.io/blog/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1

2.a) Spring configuration for Hibernate

Spring provides support for several versions of Hibernate, so you need to specify explicitly which version you're using.

With Hibernate 4:


...

     

If you were to work with Hibernate 3, you would have instead:


...



     

(the package path is different according to whether you wish to use Hibernate 3 or Hibernate 4)

When working with Hibernate, there are 2 common ways of writing your mapping: XML and annotations.

Spring-Hibernate 3 integration allows you to configure 2 kinds of SessionFactoryBean:

LocalSessionFactoryBean for xml mapping only
AnnotationSessionFactoryBean for xml mapping and/or Annotation-based mapping
With Spring 3.1 and Hibernate 4, things are now simpler: there is only one SessionFactoryBean called LocalSessionFactoryBean. It works with both annotation-based mapping and xml-based mapping.

If you followed those 2 steps carefully, you should have a running application already.

-----------------------------------------------------------------------------------------------

Exception handling in struts 2


/WEB-INF//login.jsp





-----------------------------------------------------------------


What are the benefits of using Spring?

It is lightweight in regards to size and transparency with the basic version of Spring Framework taking up around 2MB of space.
The inversion of control (IOC) allows for loose coupling.
The objects give their dependencies instead of creating or looking for dependent objects.
It is aspect oriented (AOP) and supports and enables cohesive development by separating application business logic from system services.
Spring contains and manages the life cycle and configuration of application objects.
MVC Framework provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks.
Spring has a transaction management interface that can scale down to a local transaction (using a single database, for example)
and scale up to global transactions (using JTA, for example).
Exception handling translates technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent,
unchecked exceptions.

Explain the different modules in Spring.

    The Core container module provides the fundamental functionality of the Spring framework. In this module, BeanFactory is the heart
    of any Spring-based application and the entire framework was built on the top of this module.

    The Application context module makes spring a framework and extends the concept of BeanFactory, providing support for
    internationalization (I18N) messages, application lifecycle events, and validation. It also supplies many enterprise services such
    JNDI access, EJB integration, remoting, and scheduling as well as providing support to other framework.

    The AOP module is used for developing aspects for the Spring-enabled application. Much of the support has been provided by the AOP
    Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata
    programming to Spring. Using Spring’s metadata support, you are able to add annotations to the source code that instructs Spring on
    where and how to apply aspects.

    The web module is built on the application context module and provides a context that is appropriate for web-based applications.
    This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic
    binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

    The object/relational mapping (ORM) module provides support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.
    The JDBC abstraction and DAO model allows you to keep the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module.

-------------------------

http://javaprogrammingtips4u.blogspot.in/2010/04/spring-integration-with-hibernate_23.html


Apr 23, 2010
Spring Integration with Hibernate
I was working on a nice web application that was using Spring, Hibernate, jquery and Apache velocity! The saddest fact was the reality that Spring was not properly integrated into Hibernate and transactions were not properly handled.

At last, after a detailed discussion on what would happen if such an application goes live, the spring has been integrated properly with Hibernate!
As soon as one starts integrating Hibernate with Spring, the various options would be

To use HibernateTemplate
To use HibernateDaoSupport
Use plain Hibernate with hibernate.cfg.xml (like what we have been using till date)
Autowire session factory as a bean in the daos

The Pros and Cons

Using HibernateTemplate
HibernateTemplate is a nice API from Spring for easy integration with hibernate. It mirrors all methods exposed to Hibernate session and proves to be handy!
Automatic session close and transaction participation proves to be the best part of this API. Additionally this is handy not only for the nice exception
translation but also helps a newbie who does not want to handle sessions or transactions by himself. But, with the advent of Hibernate 3.0.1, this API
(using HibernateTemplate.find and the like  - This includes defining private HibernateTemplate in the daos and setting the hibernate template while setting
the session factory in a setter method say setSessionFactory) just proves to be futile and it is highly recommended that it is better to handle the
sessionFactory by ourselves rather than clinging to Spring and depending on it for handling the sessions for us! As such, this proves to be the first level
of Spring and Hibernate integration and is a good option for a newbie!

Using HibernateDaoSupport
The process of writing SampleDaoImpl extends HibernateDaoSupport is not doubt a very good option. Here, we would then be using no callbacks and
session  = getSession(false) rather than setting the hibernate template via the session factory. This is emphatically a very remarkable API provided by Spring for integration with hibernate and is surely better than the option 1 discussed above since this allows throwing of checked exception within the data access code.
Using plain Hibernate with hibernate.cfg.xml
While this proves to be the mos traditional way of implementation, this is just for the hibernate fans. I am not for such an implementation since there is
no need for writing code as given below:

Session session = HibernateUtils.getSession();
try{
Transaction tx = session.beginTransaction();
session.save(Object o);//o is the incoming object to be persisted
tx.commit();
}
catch{
(Exception e)
//code to handle exception
}
finally{
session.close();

Using Autowiring of the SessionFactory
As far as i see, this is the best way of integrating spring with hibernate. This is not only the latest and the updated way of integration,
this proves to be the best solution for designing web application where the developer has a hold on the sessions and transactions though
Spring does this in its own way


xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">


   
   

   
        p:username="${jdbc.username}" p:password="${jdbc.password}" p:maxActive="${dbcp.maxActive}" p:maxIdle="${dbcp.maxIdle}" p:maxWait="${dbcp.maxWait}" />
   
        p:configurationClass="org.hibernate.cfg.AnnotationConfiguration" p:packagesToScan="webapp.model">
       
           
                ${hibernate.dialect}
                ${hibernate.show_sql}
                ${hibernate.format_sql}
                ${hibernate.generate_statistics}
           

       
       
   
   
  
         class="org.springframework.orm.hibernate3.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory"/>


The corresponding DAO class is as below
?
1
2
3
4
5
6
7
@Repository
@Transactional
public class SampleDaoImpl implements SampleDao {

  @Autowired
  SessionFactory sessionFactory;

-----------------------

http://www.methodsandtools.com/archive/archive.php?id=93 --> read through
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under
this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the
comments form for that would help me in getting back to you with the details you are in need of!



Struts2 Interview Questions


1.What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.
2.What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends
the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
3.What are the components of Struts?
Struts components can be categorize into Model, View and Controller: Model: Components like business logic /business processes and data are the part of model
. View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
4.What are the core classes of the Struts Framework?
Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. JavaBeans components for managing application state
and behavior. Event-driven development (via listeners as in traditional GUI development). Pages that represent MVC-style views; pages reference view roots via the JSF component tree.
5.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and
determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.
6.What is role of ActionServlet?
ActionServlet performs the role of Controller: Process user requests Determine what the user is trying to achieve according to the request Pull data from the model (if necessary) to be given to the appropriate view, Select the proper view to respond to the user Delegates most of this grunt work to Action classes Is responsible for initialization and clean-up of resources
7.What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.
8.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().

Q: How to create an action with Struts2?
Ans: Creating an action in Struts2 is very different from Struts1 in the sense that there is no mandatory requirement to extend a class from the struts
library.
A Java bean/POJO which has the private member variables and public getters and setters is sufficient to become a struts action class.
As far as execute() method of Struts1 is concerned, a method with return type of String is sufficient. The method name is to be specified in the struts.xml.
This change is done so that the testing of struts based application can be done easily.

Q: In struts.xml, what does the attribute "method" stands for in the "action" tag?
Ans: The method attribute tells the name of method to be invoked after setting the properties of the action class. This attribute can either hold the actual name of the method or the index of the result mapping.
For example:
/success.jsp /success.jsp

In both the examples, the method being invoked by Struts will be login with the signature as public String login()

----------------------------------------
http://www.mohanarun.com/interview-refresher-for-struts-spring-hibernate-soa-design-patterns/

Interview Refresher for Struts, Spring, Hibernate, SOA, Design patterns
Spring refresher for interview
Struts interview refresher
Hibernate interview questions
Answering basic questions and able to talk convincingly that ‘you know’ about Struts, Spring, Hibernate (three hot topics that most job openings ask for)
This post brings you up to speed by taking advantage of the ‘keyword-dropping’ technique that should work with most interviewers unless they try to pry your knowledge too deep. Keyword dropping method is where you make sentences with keywords and represent a convincing picture to the interviewer that you know what you are talking about, when in fact your knowledge is absolutely minimal. If you already know the stuff upside down, then there is no need to ‘keyword drop’, is there?
SOA:
SOA is like building blocks
modularly assembled and flexible, easily assembling, reconfigurable components
as opposed to ‘rigidly integrated’
makes change easier
Struts:
It is an open source web application framework for building
Servlet/JSP based web apps based on the MVC design paradigm.
It uses concepts like ActionServlet, Action class, ActionForm.
Struts validation framework
it uses xml config files validator-rules.xml and validation.xml
Xml filenames you should know
struts.xml
struts-config.xml is a link btwn the View and Model components
struts-config file contains important sections for form bean definition, global forward definition, action mapping definition, controller configuration and application resources definition.
struts plugins are configured using plug-in element. plugins extend the functionality of the struts framework. struts plugins are installed to an application by adding a jar file that contains a struts-plugin.xml file.
Struts 2.2.3 is latest version.
Architecture:
Request arrives
FilterDispatcher finds appropriate Action
Interceptors get applied
Method in Action executes
Result renders output.
ActionMapper: Provide a mapping btwn HTTP requests and action
invocation requests
Configuration files: web.xml in /WEB-INF/ = deployment descriptor
struts.xml (optional) /WEB-INF/classes/
ActionServlet, RequestProcessor, ActionForm,Action,ActionMapping and ActionForward in Controller category.
Controller:
ActionServlet intercepts HTTP request and handles it appropriately. It is the
‘struts controller’. It selects an appropriate Action and creates an instance if necessary and calls execute method. The return type of the execute method is ActionForward. The ActionForward instance describes where and how control should be forwarded, or null if the response has already been completed. (ActionMapping mapping.findForward(“testAction”);
View:
It contains utility classes – variety of custom tags (html, bean, logic) and JSP.
Types of actions:
ForwardAction
IncludeAction
DispatchAction
SwitchAction
LookupDispatchAction
How to prevent duplicate submission of the same form
- using struts tokens
Struts has 3 methods used for the token, saveToken() isTokenValid() and resetToken().
DynaActionForm means it has no associated Java class. Its JavaBeans properties are created by adding the “form-property” tag in struts config file.
What is a Struts Action class?
Action class acts as wrapper around business logic
provides an interface to the app’s Model layer.
It works btwn the View and Model layer.
transfers data from view layer to the specific business process layer and return processed data from business layer to the view layer.
An action works as an adapter btwn the contents of a HTTP request and the business logic that corresponds to it.
To use the Action, we need to subclass and overwrite the execute() method.
How to handle exceptions in Struts?
in two ways
declarative exception handling: define exception handling in struts-config.xml
or using ‘action’ tag.
Exception handling is defined using “exception” tag.
programmatic exception handling: try catch block
Hibernate:
Data access framework, an ORM solution
database independent, same code will work for all databases.
Advantages over JDBC
Hibernate is set of objects, you can treat TABLE as object.
Hibernate supports two levels of Cache.
You can disable the second-level cache. (cache.provider_class in the xml file)
Has built-in connection pool. (c3p0)
In xml file you can see all relations between tables.
Transaction mgmt
hibernate.cfg.xml
HQL (hibernate query language) is executed using session.createQuery
List empList = session.createQuery(” from Emp e”).list();
ScrollableResults rs = session.createQuery(“…”).scroll();
if (rs.next()) rs.get(0 1 2 etc)
Basically it is like manipulating the database using Java statements
rather than using SQL
Automatic Session context management
- SessionFactory,
- Session,
- Transaction
Spring:
a lightweight framework
AOP – enables behavior that would otherwise be scattered thru different methods to be modularized in a single place.
Integrates with Hibernate, iBatis, JDO etc.
Spring uses AOP under the hood to deliver important out-of-the-box
services such as declarative transaction mgmt
framework-agnostic data access.
Spring’s use of shared instances of multithreaded “controllers” is similar
to the approach of struts, but spring’s MVC web application framework is more
flexible, and integrates seamlessly with the Spring IoC container.
It can accommodate multiple view technologies like JSP, Velocity, Tiles, iText, POI.
Spring latest version is 3.
It makes common tasks easier using your own controllers – for form validation, data binding, submissions, and file uploads.
Design patterns:
How many categories of Java patterns are there?
Creational patterns, structural patterns, behavioral patterns
Creational patterns – creates objects for you, rather than having you instantiate objects directly.
Structural patterns – compose groups of objects into larger structures.
Behavioral patterns – define the communication btwn objects and control the flow.
Creational patterns:
Factory pattern – choose and return an instance of a class based on data you provide. simple decision making class that returns one of serveral possible subclasses of an abstract base class.
Abstract Factory pattern – return one of several groups of classes.
Builder pattern – assembles a number of objects to make a new object
Prototype pattern – copies or clones an existing class.
***
Singleton pattern – there is one and only one instance of an object and it is possible to obtain global access to that instance.
(example: window managers, print spoolers). getInstance() method.
lazy instantiation – create instance of singleton class only when it is called for first time.
eager instantiation – create the instance before it is needed.
constructor of singleton class is private.
How to make singleton class threadsafe? Just make your getInstance method synchronized.

------------------

http://latestjobz.org/files/documents/Spring_Interview_Questions.pdf                              // read through
http://www.mohanarun.com/interview-refresher-for-struts-spring-hibernate-soa-design-patterns/
http://www.techfaq360.com/spring_interview_questions.jsp?qid=357




What are the challenges you have envisaged for the role you have applied for and how do you intend to
overcome the same?

opening to various tech
incre knowledge bandwith wagon
co exist


Although money is an important factor, I am most interested in this opportunity because I think it gives me a good opportunity to work in your company
and also gives me good exposure and also represents a good match between your needs and my qualifications."

deliver more in the future..more value to the deliverables

indicate a range than the actual amount

“I can’t give you an exact figure now, but I am looking for something in the range of 7-9 lakhs per annum”. You can also say –
“I am looking for a raise of 20-40% over my existing salary”.

-----------------------------------------------------------------------------------------------------