Vous êtes sur la page 1sur 65

JAVA

OOPs (Object Oriented Programming System)


Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.

Collection of objects is called class. It is a logical entity. It is a template or


blueprint from which objects are created.

When one object acquires all the properties and behaviors of parent
object i.e. known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.

When one task is performed by different ways i.e. known as polymorphism.

Hiding internal details and showing functionality is known as abstraction. For


example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction .

Encapsulation in java is a process of binding code and data together into a


single unit
We can create a fully encapsulated class in java by making all the data members
of the class private. Now we can use setter and getter methods to set and get the
data in it. The Java Bean class is the example of fully encapsulated class.
Object based programming language follows all the features of OOPs except
Inheritance. JavaScript and VBScript are examples of object based programming
languages.

Polymorphism in java is a concept by which we can perform a single action by


different ways.
If you overload static method in java, it is the example of compile time
polymorphism.

Runtime polymorphism or Dynamic Method Dispatch is a process in which a


call to an overridden method is resolved at runtime rather than compile-time.
When type of the object is determined at compiled time (by the compiler), it is
known as static binding.

If there is any private, final or static method in a class, there is static binding.
When type of the object is determined at run-time, it is known as dynamic
binding.

Covariant Return Type


Before Java5, it was not possible to override any method by changing the return
type. But now, since Java5, it is possible to override method by changing the return
type if subclass overrides any method whose return type is Non-Primitive but it
changes its return type to subclass type. Let's take a simple example:

Advantage: Method overloading increases the readability of the program.

If a class has an entity reference, it is known as Aggregation. Aggregation


represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id,
name, emailId etc. It contains one more object named address, which contains its
own informations such as city, state, country, zipcode etc. as given below.

In such case, Employee has an entity reference address, so relationship is


Employee HAS-A address.
Advantage: For Code Reusability.
No, static method cannot be overridden. Because static method is bound with
class whereas instance method is bound with object. Static belongs to class area
and instance belongs to heap area.

Rules for instance initializer block:


There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is
created.
2. The instance initializer block is invoked after the parent class
constructor is invoked (i.e. after super () constructor call).
3. The instance initializer block comes in the order in which they appear.

A final variable that is not initialized at the time of declaration is known as blank
final variable.

A static final variable that is not initialized at the time of declaration is known as
static blank final variable. It can be initialized only in static block.

Overriding:

If any method is not visible in child class, if we create same method for overriding
it creates as new method.

If any method is visible then we have to maintain, increase visibility inheritance in


child class

We cannot override private methods, by accessing super class reference it gives not visible
CTE

Replacing private to default, protected, public it works fine with in package, outside
package default wont work.
Levels of access modifiers for overriding
Public Protected Default Private

By declaring super class method as static and child class as non-static it throws CTE This
instance method cannot override the static method from Super

Output: super class private method

If interface method throws any Exception its not mandatory to throw in an implemented
method, if implemented class method throws any exception its mandatory to have it in
interface method.

String Immutable Example: StringBuffer Mutable Example:


abcdef abcdef
abcdef abc

Runtime: Through NullPointerException

Collections:

List<Child> list = new ArrayList<Child>();--correct


List<Super> list = new ArrayList<Child>();--compile time error

Identifying duplicate objects for Set by using hashCode and equals

Sorting objects for list, using comparable

Collections.sort(list);
External Sorting:

Removing special characters:

This order was placed for QT3000 OK , without ^ it prints other than a-z0-9

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long,
Float, Double etc. In short, all the wrapper classes and String class is immutable.
We can also create immutable class by creating final class that have final data
members

StringBuffer is synchronized whereas StringBuilder is not synchronized.

No new objects are created if it exists already in string constant pool.

An interface in java is a blueprint of a class. It has static constants and abstract


methods only.
The interface in java is a mechanism to achieve fully abstraction. It is used to
achieve fully abstraction and multiple inheritance in Java.
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

A class that is declared with abstract keyword is known as abstract class in java. It
can have abstract and non-abstract methods (method with body).

By static import, we can access the static members of a class directly, there is no
to qualify it with the class name.

gc () is a daemon thread.gc() method is defined in System class that is used to


send request to JVM to perform garbage collection.

The purpose of the Runtime class is to provide access to the Java runtime system.

Wrapper classes are classes that allow primitive types to be accessed as objects.
Multithreading

Multithreading is a process of executing multiple threads simultaneously.

A thread is a lightweight subprocess.It is a separate path of execution. It is called


separate path of execution because each thread runs in a separate stack frame.

The java.lang.Thread.yield () method causes the currently executing thread


object to temporarily pause and allow other threads to execute.

yield() is supposed to do is make the currently running thread head back to


runnable to allow other threads of the same priority to get their turn.

sleep (): It is a static method on Thread class. It makes the current thread into the
"Not Runnable" state for specified amount of time. During this time, the thread
keeps the lock (monitors) it has acquired.

wait(): It is a method on Object class. It makes the current thread into the "Not
Runnable" state. Wait is called on a object, not a thread. Before calling wait()
method, the object should be synchronized, means the object should be inside
synchronized block. The call to wait() releases the acquired lock

The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.
The non-static join () method of class Thread lets one thread "join onto the end" of
another thread. If you have a thread B that can't do its work until another thread A
has completed its work, then you want thread B to "join" thread A. This means that
thread B will not become runnable until A has finished (and entered the dead
state).

wait () and notify () method should be called in synchronized block otherwise it


throws IllegalStateMonitorException

By using notify we can notify only one thread which is first went in to waiting state

By using notify all we can notify all threads which are in waiting state

The notify() is used to unblock one waiting thread whereas notifyAll() method is
used to unblock all the threads in waiting state.

Synchronization is the capability of control the access of multiple threads to any


shared resource.

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

Deadlock:
Deadlock is a situation when two threads are waiting on each other to release a
resource. Each thread waiting for a resource which is held by the other waiting

thread.

Exception

An exception is an event, which occurs during the execution of a program, that


disrupts the normal flow of the program's instructions.
An Error indicates that a non-recoverable condition has occurred that should not
be caught. Error, a subclass of Throwable, is intended for drastic problems, such as
OutOfMemoryError, which would be reported by the JVM itself.

Throw keyword is used to throw the exception manually. It is mainly used when
the program fails to satisfy the given condition and it wants to warn the
application.

Throws: When we are throwing any checked exception in a method and not
handling it, then we need to use throws keyword in method signature to let caller
program know the exceptions that might be thrown by the method. The caller
method might handle these exceptions or propagate it to its caller method using
throws keyword. We can provide multiple exceptions in the throws clause and it
can be used with main() method also.

The StackOverFlowError is an Error Object thorwn by the Runtime System when


it encounters that your application/code has ran out of the memory. It may occur in
case of recursive methods or a large amount of data is fetched from the server and
stored in some object. This error is generated by JVM.

ClassNotFoundException: ClassNotFoundException occurs when class loader


could not find the required class in class path. So, basically you should check your
class path and add the class in the class path.

NoClassDefFoundError: This is more difficult to debug and find the reason. This
is thrown when at compile time the required classes are present, but at run time
the classes are changed or removed or class's static initializes threw exceptions. It
means the class which is getting loaded is present in classpath, but one of the
classes which are required by this class, are either removed or failed to load by
compiler .So you should see the classes which are dependent on this class.

Now after compiling both the classes, if you delete Test1.class file, and run Test
class, it will throw
No. The static variables belong to the class are not the part of the state of the
object so they are not saved as the part of serialized object.

Java.io.InvalidClassException occurs in de serialization process.

Serialization is a process of writing the state of an object into a byte stream. It is


mainly used to travel object's state on the network. Deserialization is the process
of reconstructing the object from the serialized state.

When an object of a class is serialized, the class name and serial version UID are
written to the stream of bytes. When it's deserialized, the JVM checks if the serial
version UID read from the stream of bytes is the same as the one of the local class.
If they're not, it doesn't even try to deserialize the object, because it knows the
classes are incompatible.

Can subclass overriding method declare an exception if parent class method


doesn't throw an exception? Yes but only unchecked exception not checked.
Forwarding the exception object to the invoking method is known as exception
propagation.

ConcurrentHashMap:
o ConcurrentHashMap allows concurrent read and thread-safe update
operation.
o During update operation, ConcurrentHashMap only lock a portion of Map
instead of whole Map.
o Concurrent update is achieved by internally dividing Map into small portion
which is defined by concurrency level.
o Choose concurrency level carefully as a significant higher number can be
waste of time and space and lower number may introduce thread contention
in case writers over number concurrency level.
o All operations of ConcurrentHashMap are thread-safe.
o Since ConcurrentHashMap implementation doesn't lock whole Map, there is
chance of read overlapping with update operations like put() and remove().
In that case result returned by get() method will reflect most recently
completed operation from there start.
o Iterator returned by ConcurrentHashMap is weekly consistent, fail safe and
never throw ConcurrentModificationException. In Java.
o ConcurrentHashMap doesn't allow null as key or value.
o You can use ConcurrentHashMap in place of Hashtable but with caution as
CHM doesn't lock whole Map.
o During putAll() and clear() operations, concurrent read may only reflect
insertion or deletion of some entries.
putIfAbsent(key, value)

Design Patterns
Factory method: The method which is returning its own class object is called
factory method design pattern

Factory Patter: The process of developing a method which creates an object


based on input received to the method without exposing the creation logic to client
and referring the newly created object using a common interface/super class.

Abstract Factory patterns work around a super-factory which creates other


factories. This factory is also called as factory of factories.
In Abstract Factory pattern an interface is responsible for creating a factory of
related objects without explicitly specifying their classes. Each generated factory
can give the objects as per the Factory pattern.
Singleton pattern: The class which allows creating only one object per jvm is
known as singleton class.

Template method: The method which combines set of related methods in a


sequence to complete its task in sequential execution is known as template
method.
Business Delegate Pattern is used to decouple presentation tier and business
tier. It is basically use to reduce communication or remote lookup functionality to
business tier code in presentation tier code.

Delegate class is responsible for getting the business service object and to provide
access to Business Service methods.

The service locator design pattern is used when we want to locate various
services using JNDI lookup. Considering high cost of looking up JNDI for a service,
Service Locator pattern makes use of caching technique. For the first time a
service is required, Service Locator looks up in JNDI and caches the service object.
Further lookup or same service via Service Locator is done in its cache which
improves the performance of application to great extent.

The Transfer Object pattern (DTO) is used when we want to pass data with
multiple attributes in one shot from client to server. Transfer object is also known
as Value Object. Transfer Object is a simple POJO class having getter/setter
methods and is serializable so that it can be transferred over the network. It does
not have any behavior. Server Side business class normally fetches data from the
database and fills the POJO and send it to the client or pass it by value. For client,
transfer object is read-only. Client can create its own transfer object and pass it to
server to update values in database in one shot. Following are the entities of this
type of design pattern.

Data Access Object Pattern or DAO pattern is used to separate low level data
accessing API or operations from high level business services.
Facade pattern hides the complexities of the system and provides an interface to
the client using which the client can access the system.
This pattern involves a single class which provides simplified methods required by
client and delegates calls to methods of existing system classes.

Hibernate
Inheritance:

Table per class:


Table per subclass:
Table per concrete class:
Self-Join Mapping:
Self-Reference Many-to-Many relationship:
Getting Session Object:

Hibernate SessionFactory getCurrentSession() method returns the session bound


to the context. But for this to work, we need to configure it in hibernate
configuration file. Since this session object belongs to the hibernate context, we
dont need to close it. Once the session factory is closed, this session object gets
closed.

Hibernate SessionFactory openSession() method always opens a new session. We


should close this session object once we are done with all the database operations.
We should open a new session for each request in multi-threaded environment.

Hibernate uses Reflection API to create instance of Entity beans, usually when you
call get() or load() methods. The method Class.newInstance() is used for this and
it requires no-args constructor. So if you wont have no-args constructor in entity
beans, hibernate will fail to instantiate it and you will get HibernateException
Ordered list is better than sorted list because the actual sorting is done at
database level, that is fast and doesnt cause memory issues.

There are five collection types in hibernate used for one-to-many relationship
mappings Bag, Set, List, Array, Map.

Making Entity Class final: Hibernate use proxy classes for lazy loading of data,
only when its needed. This is done by extending the entity bean, if the entity bean
will be final then lazy loading will not be possible, hence low performance.

Hibernate implements a cache region for queries resultset that integrates closely
with the hibernate second-level cache.

Native SQL Query comes handy when we want to execute database specific
queries that are not supported by Hibernate API such as query hints or the
CONNECT keyword in Oracle Database.

Hibernate provides Named Query that we can define at a central location and
use them anywhere in the code. We can created named queries for both HQL and
Native SQL. Disadvantage hard to debug.

Hibernate provides Criteria API that is more object oriented for querying the
database and getting results. We cant use Criteria to run update or delete queries
or any DDL statements. Its only used to fetch the results from the database using
more object oriented approach.

Criteria API provides Projection that we can use for aggregate functions such
as sum(), min(), max() etc.
Criteria API can be used with ProjectionList to fetch selected columns only.
Criteria API can be used for join queries by joining multiple tables, useful
methods are createAlias(), setFetchMode() and setProjection()
Criteria API can be used for fetching results with conditions, useful methods
are add() where we can add Restrictions.
Criteria API provides addOrder() method that we can use for ordering the
results.

Hibernate uses proxy object to support lazy loading. Basically when you load
data from tables, hibernate doesnt load all the mapped objects. As soon as you
reference a child or lookup object via getter methods, if the linked entity is not in
the session cache, then the proxy code will go to the database and load the linked
object. It uses javassist to effectively and dynamically generate sub-classed
implementations of your entity objects.

Cascading Types:

None: No Cascading, its not a type but when we dont define any cascading
then no operations in parent affects the child.
ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist.
Basically everything
SAVE_UPDATE: Cascades save and update, available only in hibernate.
DELETE: Corresponds to the Hibernate native DELETE action, only in
hibernate.
DETATCH, MERGE, PERSIST, REFRESH and REMOVE for similar operations
LOCK: Corresponds to the Hibernate native LOCK action.
REPLICATE: Corresponds to the Hibernate native REPLICATE action.

Following steps are required to integrate Spring and Hibernate frameworks


together.

Add hibernate-entity manager, hibernate-core and spring-orm


dependencies.
Create Model classes and corresponding DAO implementations for database
operations. Note that DAO classes will use SessionFactory that will be
injected by Spring Bean configuration.
If you are using Hibernate 3, you need to configure
org.springframework.orm.hibernate3.LocalSessionFactoryBean or
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryB
ean in Spring Bean configuration file. For Hibernate 4, there is single class
org.springframework.orm.hibernate4.LocalSessionFactoryBean that should
be configured.
Note that we dont need to use Hibernate Transaction Management, we can
leave it to Spring declarative transaction management using @Transactional
annotation.

When Spring and Hibernate integration started, Spring ORM provided two helper
classes HibernateDaoSupport and HibernateTemplate. The reason to use them was
to get the Session from Hibernate and get the benefit of Spring transaction
management. However from Hibernate 3.0.1, we can use SessionFactory
getCurrentSession() method to get the current session and use it to get the spring
transaction management benefits. If you go through above examples, you will see
how easy it is and thats why we should not use these classes anymore.

One other benefit of HibernateTemplate was exception translation but that can be
achieved easily by using @Repository annotation with service classes, shown in
above spring mvc example. This is a trick question to judge your knowledge and
whether you are aware of recent developments or not.

Some of the design patterns used in Hibernate Framework are:

Domain Model Pattern An object model of the domain that incorporates


both behavior and data.
Data Mapper A layer of Mappers that moves data between objects and a
database while keeping them independent of each other and the mapper
itself.
Proxy Pattern for lazy loading
Factory pattern in SessionFactory

Key Points:

Always check the primary key field access, if its generated at the database
layer then you should not have a setter for this.
By default hibernate set the field values directly, without using setters. So if
you want hibernate to use setters, then make sure proper access is defined
as @Access(value=AccessType.PROPERTY).
If access type is property, make sure annotations are used with getter
methods and not setter methods. Avoid mixing of using annotations on both
filed and getter methods.
Use native sql query only when it cant be done using HQL, such as using
database specific feature.
If you have to sort the collection, use ordered list rather than sorting it using
Collection API.
Use named queries wisely, keep it at a single place for easy debugging. Use
them for commonly used queries only. For entity specific query, you can
keep them in the entity bean itself.
For web applications, always try to use JNDI DataSource rather than
configuring to create connection in hibernate.
Avoid Many-to-Many relationships, it can be easily implemented using
bidirectional One-to-Many and Many-to-One relationships.
For collections, try to use Lists, maps and sets. Avoid array because you
dont get benefit of lazy loading.
Do not treat exceptions as recoverable, roll back the Transaction and close
the Session. If you do not do this, Hibernate cannot guarantee that in-
memory state accurately represents the persistent state.
Prefer DAO pattern for exposing the different methods that can be used with
entity bean
Prefer lazy fetching for associations

Fetching Strategies:
There are four fetching strategies

1. fetch-join = Disable the lazy loading, always load all the collections and
entities.
2. fetch-select (default) = Lazy load all the collections and entities.
3. batch-size=N = Fetching up to N collections or entities, *Not record*.
4. fetch-subselect = Group its collection into a sub select statement.

fetch=select or @Fetch(FetchMode.SELECT)
This is the default fetching strategy. it enabled the lazy loading of all its related
collections.
Get parent data, while accessing get on child , for each parent data get child data
fetch=join or @Fetch(FetchMode.JOIN)
The join fetching strategy will disabled the lazy loading of all its related
collections.
Gets parent and child data using single query.
batch-size=10 or @BatchSize(size = 10)
It fetches parent records, and for child it gets based on size i.e, in (?,?,?) passing id
of parent

fetch=subselect or @Fetch(FetchMode.SUBSELECT)

This fetching strategy is enable all its related collection in a sub select statement

If we want specific columns that can be achieved by using

Multiple place projection in setProjection, for one column return is column type,
multiple Object array
Hibernate Save
As the method name suggests, hibernate save() can be used to save entity to
database. We can invoke this method outside a transaction, thats why I dont like
this method to save data. If we use this without transaction and we have
cascading between entities, then only the primary entity gets saved unless we
flush the session.

We should avoid save outside transaction boundary, otherwise mapped


entities will not be saved causing data inconsistency. Its very normal to
forget flushing the session because it doesnt throw any exception or
warnings.
Hibernate save method returns the generated id immediately; this is
possible because primary object is saved as soon as save method is
invoked.
If there are other objects mapped from the primary object, they gets saved
at the time of committing transaction or when we flush the session.
For objects that are in persistent state, save updates the data through
update query. Notice that it happens when transaction is committed. If there
are no changes in the object, there wont be any query fired. If you will run
above program multiple times, you will notice that update queries are not
fired next time because there is no change in the column values.
Hibernate save load entity object to persistent context, if you will update the
object properties after the save call but before the transaction is committed,
it will be saved into database.

Hibernate Persist
Hibernate persist is similar to save (with transaction) and it adds the entity
object to the persistent context, so any further changes are tracked. If the
object properties are changed before the transaction is committed or session is
flushed, it will also be saved into database.

Second difference is that we can use persist() method only within the boundary of
a transaction, so its safe and takes care of any cascaded objects.
Finally, persist doesnt return anything so we need to use the persisted object to
get the generated identifier value. Lets look at hibernate persist with a simple
program.

Hibernate saveOrUpdate
Hibernate saveOrUpdate results into insert or update queries based on the
provided data. If the data is present in the database, update query is executed.

We can use saveOrUpdate() without transaction also, but again you will face the
issues with mapped objects not getting saved if session is not flushed.

One important difference between save and saveOrUpdate is that it adds the
entity object to persistent context and track any further changes. Any further
changes are saved at the time of committing transaction, like persist.

Hibernate Merge
Hibernate merge can be used to update existing values, however this method
create a copy from the passed entity object and return it. The returned object is
part of persistent context and tracked for any changes, passed object is not
tracked. This is the major difference with merge() from all other methods. Lets
look at this with a simple program.

Spring

Inversion of Control (IOC) is the mechanism to achieve loose-coupling between


Objects dependencies. Responsibility of managing life cycle of object e.g. creating
object, setting there dependency etc. from application to framework

As the name implies Inversion of control means now we have inverted the control
of creating the object from our own using new operator to container or framework.
Now its the responsibility of container to create object as required.

There are two types of IoC containers. They are:


1. BeanFactory
2. ApplicationContext
The ApplicationContext interface is built on top of the BeanFactory interface. It
adds some extra functionality than BeanFactory such as simple integration with
Spring's AOP, message resource handling (for I18N), event propagation,
application layer specific context (e.g. WebApplicationContext) for web application.
So it is better to use ApplicationContext than BeanFactory.

The XmlBeanFactory is the implementation class for the BeanFactory interface.


To use the BeanFactory, we need to create the instance of XmlBeanFactory class as
given below:
The ClassPathXmlApplicationContext class is the implementation class of
ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as given
below:

Constructor Injection:
Inheriting Bean:
By using the parent attribute of bean, we can specify the inheritance relation
between the beans. In such case, parent bean values will be inherited to the
current bean.
Setter Injection:

There are many key differences between constructor injection and setter injection.

1. Partial dependency: can be injected using setter injection but it is not possible by
constructor. Suppose there are 3 properties in a class, having 3 arg constructor and
setters methods. In such case, if you want to pass information for only one property,
it is possible by setter method only.
2. Overriding: Setter injection overrides the constructor injection. If we use both
constructor and setter injection, IOC container will use the setter injection.
3. Changes: We can easily change the value by setter injection. It doesn't create a
new bean instance always like constructor. So setter injection is flexible than
constructor injection.

Autowiring feature of spring framework enables you to inject the object


dependency implicitly. It internally uses setter or constructor injection.

Autowiring can't be used to inject primitive and string values. It works with
reference only.
By using @Transactional, Spring manages transactions declaratively.
Methods are annotated with @Transactional , the Spring Hibernate transaction
manager creates the required transactions and the respective sessions.

For Annotations support , <context:annotation-config />

Spring MVC:

The Model encapsulates the application data and in general they will consist of
POJO.
The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
The Controller is responsible for processing user requests and building
appropriate model and passes it to the view for rendering.

1. After receiving an HTTP request, DispatcherServlet consults the


HandlerMapping to call the appropriate Controller.
2. The Controller takes the request and calls the appropriate service methods
based on used GET or POST method. The service method will set model data
based on defined business logic and returns view name to the
DispatcherServlet.
3. The DispatcherServlet will take help from ViewResolver to pick up the
defined view for the request.
4. Once view is finalized, The DispatcherServlet passes the model data to the
view which is finally rendered on the browser.

If you do not want to go with default filename as [servlet-name]-servlet.xml and


default location as WebContent/WEB-INF, you can customize this file name and
location by adding the servlet listener ContextLoaderListener in your web.xml file
as follows:

The [servlet-name]-servlet.xml file will be used to create the beans defined,


overriding the definitions of any beans defined with the same name in the global
scope.

The <context:component-scan...> tag will be use to activate Spring MVC


annotation scanning capability which allows to make use of annotations like
@Controller and @RequestMapping etc.
The InternalResourceViewResolver will have rules defined to resolve the view
names. As per the above defined rule, a logical view named hello is delegated to a
view implementation located at /WEB-INF/jsp/hello.jsp .

DispatcherServlet delegates the request to the controllers to execute the


functionality specific to it. The @Controller annotation indicates that a particular
class serves the role of a controller. The @RequestMapping annotation is used to
map a URL to either an entire class or a particular handler method.

The @Controller annotation defines the class as a Spring MVC controller. Here,
the first usage of @RequestMapping indicates that all handling methods on this
controller are relative to the /hello path. Next annotation
@RequestMapping(method = RequestMethod.GET) is used to declare the
printHello() method as the controller's default service method to handle HTTP GET
request. You can define another method to handle any POST request at the same
URL.

The value attribute indicates the URL to which the handler method is mapped and
the method attribute defines the service method to handle HTTP GET request.

annotation @ResponseBody, which tells Spring MVC that the String returned by
the method is the response to the request, it does not have to find view for this
string. So the retuning String will be send back to the browser as response and
hence the Ajax request will work.

JUnit:
Programmatic transaction management: This means that you have
manage the transaction with the help of programming. That gives you
extreme flexibility, but it is difficult to maintain.

Declarative transaction management: This means you separate


transaction management from the business code. You only use annotations
or XML based configuration to manage the transactions.

AOP:

Join point
Join point is any point in your program such as method execution, exception
handling, field access etc. Spring supports only method execution join point.

Advice
Advice represents an action taken by an aspect at a particular join point. There are
different types of advices:

Introduction
It means introduction of additional method and fields for a type. It allows you to
introduce new interface to any advised object.

Target Object
It is the object i.e. being advised by one or more aspects. It is also known as
proxied object in spring because Spring AOP is implemented using runtime proxies.

Aspect
It is a class that contains advices, joinpoints etc.

Interceptor
It is an aspect that contains only one advice.
AOP Proxy
It is used to implement aspect contracts, created by AOP framework. It will be a
JDK dynamic proxy or CGLIB proxy in spring framework.

Weaving
It is the process of linking aspect with other application types or objects to create
an advised object. Weaving can be done at compile time, load time or runtime.
Spring AOP performs weaving at runtime.

Spring AspectJ AOP implementation provides many annotations:


1. @Aspect declares the class as aspect.
2. @Pointcut declares the pointcut expression.
The annotations used to create advices are given below:
3. @Before declares the before advice. It is applied before calling the actual
method.
4. @After declares the after advice. It is applied after calling the actual method
and before returning result.
5. @AfterReturning declares the after returning advice. It is applied after
calling the actual method and before returning result. But you can get the
result value in the advice.
6. @Around declares the around advice. It is applied before and after calling
the actual method.
7. @AfterThrowing declares the throws advice. It is applied if actual method
throws exception.
JMS
By using browse method, we can get messages without ACK.

JMS Listener class:


Web Services
What is Web Services?

Web services are client and server applications that communicate over the
world wide webs HTTP
By using web services, applications can publish its functions to the rest of
the world.
Web services uses xml to code and to decode data, and SOAP to transport it
(using open protocols)

Uses of Web services?

Reusable application components, connect existing software

WSDL:

WSDL stands for Web services description language


It is written in xml and it describes web services and how to access them
It specifies the location of the service, arguments and operations(or
methods) of the services exposes
WSDL is a W3C recommendation
WSDL provides information about the structure of SOAP message to be sent
for invocation of different operations exposed by the web service

WSDL Elements:

Types: It describes the data types used by the web services. Data types are
usually specified by XML Schema

Binding: It describes how Web Service is bound to a protocol & how it is


accessible

Interface: It describes the operations available in the Web service i.e. methods

Service: It describes the endpoint of Web service & the address where the web
service can be reached

Endpoint: It describes the address of the web service

Message: It describes the data being exchanged between the web service
providers and consumers

PortType: It describes set of operations supported by one or more endpoints


UDDI:

UDDI stands for Universal Description, Discovery and Integration. It is a


directory service. Web services can register with a UDDI and make
themselves available through it for discovery
UDDI is a directory which storing information about web services

How can UDDI be Used

If the industry published an UDDI standard for flight rate checking and
reservation, airlines could register their services into an UDDI directory. Travel
agencies could then search the UDDI directory to find the airline's reservation
interface. When the interface is found, the travel agency can communicate with
the service immediately because it uses a well-defined reservation interface.

SOAP WEB SERVICE

SOAP stands for Simple Object Access Protocol


SOAP is a format for sending messages
SOAP is platform independent
SOAP is for communication between applications
SOAP is a communication protocol

SOAP provides a way to communicate between applications running on different


operating systems, with different technologies and programming languages.

Sample Example Using JAXWS


Sample WSDL file:
1. <?xml version="1.0" encoding="UTF-8"?>

2. <wsdl:definitions targetNamespace="http://webservices.javapostsforlearning.arpit.org" xm
lns:apachesoap="http://xml.apache.org/xml-soap" xmlns:imp
l="http://webservices.javapostsforlearning.arpit.org" xmlns:intf="http://webservices.javapost
sforlearning.arpit.org" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="htt
p://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

3. <!--WSDL created by Apache Axis version: 1.4


4. Built on Apr 22, 2006 (06:55:48 PDT)-->

5. <wsdl:types>

6. <schema elementFormDefault="qualified" targetNamespace="http://webservices.javapost


sforlearning.arpit.org" xmlns="http://www.w3.org/2001/XMLSchema">

7. <element name="sayHelloWorld">

8. <complexType>

9. <sequence>

10. <element name="name" type="xsd:string"/>

11. </sequence>

12. </complexType>

13. </element>

14. <element name="sayHelloWorldResponse">

15. <complexType>

16. <sequence>

17. <element name="sayHelloWorldReturn" type="xsd:string"/>

18. </sequence>

19. </complexType>

20. </element>

21. </schema>

22. </wsdl:types>

23. <wsdl:message name="sayHelloWorldRequest">

24. <wsdl:part element="impl:sayHelloWorld" name="parameters"/>

25. </wsdl:message>

26. <wsdl:message name="sayHelloWorldResponse">

27. <wsdl:part element="impl:sayHelloWorldResponse" name="parameters"/>

28. </wsdl:message>

29. <wsdl:portType name="HelloWorld">


30. <wsdl:operation name="sayHelloWorld">

31. <wsdl:input message="impl:sayHelloWorldRequest" name="sayHelloWorldRequest"/>

32. <wsdl:output message="impl:sayHelloWorldResponse" name="sayHelloWorldRespon


se"/>

33. </wsdl:operation>

34. </wsdl:portType>

35. <wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">

36. <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/htt


p"/>

37. <wsdl:operation name="sayHelloWorld">

38. <wsdlsoap:operation soapAction=""/>

39. <wsdl:input name="sayHelloWorldRequest">

40. <wsdlsoap:body use="literal"/>

41. </wsdl:input>

42. <wsdl:output name="sayHelloWorldResponse">

43. <wsdlsoap:body use="literal"/>

44. </wsdl:output>

45. </wsdl:operation>

46. </wsdl:binding>

47. <wsdl:service name="HelloWorldService">

48. <wsdl:port binding="impl:HelloWorldSoapBinding" name="HelloWorld">

49. <wsdlsoap:address location="http://localhost:8080/SimpleSOAPExample/services/Hel


loWorld"/>

50. </wsdl:port>

51. </wsdl:service>

52. </wsdl:definitions>
Generating Web service client code by using maven:
Marshalling & UnMarshalling

Can we modify the header and body parts of SOAP messages so that
some common operations like logging can be performed?

This can be achieved by using interceptors which intercept the message before
sending and receiving it. An interceptor can be written on the client or server
side and perform its job as defined in the code. These interceptors are known as
handlers in JAX-WS specification. There are SOAPHandlers and LogicalHandlers
which can do different processing on the server side and client side.

SOAP defines a standard communication protocol (set of rules) specification for


XML-based message exchange. SOAP uses different transport protocols, such as
HTTP and SMTP. The standard protocol HTTP makes it easier for SOAP model to
tunnel across firewalls and proxies without any modifications to the SOAP
protocol. SOAP can sometimes be slower than middleware technologies like
CORBA or ICE due to its verbose XML format.

REST describes a set of architectural principles by which data can be transmitted


over a standardized interface (such as HTTP). REST does not contain an
additional messaging layer and focuses on design rules for creating stateless
services. A client can access the resource using the unique URI and a
representation of the resource is returned. With each new resource
representation, the client is said to transfer state. While accessing RESTful
resources with HTTP protocol, the URL of the resource serves as the resource
identifier and GET, PUT, DELETE, POST and HEAD are the standard HTTP
operations to be performed on that resource.

REST fundamentals:

Everything in REST is considered as a resource.

Every resource is identified by an URI.

Uses uniform interfaces. Resources are handled using POST, GET, PUT,
DELETE operations which are similar to Create, Read, update and Delete
(CRUD) operations.

Be stateless. Every request is an independent request. Each request from


client to server must contain all the information necessary to understand
the request.

Communications are done via representations. E.g. XML, JSON

Security to Webservice:
Java: 1.6

Spring: 3.0.4
Hibernate: 3.3.1

JMS: 10.3

Web services: 2.2.6

Maven: 3.0.3

Oracle
Outer Joins
Outer joins is divided into left outer joins, right outer joins, and full outer
joins.
select * from employee left outer join location on employee.empID =
location.empID;
or
select * from employee left join location on employee.empID =
location.empID;
Inner Joins

The difference between an inner join and an outer join is that an inner join
will return only the rows that actually match based on the join predicate.

select * from employee inner join location on employee.empID =


location.empID
or
select * from employee, locationwhere employee.empID = location.empID

There are various type of joins. Like


=>Equi-Joins
=> Self-Join
=> Outer-Join
=> Semi-Join
=>Anti-Join
=> Cross-Join
Equi-join
It is a sql join where we use the equal sign as the comparison operator i.e
"=" between two tables.By default this join is inner-equi-join.
SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO;

Non-Equi Join:
A Non- Equi Join is a SQL Join where condition is established between table
using all comparison operators (>=, <=, <, >) can used except the equal
(=) .

SELECT * FROM EMPLOYEE E, SALARY_GRADE SD WHERE


E.SAL<=SD.LOWSAL

Self Joins:
A self means joining columns of a table to itself. It fetches record from
same table only and for that we have to mention table alias name twice
times.
SELECT * FROM EMP E1, EMP E2 WHERE E1.EMPNO=E2.MGR

Outer-Join

Outer join returns all records from one table and those records from
another table where meets joining condition.
There are three types of outer joins
=>Left Outer-join
=>Right outer-join
=>Full outer-join

SELECT * FROM EMP LEFT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;


SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO(+);

SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO


SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO

Full Outer-join
Full Outer-join is combination of left and right outer join.It returns both
match and unmatched row from both tables.
SELECT * FROM EMP FULL OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO(+)

Anti Join

Suppose there are two tables A and B Anti-join between two tables A AND B
returns rows from the table A, for which there are no corresponding rows in
the Table B. Anti-join is also a sub-query in which parent query doesn't
depend upon child query. Example1:List deptno. Dept name for all the
departments in which there are no employees in the department.

SELECT * FROM DEPT D WHERE NOT EXIST (SELECT * FROM EMP E WHERE
D.DEPTNO = E.DEPTNO)

Example2:There are two tables Emp1 and Emp2. Fetch the record those are
present in Emp1 not in Emp2
SELECT * FROM EMP1 MINUS SELECT * FROM EMP2

Semi-join

between two tables returns rows from table A ,where one or more matches
are found in table B.It is kown as Co-Related-Sub-query, Where parent
query depents upon Child query.

Example1:There are two tables Emp1 and Emp2. Fetch the record common
in Emp1 and emp2.
SELECT * FROM EMP1 INTERSECT SELECT * FROM EMP2
Example2:Select records from emp and Dept where Deptno of Emp matches
Deptno in Dept
SELECT * FROM EMP WHERE EMP.DEPTNO IN(SELECT DEPTNO FROM DEPT)
Cross Join

Cross join jenerally generate cross product between two table. Each row of
Table1 ,combined with each rows of Table2.

Example Generate cross join between Emp and Dept


SELECT * FROM EMP CROSS JOIN DEPT;
or
SELECT * FROM EMP,DEPT;

1. To fetch ALTERNATE records from a table. (EVEN NUMBERED)


select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from
emp);
2. To select ALTERNATE records from a table. (ODD NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from
emp);
3. Find the 3rd MAX salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where
e1.sal <= e2.sal);
select * from (
select e.*, row_number() over (order by sal desc) rn from emp e
)
where rn = 2;
4. Find the 3rd MIN salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where
e1.sal >= e2.sal);
5. Select FIRST n records from a table.
select * from emp where rownum <= &n;
6. Select LAST n records from a table
select * from emp minus select * from emp where rownum <= (select count(*) - &n
from emp);
7. List dept no., Dept name for all the departments in which there are no
employees in the department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where
a.deptno = b.deptno);
altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b where
a.deptno(+) = b.deptno and empno is null;
8. How to get 3 Max salaries ?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where
a.sal <= b.sal) order by a.sal desc;
9. How to get 3 Min salaries ?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where
a.sal >= b.sal);
10. How to get nth max salaries ?
select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b
where a.sal >= b.sal);
11. Select DISTINCT RECORDS from emp table.
select * from emp a where rowid = (select max(rowid) from emp b where
a.empno=b.empno);
12. How to delete duplicate rows in a table?
delete from emp a where rowid != (select max(rowid) from emp b where
a.empno=b.empno);
13. Count of number of employees in department wise.
select count(EMPNO), b.deptno, dname from emp a, dept b where
a.deptno(+)=b.deptno group by b.deptno,dname;
14. Suppose there is annual salary information provided by emp table.
How to fetch monthly salary of each and every employee?
select ename,sal/12 as monthlysal from emp;
15. Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;
16. Select all record from emp table where deptno=30 and sal>1500.
select * from emp where deptno=30 and sal>1500;
17. Select all record from emp where job not in SALESMAN or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');
18. Select all record from emp where ename in
'BLAKE','SCOTT','KING'and'FORD'.
select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');
19. Select all records where ename starts with S and its lenth is 6 char.
select * from emp where ename like'S____';
20. Select all records where ename may be any no of character but it
should end with R.
select * from emp where ename like'%R';
21. Count MGR and their salary in emp table.
select count(MGR),count(sal) from emp;
22. In emp table add comm+sal as total sal .
select ename,(sal+nvl(comm,0)) as totalsal from emp;
23. Select any salary <3000 from emp table.
select * from emp where sal> any(select sal from emp where sal<3000);
24. Select all salary <3000 from emp table.
select * from emp where sal> all(select sal from emp where sal<3000);
25.Select all the employee group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;
26.How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
27.How to retrive record where sal between 1000 to 2000?
Select * from emp where sal>=1000 And sal<2000
28. Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where emp.deptno=dept.deptno)
29. If there are two tables emp1 and emp2, and both have common record.
How can I fetch all the recods but common records only once?
(Select * from emp) Union (Select * from emp1)
30. How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
31. How can I retrive all records of emp1 those should not present in
emp2?
(Select * from emp) Minus (Select * from emp1)
32. Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) > 2

HTML
HTML also has six levels of headings, which use the elements <h1>, <h2>,
<h3>, <h4>, <h5>, and <h6> Big to small
The <hr> tag creates a line from the current position in the document to the right
margin and breaks the line accordingly.

<pre>
function testFunction( strText ){
alert (strText)
}
</pre>

<b>bold</b> bold
<i>italicized</i> italicized
<u>underlined</u> underlined
<strike>strikethrough</strike> strikethrough
<tt>monospaced</tt> monospaced
<sup>superscript</sup> superscript
<sub>subscript</sub> subscript
<big>big</big> big
<small>small</small> small
<em>emphasized</em> emphasized
<mark>marked</mark> marked
<strong>strong</strong> strong
<abbr title="Abhishek">Abhy</abbr>
<bdo dir="rtl">This text will go right to left.</bdo></p> This text will go right to left.

The <div> and <span> elements allow you to group together several elements
to create sections or subsections of a page.

<meta http-equiv="refresh" content="5" />

<ul> - An unordered list. This will list items using plain bullets.

<ol> - An ordered list. This will use different schemes of numbers to list your
items.

<dl> - A definition list. This arranges your items in the same way as they are
arranged in a dictionary.

<ul type="square">
<ul type="disc">
<ul type="circle">

<ul type="square">
<li>Beetroot</li> Beetroot
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
<ol type="1"> - Default-Case Numerals.
<ol type="I"> - Upper-Case Numerals.
<ol type="i"> - Lower-Case Numerals.
<ol type="a"> - Lower-Case Letters.
<ol type="A"> - Upper-Case Letters.

<a href="http://www.tutorialspoint.com" target="_self">Tutorials Point</a>


_blank Opens the linked document in a new window or tab.
_self Opens the linked document in the same frame.
_parent Opens the linked document in the parent frame.
_top Opens the linked document in the full body of the window.
targetframe Opens the linked document in a named targetframe.

<a href="mailto:abc@example.com?subject=Feedback&body=Message">
Send Feedback
</a>

<frameset rows="10%,80%,10%">
<frame name="top" src="/html/top_frame.htm" />
<frame name="main" src="/html/main_frame.htm" />
<frame name="bottom" src="/html/bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>

<table bgcolor="#f1f1f1" >

<table background="/images/html.gif" width="100%" height="100">

The <body> tag has following attributes which can be used to set different colors:

bgcolor - sets a color for the background of the page.

text - sets a color for the body text.

alink - sets a color for active links or selected links.

link - sets a color for linked text.

vlink - sets a color for visited links - that is, for linked text that you have already clicked
on.

The font tag is having three attributes called size, color, and face

<marquee>This is basic example of marquee</marquee>


<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="/html/script.js" type="text/javascript"/></script>

CSS

CSS Style Rule Syntax as follows:


selector { property: value }

Type selectors:
h1 {
color: #36CFFF;
}

Universal Selector:
*{
color: #000000;
}

Descendant selector:
Suppose you want to apply a style rule to a particular element only when it lies
inside a particular element.
ul em {
color: #000000;
}

Class selector:
.black {
color: #000000;
}
h1.black {
color: #000000;
}

ID Selector:
#elementid {
color: #000000;
}
h1# elementid {
color: #000000;
}

Child selectors:
body > p {
color: #000000;
}

Attribute Selector:
input[type="text"]{
color: #000000;
}

Embedded CSS:
<head>
<style type="text/css" media="..."> 2
Style Rules
............
</style>
</head>

Inline CSS:
<element style="...style rules...."> priority:1

External CSS:
<head>
<link type="text/css" href="..." media="..." /> 3
</head>

<@import "URL"; importing external css

The background-color property is used to set the background color of an element.

The background-image property is used to set the background image of an element.

The background-repeat property is used to control the repetition of an image in the background.

The background-position property is used to control the position of an image in the background.

The background-attachment property is used to control the scrolling of an image in the background.

The background property is used as shorthand to specify a number of other background properties.

The font-family property is used to change the face of a font.

The font-style property is used to make a font italic or oblique.

The font-variant property is used to create a small-caps effect.

The font-weight property is used to increase or decrease how bold or light a font appears.

The font-size property is used to increase or decrease the size of a font.

The direction property is used to set the text direction.


<p style="direction:rtl;">
This text will be renedered from right to left
</p>

The letter-spacing property is used to add or subtract space between the letters
that make up a word.
<p style="letter-spacing:5px;">
This text is having space between letters.
</p>

The word-spacing property is used to add or subtract space between the words
of a sentence.
<p style="word-spacing:5px;">
This text is having space between words.
</p>

The text-indent property is used to indent the text of a paragraph.


<p style="text-indent:1cm;">
This text will have first line indented by 1cm
and this line will remain at its actual position
this is done by CSS text-indent property.
</p>

<p style="text-decoration:underline;">
This will be underlined
</p>

<p style="text-transform:capitalize;">
This will be capitalized
</p>

<p style="white-space:pre;">This text has a line break


and the white-space pre setting tells the browser to honor it
just like the HTML pre tag.</p>

<p style="text-shadow:4px 4px 8px blue;">


If your browser supports the CSS text-shadow property,
this text will have a blue shadow.</p>

<style type="text/css">
a:link {color: #000000}
a:visited {color: #006600}
a:hover {color: #FFCC00}
a:active {color: #FF00CC}
</style>

<p style="visibility:hidden;">
This paragraph should not be visible.
</p>

Relative Positioning: Relative positioning changes the position of the HTML


element relative to where it normally appears. So "left:20" adds 20 pixels to the
element's LEFT position.

Absolute Positioning: An element with position: absolute is positioned at the


specified coordinates relative to your screen top left corner.
Fixed Positioning: Fixed positioning allows you to fix the position of an element to
a particular spot on the page - regardless of scrolling. Specified coordinates will be
relative to the browser window.

The: visited pseudo-class

<style type="text/css">

a:visited {color: #006600}

</style>

<a href="/html/index.htm">Click this link</a>

elements

p:first-line { text-decoration: underline; }

p.noline:first-line { text-decoration: none; }

<style tyle="text/css">

<!--

p { color: #ff0000 !important; }

p { color: #000000; }

-->

</style>

Here you have made p { color: #ff0000 !important; } mandatory, now this rule will
always apply even you have defined another rule p { color: #000000; }

JAVA SCRIPT

JavaScript allows you to work with three primitive data types:


Numbers eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value.

Page redirect
window.location="http://www.newlocation.com";

print window.print();

var book = new Object(); // Create the object


book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";

var fruits = new Array( "apple", "orange", "mango" );


var fruits = [ "apple", "orange", "mango" ];

getting form value : document.myForm.Name.value


document.getElementById(value);

setTimeout( function, duration) - This function calls function after duration


milliseconds from now.
setInterval(function, duration) - This function calls function after every
duration milliseconds.
clearTimeout(setTimeout_variable) - This function calls clears any timer set by
the setTimeout() functions.
AJAX:

Vous aimerez peut-être aussi